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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1385  ! raeburn     4: # $Id: lonnet.pm,v 1.1384 2018/09/20 14:17:11 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
                     76: 
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);
                    240:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
                    241:         $uselocal = 1;
                    242:     }
1.1316    raeburn   243:     if (($context ne 'cgi') && ($uselocal)) {
1.1315    raeburn   244:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   245:         if ($distro eq '') {
                    246:             $uselocal = 0;
                    247:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   248:             if ($1 < 6) {
                    249:                 $uselocal = 0;
                    250:             }
1.1346    raeburn   251:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    252:             if ($1 < 12) {
                    253:                 $uselocal = 0;
                    254:             }
1.1315    raeburn   255:         }
                    256:     }
                    257:     if ($uselocal) {
1.1383    raeburn   258:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   259:     } else {
                    260:         $rep=&reply('servercerts',$lonhost);
                    261:     }
                    262:     my ($result,%returnhash);
                    263:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    264:         ($rep eq 'unknown_cmd')) {
                    265:         $result = $rep;
                    266:     } else {
                    267:         $result = 'ok';
                    268:         my @pairs=split(/\&/,$rep);
                    269:         foreach my $item (@pairs) {
                    270:             my ($key,$value)=split(/=/,$item,2);
                    271:             my $what = &unescape($key);
                    272:             $returnhash{$what}=&thaw_unescape($value);
                    273:         }
                    274:     }
                    275:     return ($result,\%returnhash);
                    276: }
                    277: 
1.993     raeburn   278: sub get_server_loncaparev {
1.1073    raeburn   279:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   280:     if (defined($lonhost)) {
                    281:         if (!defined(&hostname($lonhost))) {
                    282:             undef($lonhost);
                    283:         }
                    284:     }
                    285:     if (!defined($lonhost)) {
                    286:         if (defined(&domain($dom,'primary'))) {
                    287:             $lonhost=&domain($dom,'primary');
                    288:             if ($lonhost eq 'no_host') {
                    289:                 undef($lonhost);
                    290:             }
                    291:         }
                    292:     }
                    293:     if (defined($lonhost)) {
1.1073    raeburn   294:         my $cachetime = 12*3600;
                    295:         if (!$ignore_cache) {
                    296:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    297:             if (defined($cached)) {
                    298:                 return $loncaparev;
                    299:             }
                    300:         }
                    301:         my ($answer,$loncaparev);
                    302:         my @ids=&current_machine_ids();
                    303:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    304:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   305:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   306:                 $loncaparev = $1;
                    307:             }
                    308:         } else {
                    309:             $answer = &reply('serverloncaparev',$lonhost);
                    310:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    311:                 if ($caller eq 'loncron') {
                    312:                     my $protocol = $protocol{$lonhost};
                    313:                     $protocol = 'http' if ($protocol ne 'https');
                    314:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    315:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   316:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   317:                     unless ($response->is_error()) {
                    318:                         my $content = $response->content;
1.1081    raeburn   319:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   320:                             $loncaparev = $1;
                    321:                         }
                    322:                     }
                    323:                 } else {
                    324:                     $loncaparev = $loncaparevs{$lonhost};
                    325:                 }
1.1081    raeburn   326:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   327:                 $loncaparev = $1;
                    328:             }
1.993     raeburn   329:         }
1.1073    raeburn   330:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   331:     }
                    332: }
                    333: 
1.1074    raeburn   334: sub get_server_homeID {
                    335:     my ($hostname,$ignore_cache,$caller) = @_;
                    336:     unless ($ignore_cache) {
                    337:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    338:         if (defined($cached)) {
                    339:             return $serverhomeID;
                    340:         }
                    341:     }
                    342:     my $cachetime = 12*3600;
                    343:     my $serverhomeID;
                    344:     if ($caller eq 'loncron') { 
                    345:         my @machine_ids = &machine_ids($hostname);
                    346:         foreach my $id (@machine_ids) {
                    347:             my $response = &reply('serverhomeID',$id);
                    348:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    349:                 $serverhomeID = $response;
                    350:                 last;
                    351:             }
                    352:         }
                    353:         if ($serverhomeID eq '') {
                    354:             $serverhomeID = $machine_ids[-1];
                    355:         }
                    356:     } else {
                    357:         $serverhomeID = $serverhomeIDs{$hostname};
                    358:     }
                    359:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    360: }
                    361: 
1.1121    raeburn   362: sub get_remote_globals {
                    363:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   364:     my ($result,%returnhash,%whatneeded);
                    365:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   366:         foreach my $what (sort(keys(%{$whathash}))) {
                    367:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   368:             my ($response,$cached);
1.1121    raeburn   369:             unless ($ignore_cache) {
1.1125    raeburn   370:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   371:             }
                    372:             if (defined($cached)) {
1.1125    raeburn   373:                 $returnhash{$what} = $response;
1.1121    raeburn   374:             } else {
1.1125    raeburn   375:                 $whatneeded{$what} = 1;
1.1121    raeburn   376:             }
                    377:         }
1.1125    raeburn   378:         if (keys(%whatneeded) == 0) {
                    379:             $result = 'ok';
                    380:         } else {
1.1121    raeburn   381:             my $requested = &freeze_escape(\%whatneeded);
                    382:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   383:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    384:                 ($rep eq 'unknown_cmd')) {
                    385:                 $result = $rep;
                    386:             } else {
                    387:                 $result = 'ok';
1.1121    raeburn   388:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   389:                 foreach my $item (@pairs) {
                    390:                     my ($key,$value)=split(/=/,$item,2);
                    391:                     my $what = &unescape($key);
                    392:                     my $hashid = $lonhost.'-'.$what;
                    393:                     $returnhash{$what}=&thaw_unescape($value);
                    394:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   395:                 }
                    396:             }
                    397:         }
                    398:     }
1.1125    raeburn   399:     return ($result,\%returnhash);
1.1121    raeburn   400: }
                    401: 
1.1124    raeburn   402: sub remote_devalidate_cache {
1.1241    raeburn   403:     my ($lonhost,$cachekeys) = @_;
                    404:     my $items;
                    405:     return unless (ref($cachekeys) eq 'ARRAY');
                    406:     my $cachestr = join('&',@{$cachekeys});
                    407:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   408:     return $response;
                    409: }
                    410: 
1.1       albertel  411: # -------------------------------------------------- Non-critical communication
                    412: sub subreply {
                    413:     my ($cmd,$server)=@_;
1.838     albertel  414:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      415:     #
                    416:     #  With loncnew process trimming, there's a timing hole between lonc server
                    417:     #  process exit and the master server picking up the listen on the AF_UNIX
                    418:     #  socket.  In that time interval, a lock file will exist:
                    419: 
                    420:     my $lockfile=$peerfile.".lock";
                    421:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   422: 	sleep(0.1);
1.549     foxr      423:     }
                    424:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      425:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      426:     #
1.550     foxr      427:     #   We'll give the connection a few tries before abandoning it.  If
                    428:     #   connection is not possible, we'll con_lost back to the client.
                    429:     #   
                    430:     my $client;
                    431:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    432: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    433: 				      Type    => SOCK_STREAM,
                    434: 				      Timeout => 10);
1.869     albertel  435: 	if ($client) {
1.550     foxr      436: 	    last;		# Connected!
1.850     albertel  437: 	} else {
1.853     albertel  438: 	    &create_connection(&hostname($server),$server);
1.550     foxr      439: 	}
1.1289    damieng   440:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      441:     }
                    442:     my $answer;
                    443:     if ($client) {
1.704     albertel  444: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      445: 	$answer=<$client>;
                    446: 	if (!$answer) { $answer="con_lost"; }
                    447: 	chomp($answer);
                    448:     } else {
                    449: 	$answer = 'con_lost';	# Failed connection.
                    450:     }
1.1       albertel  451:     return $answer;
                    452: }
                    453: 
                    454: sub reply {
                    455:     my ($cmd,$server)=@_;
1.838     albertel  456:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  457:     my $answer=subreply($cmd,$server);
1.65      www       458:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  459:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       460:                 " $cmd to $server returned $answer</font>");
                    461:     }
1.1       albertel  462:     return $answer;
                    463: }
                    464: 
                    465: # ----------------------------------------------------------- Send USR1 to lonc
                    466: 
                    467: sub reconlonc {
1.891     albertel  468:     my ($lonid) = @_;
                    469:     if ($lonid) {
1.1295    raeburn   470:         my $hostname = &hostname($lonid);
1.891     albertel  471: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    472: 	if ($hostname && -e $peerfile) {
                    473: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    474: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    475: 					     Type    => SOCK_STREAM,
                    476: 					     Timeout => 10);
                    477: 	    if ($client) {
                    478: 		print $client ("reset_retries\n");
                    479: 		my $answer=<$client>;
                    480: 		#reset just this one.
                    481: 	    }
                    482: 	}
                    483: 	return;
                    484:     }
                    485: 
1.836     www       486:     &logthis("Trying to reconnect lonc");
1.1       albertel  487:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   488:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  489: 	my $loncpid=<$fh>;
                    490:         chomp($loncpid);
                    491:         if (kill 0 => $loncpid) {
                    492: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    493:             kill USR1 => $loncpid;
                    494:             sleep 1;
1.1295    raeburn   495:         } else {
1.12      www       496: 	    &logthis(
1.672     albertel  497:                "<font color=\"blue\">WARNING:".
1.12      www       498:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  499:         }
                    500:     } else {
1.836     www       501: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  502:     }
                    503: }
                    504: 
                    505: # ------------------------------------------------------ Critical communication
1.12      www       506: 
1.1       albertel  507: sub critical {
                    508:     my ($cmd,$server)=@_;
1.838     albertel  509:     unless (&hostname($server)) {
1.672     albertel  510:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       511:                " Critical message to unknown server ($server)</font>");
                    512:         return 'no_such_host';
                    513:     }
1.1       albertel  514:     my $answer=reply($cmd,$server);
                    515:     if ($answer eq 'con_lost') {
1.1295    raeburn   516: 	&reconlonc($server);
1.589     albertel  517: 	my $answer=reply($cmd,$server);
1.1       albertel  518:         if ($answer eq 'con_lost') {
                    519:             my $now=time;
                    520:             my $middlename=$cmd;
1.5       www       521:             $middlename=substr($middlename,0,16);
1.1       albertel  522:             $middlename=~s/\W//g;
                    523:             my $dfilename=
1.305     www       524:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    525:             $dumpcount++;
1.1       albertel  526:             {
1.448     albertel  527: 		my $dfh;
1.1359    raeburn   528: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  529: 		    print $dfh "$cmd\n"; 
                    530: 		    close($dfh);
                    531: 		}
1.1       albertel  532:             }
1.1288    damieng   533:             sleep 1;
1.1       albertel  534:             my $wcmd='';
                    535:             {
1.448     albertel  536: 		my $dfh;
1.1359    raeburn   537: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  538: 		    $wcmd=<$dfh>; 
                    539: 		    close($dfh);
                    540: 		}
1.1       albertel  541:             }
                    542:             chomp($wcmd);
1.7       www       543:             if ($wcmd eq $cmd) {
1.672     albertel  544: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       545:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  546:                 &logperm("D:$server:$cmd");
                    547: 	        return 'con_delayed';
                    548:             } else {
1.672     albertel  549:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       550:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  551:                 &logperm("F:$server:$cmd");
                    552:                 return 'con_failed';
                    553:             }
                    554:         }
                    555:     }
                    556:     return $answer;
1.405     albertel  557: }
                    558: 
1.755     albertel  559: # ------------------------------------------- check if return value is an error
                    560: 
                    561: sub error {
                    562:     my ($result) = @_;
1.756     albertel  563:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  564: 	if ($2 == 2) { return undef; }
                    565: 	return $1;
                    566:     }
                    567:     return undef;
                    568: }
                    569: 
1.783     albertel  570: sub convert_and_load_session_env {
                    571:     my ($lonidsdir,$handle)=@_;
                    572:     my @profile;
                    573:     {
1.917     albertel  574: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    575: 	if (!$opened) {
1.915     albertel  576: 	    return 0;
                    577: 	}
1.783     albertel  578: 	flock($idf,LOCK_SH);
                    579: 	@profile=<$idf>;
                    580: 	close($idf);
                    581:     }
                    582:     my %temp_env;
                    583:     foreach my $line (@profile) {
1.786     albertel  584: 	if ($line !~ m/=/) {
                    585: 	    return 0;
                    586: 	}
1.783     albertel  587: 	chomp($line);
                    588: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    589: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    590:     }
                    591:     unlink("$lonidsdir/$handle.id");
                    592:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    593: 	    0640)) {
                    594: 	%disk_env = %temp_env;
                    595: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    596: 	untie(%disk_env);
                    597:     }
1.786     albertel  598:     return 1;
1.783     albertel  599: }
                    600: 
1.374     www       601: # ------------------------------------------- Transfer profile into environment
1.780     albertel  602: my $env_loaded;
                    603: sub transfer_profile_to_env {
1.788     albertel  604:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    605:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       606: 
1.720     albertel  607:     if (!defined($lonidsdir)) {
                    608: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    609:     }
                    610:     if (!defined($handle)) {
                    611:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    612:     }
                    613: 
1.786     albertel  614:     my $convert;
                    615:     {
1.917     albertel  616:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    617: 	if (!$opened) {
1.915     albertel  618: 	    return;
                    619: 	}
1.786     albertel  620: 	flock($idf,LOCK_SH);
                    621: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    622: 		&GDBM_READER(),0640)) {
                    623: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    624: 	    untie(%disk_env);
                    625: 	} else {
                    626: 	    $convert = 1;
                    627: 	}
                    628:     }
                    629:     if ($convert) {
                    630: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    631: 	    &logthis("Failed to load session, or convert session.");
                    632: 	}
1.374     www       633:     }
1.783     albertel  634: 
1.786     albertel  635:     my %remove;
1.783     albertel  636:     while ( my $envname = each(%env) ) {
1.433     matthew   637:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    638:             if ($time < time-300) {
1.783     albertel  639:                 $remove{$key}++;
1.433     matthew   640:             }
                    641:         }
                    642:     }
1.783     albertel  643: 
1.619     albertel  644:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  645:     $env_loaded=1;
1.783     albertel  646:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   647:         &delenv($expired_key);
1.374     www       648:     }
1.1       albertel  649: }
                    650: 
1.916     albertel  651: # ---------------------------------------------------- Check for valid session 
                    652: sub check_for_valid_session {
1.1355    raeburn   653:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  654:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   655:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    656:     if ($name eq 'lonDAV') {
                    657:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    658:     } else {
                    659:         $lonidsdir=$r->dir_config('lonIDsDir');
                    660:         if ($name eq '') {
                    661:             $name = 'lonID';
                    662:         }
                    663:     }
                    664:     if ($name eq 'lonID') {
                    665:         $secure = 'lonSID';
1.1337    raeburn   666:         $linkname = 'lonLinkID';
                    667:         $pubname = 'lonPubID';
1.1378    raeburn   668:         if (exists($cookies{$secure})) {
                    669:             $lonid=$cookies{$secure};
                    670:         } elsif (exists($cookies{$name})) {
                    671:             $lonid=$cookies{$name};
                    672:         } elsif (exists($cookies{$linkname})) {
1.1337    raeburn   673:             $lonid=$cookies{$linkname};
1.1378    raeburn   674:         } elsif (exists($cookies{$pubname})) {
                    675:             $lonid=$cookies{$pubname};
1.1337    raeburn   676:         }
1.1378    raeburn   677:     } else {
                    678:         $lonid=$cookies{$name};
1.1337    raeburn   679:     }
1.916     albertel  680:     return undef if (!$lonid);
                    681: 
                    682:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   683:     if (-l "$lonidsdir/$handle.id") {
                    684:         my $link = readlink("$lonidsdir/$handle.id");
                    685:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    686:             $handle = $1;
                    687:         }
1.1155    raeburn   688:     }
1.1355    raeburn   689:     if (!-e "$lonidsdir/$handle.id") {
                    690:         if ((ref($domref)) && ($name eq 'lonID') && 
                    691:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    692:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    693:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    694:                 $$domref = $possudom;
                    695:             }
                    696:         }
                    697:         return undef;
                    698:     }
1.916     albertel  699: 
1.917     albertel  700:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    701:     return undef if (!$opened);
1.916     albertel  702: 
                    703:     flock($idf,LOCK_SH);
                    704:     my %disk_env;
                    705:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    706: 	    &GDBM_READER(),0640)) {
                    707: 	return undef;	
                    708:     }
                    709: 
                    710:     if (!defined($disk_env{'user.name'})
                    711: 	|| !defined($disk_env{'user.domain'})) {
                    712: 	return undef;
                    713:     }
1.1245    raeburn   714: 
                    715:     if (ref($userhashref) eq 'HASH') {
                    716:         $userhashref->{'name'} = $disk_env{'user.name'};
                    717:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   718:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   719:         if ($userhashref->{'lti'}) {
                    720:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    721:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    722:         }
1.1212    raeburn   723:     }
1.1245    raeburn   724: 
1.916     albertel  725:     return $handle;
                    726: }
                    727: 
1.830     albertel  728: sub timed_flock {
                    729:     my ($file,$lock_type) = @_;
                    730:     my $failed=0;
                    731:     eval {
                    732: 	local $SIG{__DIE__}='DEFAULT';
                    733: 	local $SIG{ALRM}=sub {
                    734: 	    $failed=1;
                    735: 	    die("failed lock");
                    736: 	};
                    737: 	alarm(13);
                    738: 	flock($file,$lock_type);
                    739: 	alarm(0);
                    740:     };
                    741:     if ($failed) {
                    742: 	return undef;
                    743:     } else {
                    744: 	return 1;
                    745:     }
                    746: }
                    747: 
1.5       www       748: # ---------------------------------------------------------- Append Environment
                    749: 
                    750: sub appenv {
1.949     raeburn   751:     my ($newenv,$roles) = @_;
                    752:     if (ref($newenv) eq 'HASH') {
                    753:         foreach my $key (keys(%{$newenv})) {
                    754:             my $refused = 0;
                    755: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    756:                 $refused = 1;
                    757:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   758:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   759:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    760:                         $refused = 0;
                    761:                     }
                    762:                 }
                    763:             }
                    764:             if ($refused) {
                    765:                 &logthis("<font color=\"blue\">WARNING: ".
                    766:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    767:                          .'</font>');
                    768: 	        delete($newenv->{$key});
                    769:             } else {
                    770:                 $env{$key}=$newenv->{$key};
                    771:             }
                    772:         }
1.1376    raeburn   773:         my $lonids = $perlvar{'lonIDsDir'};
                    774:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    775:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    776:             if ($opened
                    777: 	        && &timed_flock($env_file,LOCK_EX)
                    778: 	        &&
                    779: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    780: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    781: 	        while (my ($key,$value) = each(%{$newenv})) {
                    782: 	            $disk_env{$key} = $value;
                    783: 	        }
                    784: 	        untie(%disk_env);
                    785:             }
1.35      www       786:         }
1.191     harris41  787:     }
1.56      www       788:     return 'ok';
                    789: }
                    790: # ----------------------------------------------------- Delete from Environment
                    791: 
                    792: sub delenv {
1.1104    raeburn   793:     my ($delthis,$regexp,$roles) = @_;
                    794:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    795:         my $refused = 1;
                    796:         if (ref($roles) eq 'ARRAY') {
                    797:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    798:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    799:                 $refused = 0;
                    800:             }
                    801:         }
                    802:         if ($refused) {
                    803:             &logthis("<font color=\"blue\">WARNING: ".
                    804:                      "Attempt to delete from environment ".$delthis);
                    805:             return 'error';
                    806:         }
1.56      www       807:     }
1.917     albertel  808:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    809:     if ($opened
1.915     albertel  810: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  811: 	&&
                    812: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    813: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  814: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   815: 	    if ($regexp) {
                    816:                 if ($key=~/^$delthis/) {
                    817:                     delete($env{$key});
                    818:                     delete($disk_env{$key});
                    819:                 } 
                    820:             } else {
                    821:                 if ($key=~/^\Q$delthis\E/) {
                    822: 		    delete($env{$key});
                    823: 		    delete($disk_env{$key});
                    824: 	        }
                    825:             }
1.448     albertel  826: 	}
1.783     albertel  827: 	untie(%disk_env);
1.5       www       828:     }
                    829:     return 'ok';
1.369     albertel  830: }
                    831: 
1.790     albertel  832: sub get_env_multiple {
                    833:     my ($name) = @_;
                    834:     my @values;
                    835:     if (defined($env{$name})) {
                    836:         # exists is it an array
                    837:         if (ref($env{$name})) {
                    838:             @values=@{ $env{$name} };
                    839:         } else {
                    840:             $values[0]=$env{$name};
                    841:         }
                    842:     }
                    843:     return(@values);
                    844: }
                    845: 
1.958     www       846: # ------------------------------------------------------------------- Locking
                    847: 
                    848: sub set_lock {
                    849:     my ($text)=@_;
                    850:     $locknum++;
                    851:     my $id=$$.'-'.$locknum;
                    852:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    853:              'session.lock.'.$id => $text});
                    854:     return $id;
                    855: }
                    856: 
                    857: sub get_locks {
                    858:     my $num=0;
                    859:     my %texts=();
                    860:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    861:        if ($lock=~/\w/) {
                    862:           $num++;
                    863:           $texts{$lock}=$env{'session.lock.'.$lock};
                    864:        }
                    865:    }
                    866:    return ($num,%texts);
                    867: }
                    868: 
                    869: sub remove_lock {
                    870:     my ($id)=@_;
                    871:     my $newlocks='';
                    872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    873:        if (($lock=~/\w/) && ($lock ne $id)) {
                    874:           $newlocks.=','.$lock;
                    875:        }
                    876:     }
                    877:     &appenv({'session.locks' => $newlocks});
                    878:     &delenv('session.lock.'.$id);
                    879: }
                    880: 
                    881: sub remove_all_locks {
                    882:     my $activelocks=$env{'session.locks'};
                    883:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    884:        if ($lock=~/\w/) {
                    885:           &remove_lock($lock);
                    886:        }
                    887:     }
                    888: }
                    889: 
                    890: 
1.369     albertel  891: # ------------------------------------------ Find out current server userload
                    892: sub userload {
                    893:     my $numusers=0;
                    894:     {
                    895: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    896: 	my $filename;
                    897: 	my $curtime=time;
                    898: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  899: 	    next if ($filename eq '.' || $filename eq '..');
                    900: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  901: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  902: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  903: 	}
                    904: 	closedir(LONIDS);
                    905:     }
                    906:     my $userloadpercent=0;
                    907:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    908:     if ($maxuserload) {
1.371     albertel  909: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  910:     }
1.372     albertel  911:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  912:     return $userloadpercent;
1.283     www       913: }
                    914: 
1.1       albertel  915: # ------------------------------ Find server with least workload from spare.tab
1.11      www       916: 
1.1       albertel  917: sub spareserver {
1.1083    raeburn   918:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  919:     my $spare_server;
1.370     albertel  920:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  921:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    922:                                                      :  $userloadpercent;
1.1083    raeburn   923:     my ($uint_dom,$remotesessions);
                    924:     if (($udom ne '') && (&domain($udom) ne '')) {
                    925:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    926:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    927:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    928:         $remotesessions = $udomdefaults{'remotesessions'};
                    929:     }
1.1123    raeburn   930:     my $spareshash = &this_host_spares($udom);
                    931:     if (ref($spareshash) eq 'HASH') {
                    932:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    933:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   934:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    935:                                              $try_server));
1.1123    raeburn   936: 	        ($spare_server, $lowest_load) =
                    937: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    938:             }
1.1083    raeburn   939:         }
1.784     albertel  940: 
1.1123    raeburn   941:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    942: 
                    943:         if (!$found_server) {
                    944:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    945: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   946:                     next unless (&spare_can_host($udom,$uint_dom,
                    947:                                                  $remotesessions,$try_server));
1.1123    raeburn   948: 	            ($spare_server, $lowest_load) =
                    949: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    950:                 }
                    951: 	    }
                    952:         }
1.784     albertel  953:     }
                    954: 
                    955:     if (!$want_server_name) {
1.968     raeburn   956:         my $protocol = 'http';
                    957:         if ($protocol{$spare_server} eq 'https') {
                    958:             $protocol = $protocol{$spare_server};
                    959:         }
1.1001    raeburn   960:         if (defined($spare_server)) {
                    961:             my $hostname = &hostname($spare_server);
1.1083    raeburn   962:             if (defined($hostname)) {
1.1001    raeburn   963: 	        $spare_server = $protocol.'://'.$hostname;
                    964:             }
                    965:         }
1.784     albertel  966:     }
                    967:     return $spare_server;
                    968: }
                    969: 
                    970: sub compare_server_load {
1.1253    raeburn   971:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    972: 
                    973:     if ($required) {
                    974:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    975:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    976:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    977:         if (($major eq '' && $minor eq '') ||
                    978:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    979:             return ($spare_server,$lowest_load);
                    980:         }
                    981:     }
1.784     albertel  982: 
                    983:     my $loadans     = &reply('load',    $try_server);
                    984:     my $userloadans = &reply('userload',$try_server);
                    985: 
                    986:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   987: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  988:     }
                    989: 
                    990:     my $load;
                    991:     if ($loadans =~ /\d/) {
                    992: 	if ($userloadans =~ /\d/) {
                    993: 	    #both are numbers, pick the bigger one
                    994: 	    $load = ($loadans > $userloadans) ? $loadans 
                    995: 		                              : $userloadans;
1.411     albertel  996: 	} else {
1.784     albertel  997: 	    $load = $loadans;
1.411     albertel  998: 	}
1.784     albertel  999:     } else {
                   1000: 	$load = $userloadans;
                   1001:     }
                   1002: 
                   1003:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1004: 	$spare_server = $try_server;
                   1005: 	$lowest_load  = $load;
1.370     albertel 1006:     }
1.784     albertel 1007:     return ($spare_server,$lowest_load);
1.202     matthew  1008: }
1.914     albertel 1009: 
                   1010: # --------------------------- ask offload servers if user already has a session
                   1011: sub find_existing_session {
                   1012:     my ($udom,$uname) = @_;
1.1123    raeburn  1013:     my $spareshash = &this_host_spares($udom);
                   1014:     if (ref($spareshash) eq 'HASH') {
                   1015:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1016:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1017:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1018:             }
                   1019:         }
                   1020:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1021:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1022:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1023:             }
                   1024:         }
1.914     albertel 1025:     }
                   1026:     return;
                   1027: }
                   1028: 
                   1029: # -------------------------------- ask if server already has a session for user
                   1030: sub has_user_session {
                   1031:     my ($lonid,$udom,$uname) = @_;
                   1032:     my $result = &reply(join(':','userhassession',
                   1033: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1034:     return 1 if ($result eq 'ok');
                   1035: 
                   1036:     return 0;
                   1037: }
                   1038: 
1.1076    raeburn  1039: # --------- determine least loaded server in a user's domain which allows login
                   1040: 
                   1041: sub choose_server {
1.1259    raeburn  1042:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1043:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1044:     my %servers = &get_servers($udom);
1.1076    raeburn  1045:     my $lowest_load = 30000;
1.1259    raeburn  1046:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1047:     if ($skiploadbal) {
                   1048:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1049:         unless (defined($cached)) {
                   1050:             my $cachetime = 60*60*24;
                   1051:             my %domconfig =
                   1052:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1053:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1054:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1055:                                            $cachetime);
                   1056:             }
                   1057:         }
                   1058:     }
1.1076    raeburn  1059:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1060:         if ($skiploadbal) {
                   1061:             if (ref($balancers) eq 'HASH') {
                   1062:                 next if (exists($balancers->{$lonhost}));
                   1063:             }
                   1064:         }   
1.1115    raeburn  1065:         my $loginvia;
                   1066:         if ($checkloginvia) {
                   1067:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1068:             if ($loginvia) {
                   1069:                 my ($server,$path) = split(/:/,$loginvia);
                   1070:                 ($login_host, $lowest_load) =
1.1253    raeburn  1071:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1072:                 if ($login_host eq $server) {
                   1073:                     $portal_path = $path;
1.1151    raeburn  1074:                     $isredirect = 1;
1.1116    raeburn  1075:                 }
                   1076:             } else {
                   1077:                 ($login_host, $lowest_load) =
1.1253    raeburn  1078:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1079:                 if ($login_host eq $lonhost) {
                   1080:                     $portal_path = '';
1.1151    raeburn  1081:                     $isredirect = ''; 
1.1116    raeburn  1082:                 }
                   1083:             }
                   1084:         } else {
1.1076    raeburn  1085:             ($login_host, $lowest_load) =
1.1253    raeburn  1086:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1087:         }
                   1088:     }
                   1089:     if ($login_host ne '') {
1.1116    raeburn  1090:         $hostname = &hostname($login_host);
1.1076    raeburn  1091:     }
1.1331    raeburn  1092:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1093: }
                   1094: 
1.202     matthew  1095: # --------------------------------------------- Try to change a user's password
                   1096: 
                   1097: sub changepass {
1.799     raeburn  1098:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1099:     $currentpass = &escape($currentpass);
                   1100:     $newpass     = &escape($newpass);
1.1030    raeburn  1101:     my $lonhost = $perlvar{'lonHostID'};
                   1102:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1103: 		       $server);
                   1104:     if (! $answer) {
                   1105: 	&logthis("No reply on password change request to $server ".
                   1106: 		 "by $uname in domain $udom.");
                   1107:     } elsif ($answer =~ "^ok") {
                   1108:         &logthis("$uname in $udom successfully changed their password ".
                   1109: 		 "on $server.");
                   1110:     } elsif ($answer =~ "^pwchange_failure") {
                   1111: 	&logthis("$uname in $udom was unable to change their password ".
                   1112: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1113: 		 "or pwchange");
                   1114:     } elsif ($answer =~ "^non_authorized") {
                   1115:         &logthis("$uname in $udom did not get their password correct when ".
                   1116: 		 "attempting to change it on $server.");
                   1117:     } elsif ($answer =~ "^auth_mode_error") {
                   1118:         &logthis("$uname in $udom attempted to change their password despite ".
                   1119: 		 "not being locally or internally authenticated on $server.");
                   1120:     } elsif ($answer =~ "^unknown_user") {
                   1121:         &logthis("$uname in $udom attempted to change their password ".
                   1122: 		 "on $server but were unable to because $server is not ".
                   1123: 		 "their home server.");
                   1124:     } elsif ($answer =~ "^refused") {
                   1125: 	&logthis("$server refused to change $uname in $udom password because ".
                   1126: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1127:     } elsif ($answer =~ "invalid_client") {
                   1128:         &logthis("$server refused to change $uname in $udom password because ".
                   1129:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1130:     }
                   1131:     return $answer;
1.1       albertel 1132: }
                   1133: 
1.169     harris41 1134: # ----------------------- Try to determine user's current authentication scheme
                   1135: 
                   1136: sub queryauthenticate {
                   1137:     my ($uname,$udom)=@_;
1.456     albertel 1138:     my $uhome=&homeserver($uname,$udom);
                   1139:     if (!$uhome) {
                   1140: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1141: 	return 'no_host';
                   1142:     }
                   1143:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1144:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1145: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1146:     }
1.456     albertel 1147:     return $answer;
1.169     harris41 1148: }
                   1149: 
1.1       albertel 1150: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1151: 
1.1       albertel 1152: sub authenticate {
1.1073    raeburn  1153:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1154:     $upass=&escape($upass);
                   1155:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1156:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1157:     my $newhome;
1.836     www      1158:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1159: # Maybe the machine was offline and only re-appeared again recently?
                   1160:         &reconlonc();
                   1161: # One more
1.952     raeburn  1162: 	$uhome=&homeserver($uname,$udom,1);
                   1163:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1164:             if (defined(&domain($udom,'primary'))) {
                   1165:                 $newhome=&domain($udom,'primary');
                   1166:             }
                   1167:             if ($newhome ne '') {
                   1168:                 $uhome = $newhome;
                   1169:             }
                   1170:         }
1.836     www      1171: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1172: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1173: 	    return 'no_host';
                   1174:         }
1.1       albertel 1175:     }
1.1073    raeburn  1176:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1177:     if ($answer eq 'authorized') {
1.952     raeburn  1178:         if ($newhome) {
                   1179:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1180:             return 'no_account_on_host'; 
                   1181:         } else {
                   1182:             &logthis("User $uname at $udom authorized by $uhome");
                   1183:             return $uhome;
                   1184:         }
1.471     albertel 1185:     }
                   1186:     if ($answer eq 'non_authorized') {
                   1187: 	&logthis("User $uname at $udom rejected by $uhome");
                   1188: 	return 'no_host'; 
1.9       www      1189:     }
1.471     albertel 1190:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1191:     return 'no_host';
                   1192: }
                   1193: 
1.1073    raeburn  1194: sub can_host_session {
1.1074    raeburn  1195:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1196:     my $canhost = 1;
1.1074    raeburn  1197:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1198:     if (ref($remotesessions) eq 'HASH') {
                   1199:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1200:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1201:                 $canhost = 0;
                   1202:             } else {
                   1203:                 $canhost = 1;
                   1204:             }
                   1205:         }
                   1206:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1207:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1208:                 $canhost = 1;
                   1209:             } else {
                   1210:                 $canhost = 0;
                   1211:             }
                   1212:         }
                   1213:         if ($canhost) {
                   1214:             if ($remotesessions->{'version'} ne '') {
                   1215:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1216:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1217:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1218:                         my $major = $1;
                   1219:                         my $minor = $2;
                   1220:                         if (($major < $reqmajor ) ||
                   1221:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1222:                             $canhost = 0;
                   1223:                         }
                   1224:                     } else {
                   1225:                         $canhost = 0;
                   1226:                     }
                   1227:                 }
                   1228:             }
                   1229:         }
                   1230:     }
                   1231:     if ($canhost) {
                   1232:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1233:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1234:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1235:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1236:                 if (($uint_dom ne '') && 
                   1237:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1238:                     $canhost = 0;
                   1239:                 } else {
                   1240:                     $canhost = 1;
                   1241:                 }
                   1242:             }
                   1243:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1244:                 if (($uint_dom ne '') && 
                   1245:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1246:                     $canhost = 1;
                   1247:                 } else {
                   1248:                     $canhost = 0;
                   1249:                 }
                   1250:             }
                   1251:         }
                   1252:     }
                   1253:     return $canhost;
                   1254: }
                   1255: 
1.1083    raeburn  1256: sub spare_can_host {
                   1257:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1258:     my $canhost=1;
1.1279    raeburn  1259:     my $try_server_hostname = &hostname($try_server);
                   1260:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1261:     my $serverhomedom = &host_domain($serverhomeID);
                   1262:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1263:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1264:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1265:             $canhost = 0;
                   1266:         }
                   1267:     }
                   1268:     if (($canhost) && ($uint_dom)) {
                   1269:         my @intdoms;
                   1270:         my $internet_names = &get_internet_names($try_server);
                   1271:         if (ref($internet_names) eq 'ARRAY') {
                   1272:             @intdoms = @{$internet_names};
                   1273:         }
                   1274:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1275:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1276:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1277:                                          $remotesessions,
                   1278:                                          $defdomdefaults{'hostedsessions'});
                   1279:         }
1.1083    raeburn  1280:     }
                   1281:     return $canhost;
                   1282: }
                   1283: 
1.1123    raeburn  1284: sub this_host_spares {
                   1285:     my ($dom) = @_;
1.1126    raeburn  1286:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1287:     my @hosts = &current_machine_ids();
                   1288:     foreach my $lonhost (@hosts) {
                   1289:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1290:             $dom_in_use = $dom;
                   1291:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1292:             last;
                   1293:         }
                   1294:     }
1.1126    raeburn  1295:     if ($dom_in_use ne '') {
                   1296:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1297:     }
                   1298:     if (ref($result) ne 'HASH') {
                   1299:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1300:         $dom_in_use = &host_domain($lonhost_in_use);
                   1301:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1302:         if (ref($result) ne 'HASH') {
                   1303:             $result = \%spareid;
                   1304:         }
                   1305:     }
                   1306:     return $result;
                   1307: }
                   1308: 
                   1309: sub spares_for_offload  {
                   1310:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1311:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1312:     if (defined($cached)) {
                   1313:         return $result;
                   1314:     } else {
1.1126    raeburn  1315:         my $cachetime = 60*60*24;
                   1316:         my %domconfig =
                   1317:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1318:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1319:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1320:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1321:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1322:                 }
                   1323:             }
                   1324:         }
                   1325:     }
1.1126    raeburn  1326:     return;
1.1123    raeburn  1327: }
                   1328: 
1.1129    raeburn  1329: sub get_lonbalancer_config {
                   1330:     my ($servers) = @_;
                   1331:     my ($currbalancer,$currtargets);
                   1332:     if (ref($servers) eq 'HASH') {
                   1333:         foreach my $server (keys(%{$servers})) {
                   1334:             my %what = (
                   1335:                          spareid => 1,
                   1336:                          perlvar => 1,
                   1337:                        );
                   1338:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1339:             if ($result eq 'ok') {
                   1340:                 if (ref($returnhash) eq 'HASH') {
                   1341:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1342:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1343:                             $currbalancer = $server;
                   1344:                             $currtargets = {};
                   1345:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1346:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1347:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1348:                                 }
                   1349:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1350:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1351:                                 }
                   1352:                             }
                   1353:                             last;
                   1354:                         }
                   1355:                     }
                   1356:                 }
                   1357:             }
                   1358:         }
                   1359:     }
                   1360:     return ($currbalancer,$currtargets);
                   1361: }
                   1362: 
                   1363: sub check_loadbalancing {
1.1331    raeburn  1364:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1365:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1366:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1367:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1368:     my @hosts = &current_machine_ids();
1.1129    raeburn  1369:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1370:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1371:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1372:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1373:     my $domneedscache;
1.1129    raeburn  1374:     my $cachetime = 60*60*24;
                   1375: 
                   1376:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1377:         $dom_in_use = $udom;
                   1378:         $homeintdom = 1;
                   1379:     } else {
                   1380:         $dom_in_use = $serverhomedom;
                   1381:     }
                   1382:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1383:     unless (defined($cached)) {
                   1384:         my %domconfig =
                   1385:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1386:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1387:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1388:         } else {
                   1389:             $domneedscache = $dom_in_use;
1.1129    raeburn  1390:         }
                   1391:     }
                   1392:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1393:         ($is_balancer,$currtargets,$currrules) = 
                   1394:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1395:         if ($is_balancer) {
                   1396:             if (ref($currrules) eq 'HASH') {
                   1397:                 if ($homeintdom) {
                   1398:                     if ($uname ne '') {
                   1399:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1400:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1401:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1402:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1403:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1404:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1405:                             }
                   1406:                         }
                   1407:                         if ($rule_in_effect eq '') {
                   1408:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1409:                             if ($userenv{'inststatus'} ne '') {
                   1410:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1411:                                 my ($othertitle,$usertypes,$types) =
                   1412:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1413:                                 if (ref($types) eq 'ARRAY') {
                   1414:                                     foreach my $type (@{$types}) {
                   1415:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1416:                                             if (exists($currrules->{$type})) {
                   1417:                                                 $rule_in_effect = $currrules->{$type};
                   1418:                                             }
                   1419:                                         }
                   1420:                                     }
                   1421:                                 }
                   1422:                             } else {
                   1423:                                 if (exists($currrules->{'default'})) {
                   1424:                                     $rule_in_effect = $currrules->{'default'};
                   1425:                                 }
                   1426:                             }
                   1427:                         }
                   1428:                     } else {
                   1429:                         if (exists($currrules->{'default'})) {
                   1430:                             $rule_in_effect = $currrules->{'default'};
                   1431:                         }
                   1432:                     }
                   1433:                 } else {
                   1434:                     if ($currrules->{'_LC_external'} ne '') {
                   1435:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1436:                     }
                   1437:                 }
                   1438:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1439:                                                        $uname,$udom);
                   1440:             }
                   1441:         }
                   1442:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1443:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1444:         unless (defined($cached)) {
                   1445:             my %domconfig =
                   1446:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1447:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1448:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1449:             } else {
                   1450:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1451:             }
                   1452:         }
                   1453:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1454:             ($is_balancer,$currtargets,$currrules) = 
                   1455:                 &check_balancer_result($result,@hosts);
                   1456:             if ($is_balancer) {
1.1129    raeburn  1457:                 if (ref($currrules) eq 'HASH') {
                   1458:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1459:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1460:                     }
                   1461:                 }
                   1462:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1463:                                                        $uname,$udom);
                   1464:             }
                   1465:         } else {
                   1466:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1467:                 $is_balancer = 1;
                   1468:                 $offloadto = &this_host_spares($dom_in_use);
                   1469:             }
1.1307    raeburn  1470:             unless (defined($cached)) {
                   1471:                 $domneedscache = $serverhomedom;
                   1472:             }
1.1129    raeburn  1473:         }
                   1474:     } else {
                   1475:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1476:             $is_balancer = 1;
                   1477:             $offloadto = &this_host_spares($dom_in_use);
                   1478:         }
1.1307    raeburn  1479:         unless (defined($cached)) {
                   1480:             $domneedscache = $serverhomedom;
                   1481:         }
                   1482:     }
                   1483:     if ($domneedscache) {
                   1484:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1485:     }
1.1176    raeburn  1486:     if ($is_balancer) {
                   1487:         my $lowest_load = 30000;
                   1488:         if (ref($offloadto) eq 'HASH') {
                   1489:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1490:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1491:                     ($otherserver,$lowest_load) =
                   1492:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1493:                 }
1.1129    raeburn  1494:             }
1.1176    raeburn  1495:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1496: 
1.1176    raeburn  1497:             if (!$found_server) {
                   1498:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1499:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1500:                         ($otherserver,$lowest_load) =
                   1501:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1502:                     }
                   1503:                 }
                   1504:             }
                   1505:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1506:             if (@{$offloadto} == 1) {
                   1507:                 $otherserver = $offloadto->[0];
                   1508:             } elsif (@{$offloadto} > 1) {
                   1509:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1510:                     ($otherserver,$lowest_load) =
                   1511:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1512:                 }
                   1513:             }
                   1514:         }
1.1331    raeburn  1515:         unless ($caller eq 'login') {
                   1516:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1517:                 $is_balancer = 0;
                   1518:                 if ($uname ne '' && $udom ne '') {
                   1519:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1520:                     
1.1331    raeburn  1521:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1522:                                  'user.loadbalcheck.time' => time});
                   1523:                     }
1.1176    raeburn  1524:                 }
1.1129    raeburn  1525:             }
                   1526:         }
                   1527:     }
                   1528:     return ($is_balancer,$otherserver);
                   1529: }
                   1530: 
1.1191    raeburn  1531: sub check_balancer_result {
                   1532:     my ($result,@hosts) = @_;
                   1533:     my ($is_balancer,$currtargets,$currrules);
                   1534:     if (ref($result) eq 'HASH') {
                   1535:         if ($result->{'lonhost'} ne '') {
                   1536:             my $currbalancer = $result->{'lonhost'};
                   1537:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1538:                 $is_balancer = 1;
                   1539:                 $currtargets = $result->{'targets'};
                   1540:                 $currrules = $result->{'rules'};
                   1541:             }
                   1542:         } else {
                   1543:             foreach my $key (keys(%{$result})) {
                   1544:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1545:                     (ref($result->{$key}) eq 'HASH')) {
                   1546:                     $is_balancer = 1;
                   1547:                     $currrules = $result->{$key}{'rules'};
                   1548:                     $currtargets = $result->{$key}{'targets'};
                   1549:                     last;
                   1550:                 }
                   1551:             }
                   1552:         }
                   1553:     }
                   1554:     return ($is_balancer,$currtargets,$currrules);
                   1555: }
                   1556: 
1.1129    raeburn  1557: sub get_loadbalancer_targets {
                   1558:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1559:     my $offloadto;
1.1175    raeburn  1560:     if ($rule_in_effect eq 'none') {
                   1561:         return [$perlvar{'lonHostID'}];
                   1562:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1563:         $offloadto = $currtargets;
                   1564:     } else {
                   1565:         if ($rule_in_effect eq 'homeserver') {
                   1566:             my $homeserver = &homeserver($uname,$udom);
                   1567:             if ($homeserver ne 'no_host') {
                   1568:                 $offloadto = [$homeserver];
                   1569:             }
                   1570:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1571:             my %domconfig =
                   1572:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1573:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1574:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1575:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1576:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1577:                     }
                   1578:                 }
                   1579:             } else {
1.1178    raeburn  1580:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1581:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1582:                 if (&hostname($remotebalancer) ne '') {
                   1583:                     $offloadto = [$remotebalancer];
                   1584:                 }
                   1585:             }
                   1586:         } elsif (&hostname($rule_in_effect) ne '') {
                   1587:             $offloadto = [$rule_in_effect];
                   1588:         }
                   1589:     }
                   1590:     return $offloadto;
                   1591: }
                   1592: 
1.1127    raeburn  1593: sub internet_dom_servers {
                   1594:     my ($dom) = @_;
                   1595:     my (%uniqservers,%servers);
                   1596:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1597:     my @machinedoms = &machine_domains($primaryserver);
                   1598:     foreach my $mdom (@machinedoms) {
                   1599:         my %currservers = %servers;
                   1600:         my %server = &get_servers($mdom);
                   1601:         %servers = (%currservers,%server);
                   1602:     }
                   1603:     my %by_hostname;
                   1604:     foreach my $id (keys(%servers)) {
                   1605:         push(@{$by_hostname{$servers{$id}}},$id);
                   1606:     }
                   1607:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1608:         if (@{$by_hostname{$hostname}} > 1) {
                   1609:             my $match = 0;
                   1610:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1611:                 if (&host_domain($id) eq $dom) {
                   1612:                     $uniqservers{$id} = $hostname;
                   1613:                     $match = 1;
                   1614:                 }
                   1615:             }
                   1616:             unless ($match) {
                   1617:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1618:             }
                   1619:         } else {
                   1620:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1621:         }
                   1622:     }
                   1623:     return %uniqservers;
                   1624: }
                   1625: 
1.1347    raeburn  1626: sub trusted_domains {
                   1627:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1628:     my ($trusted,$untrusted);
1.1347    raeburn  1629:     if (&domain($calldom) eq '') {
1.1349    raeburn  1630:         return ($trusted,$untrusted);
1.1347    raeburn  1631:     }
                   1632:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1633:         return ($trusted,$untrusted);
1.1347    raeburn  1634:     }
                   1635:     my $callprimary = &domain($calldom,'primary');
                   1636:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1637:     if ($intcalldom eq '') {
1.1349    raeburn  1638:         return ($trusted,$untrusted);
1.1347    raeburn  1639:     }
                   1640: 
                   1641:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1642:     unless (defined($cached)) {
                   1643:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1644:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1645:         $trustconfig = $domconfig{'trust'};
                   1646:     }
                   1647:     if (ref($trustconfig)) {
                   1648:         my (%possexc,%possinc,@allexc,@allinc); 
                   1649:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1650:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1651:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1652:             }
                   1653:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1654:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1655:             }
                   1656:         }
                   1657:         if (keys(%possexc)) {
                   1658:             if (keys(%possinc)) {
                   1659:                 foreach my $key (sort(keys(%possexc))) {
                   1660:                     next if ($key eq $intcalldom);
                   1661:                     unless ($possinc{$key}) {
                   1662:                         push(@allexc,$key);
                   1663:                     }
                   1664:                 }
                   1665:             } else {
                   1666:                 @allexc = sort(keys(%possexc));
                   1667:             }
                   1668:         }
                   1669:         if (keys(%possinc)) {
                   1670:             $possinc{$intcalldom} = 1;
                   1671:             @allinc = sort(keys(%possinc));
                   1672:         }
                   1673:         if ((@allexc > 0) || (@allinc > 0)) {
                   1674:             my %doms_by_intdom;
                   1675:             my %allintdoms = &all_host_intdom();
                   1676:             my %alldoms = &all_host_domain();
                   1677:             foreach my $key (%allintdoms) {
                   1678:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1679:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1680:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1681:                     }
                   1682:                 } else {
                   1683:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1684:                 }
                   1685:             }
                   1686:             foreach my $exc (@allexc) {
                   1687:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1688:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1689:                 }
                   1690:             }
                   1691:             foreach my $inc (@allinc) {
                   1692:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1693:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1694:                 }
                   1695:             }
                   1696:         }
                   1697:     }
1.1349    raeburn  1698:     return ($trusted,$untrusted);
1.1347    raeburn  1699: }
                   1700: 
                   1701: sub will_trust {
                   1702:     my ($cmdtype,$domain,$possdom) = @_;
                   1703:     return 1 if ($domain eq $possdom);
                   1704:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1705:     my $willtrust; 
                   1706:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1707:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1708:             $willtrust = 1;
                   1709:         }
                   1710:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1711:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1712:             $willtrust = 1;
                   1713:         }
                   1714:     } else {
                   1715:         $willtrust = 1;
                   1716:     }
                   1717:     return $willtrust;
                   1718: }
                   1719: 
1.1       albertel 1720: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1721: 
1.599     albertel 1722: my %homecache;
1.1       albertel 1723: sub homeserver {
1.230     stredwic 1724:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1725:     my $index="$uname:$udom";
1.426     albertel 1726: 
1.599     albertel 1727:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1728: 
                   1729:     my %servers = &get_servers($udom,'library');
                   1730:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1731:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1732: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1733: 
                   1734: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1735: 	if ($answer eq 'found') {
                   1736: 	    delete($badServerCache{$tryserver}); 
                   1737: 	    return $homecache{$index}=$tryserver;
                   1738: 	} elsif ($answer eq 'no_host') {
                   1739: 	    $badServerCache{$tryserver}=1;
                   1740: 	}
1.1       albertel 1741:     }    
                   1742:     return 'no_host';
1.70      www      1743: }
                   1744: 
1.1300    raeburn  1745: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1746: 
                   1747: sub idget {
1.1300    raeburn  1748:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1749:     my %returnhash=();
1.1300    raeburn  1750:     my @ids=(); 
                   1751:     if (ref($idsref) eq 'ARRAY') {
                   1752:         @ids = @{$idsref};
                   1753:     } else {
                   1754:         return %returnhash; 
                   1755:     }
                   1756:     if ($namespace eq '') {
                   1757:         $namespace = 'ids';
                   1758:     }
1.70      www      1759:     
1.841     albertel 1760:     my %servers = &get_servers($udom,'library');
                   1761:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1762: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1763: 	if ($namespace eq 'ids') {
                   1764: 	    $idlist=~tr/A-Z/a-z/;
                   1765: 	}
                   1766: 	my $reply;
                   1767: 	if ($namespace eq 'ids') {
                   1768: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1769: 	} else {
                   1770: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1771: 	}
1.841     albertel 1772: 	my @answer=();
                   1773: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1774: 	    @answer=split(/\&/,$reply);
                   1775: 	}                    ;
                   1776: 	my $i;
                   1777: 	for ($i=0;$i<=$#ids;$i++) {
                   1778: 	    if ($answer[$i]) {
1.1299    raeburn  1779: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1780: 	    }
1.841     albertel 1781: 	}
1.1300    raeburn  1782:     }
1.70      www      1783:     return %returnhash;
                   1784: }
                   1785: 
                   1786: # ------------------------------------- Find the IDs behind a list of usernames
                   1787: 
                   1788: sub idrget {
                   1789:     my ($udom,@unames)=@_;
                   1790:     my %returnhash=();
1.800     albertel 1791:     foreach my $uname (@unames) {
                   1792:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1793:     }
1.70      www      1794:     return %returnhash;
                   1795: }
                   1796: 
1.1300    raeburn  1797: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1798: 
                   1799: sub idput {
1.1300    raeburn  1800:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1801:     my %servers=();
1.1300    raeburn  1802:     my %ids=();
                   1803:     my %byid = ();
                   1804:     if (ref($idsref) eq 'HASH') {
                   1805:         %ids=%{$idsref};
                   1806:     }
                   1807:     if ($namespace eq '') {
                   1808:         $namespace = 'ids'; 
                   1809:     }
1.800     albertel 1810:     foreach my $uname (keys(%ids)) {
                   1811: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1812:         if ($uhom eq '') {
                   1813:             $uhom=&homeserver($uname,$udom);
                   1814:         }
1.70      www      1815:         if ($uhom ne 'no_host') {
1.800     albertel 1816:             my $esc_unam=&escape($uname);
1.1300    raeburn  1817:             if ($namespace eq 'ids') {
                   1818:                 my $id=&escape($ids{$uname});
                   1819:                 $id=~tr/A-Z/a-z/;
                   1820:                 my $esc_unam=&escape($uname);
                   1821:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1822:             } else {
1.1300    raeburn  1823:                 my @currids = split(/,/,$ids{$uname});
                   1824:                 foreach my $id (@currids) {
                   1825:                     $byid{$uhom}{$id} .= $uname.',';
                   1826:                 }
                   1827:             }
                   1828:         }
                   1829:     }
                   1830:     if ($namespace eq 'clickers') {
                   1831:         foreach my $server (keys(%byid)) {
                   1832:             if (ref($byid{$server}) eq 'HASH') {
                   1833:                 foreach my $id (keys(%{$byid{$server}})) {
                   1834:                     $byid{$server} =~ s/,$//;
                   1835:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1836:                 }
1.70      www      1837:             }
                   1838:         }
1.191     harris41 1839:     }
1.800     albertel 1840:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1841:         $servers{$server} =~ s/\&$//;
                   1842:         if ($namespace eq 'ids') {     
                   1843:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1844:         } else {
                   1845:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1846:         }
1.191     harris41 1847:     }
1.344     www      1848: }
                   1849: 
1.1300    raeburn  1850: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1851: 
                   1852: sub iddel {
1.1300    raeburn  1853:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1854:     my %result=();
1.1300    raeburn  1855:     my %ids=();
                   1856:     my %byid = ();
                   1857:     if (ref($idshashref) eq 'HASH') {
                   1858:         %ids=%{$idshashref};
                   1859:     } else {
1.1231    raeburn  1860:         return %result;
                   1861:     }
1.1300    raeburn  1862:     if ($namespace eq '') {
                   1863:         $namespace = 'ids';
                   1864:     }
1.1231    raeburn  1865:     my %servers=();
1.1300    raeburn  1866:     while (my ($id,$unamestr) = each(%ids)) {
                   1867:         if ($namespace eq 'ids') {
                   1868:             my $uhom = $uhome;
                   1869:             if ($uhom eq '') { 
                   1870:                 $uhom=&homeserver($unamestr,$udom);
                   1871:             }
                   1872:             if ($uhom ne 'no_host') {
                   1873:                 $servers{$uhom}.='&'.&escape($id);
                   1874:             }
                   1875:          } else {
                   1876:             my @curritems = split(/,/,$ids{$id});
                   1877:             foreach my $uname (@curritems) {
                   1878:                 my $uhom = $uhome;
                   1879:                 if ($uhom eq '') {
                   1880:                     $uhom=&homeserver($uname,$udom);
                   1881:                 }
                   1882:                 if ($uhom ne 'no_host') { 
                   1883:                     $byid{$uhom}{$id} .= $uname.',';
                   1884:                 }
                   1885:             }
1.1231    raeburn  1886:         }
1.1300    raeburn  1887:     }
                   1888:     if ($namespace eq 'clickers') {
                   1889:         foreach my $server (keys(%byid)) {
                   1890:             if (ref($byid{$server}) eq 'HASH') {
                   1891:                 foreach my $id (keys(%{$byid{$server}})) {
                   1892:                     $byid{$server}{$id} =~ s/,$//;
                   1893:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1894:                 }
1.1231    raeburn  1895:             }
                   1896:         }
                   1897:     }
                   1898:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1899:         $servers{$server} =~ s/\&$//;
                   1900:         if ($namespace eq 'ids') {
                   1901:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1902:         } elsif ($namespace eq 'clickers') {
                   1903:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1904:         }
1.1231    raeburn  1905:     }
                   1906:     return %result;
                   1907: }
                   1908: 
1.1300    raeburn  1909: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1910: 
                   1911: sub updateclickers {
                   1912:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1913:     my %clickers;
                   1914:     if (ref($idshashref) eq 'HASH') {
                   1915:         %clickers=%{$idshashref};
                   1916:     } else {
                   1917:         return;
                   1918:     }
                   1919:     my $items='';
                   1920:     foreach my $item (keys(%clickers)) {
                   1921:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1922:     }
                   1923:     $items=~s/\&$//;
                   1924:     my $request = "updateclickers:$udom:$action:$items";
                   1925:     if ($critical) {
                   1926:         return &critical($request,$uhome);
                   1927:     } else {
                   1928:         return &reply($request,$uhome);
                   1929:     }
                   1930: }
                   1931: 
1.1023    raeburn  1932: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1933: sub dump_dom {
1.1165    droeschl 1934:     my ($namespace, $udom, $regexp) = @_;
                   1935: 
                   1936:     $udom ||= $env{'user.domain'};
                   1937: 
                   1938:     return () unless $udom;
                   1939: 
                   1940:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1941: }
                   1942: 
1.1023    raeburn  1943: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1944: 
                   1945: sub get_dom {
1.860     raeburn  1946:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1947:     return if ($udom eq 'public');
1.806     raeburn  1948:     my $items='';
                   1949:     foreach my $item (@$storearr) {
                   1950:         $items.=&escape($item).'&';
                   1951:     }
                   1952:     $items=~s/\&$//;
1.860     raeburn  1953:     if (!$udom) {
                   1954:         $udom=$env{'user.domain'};
1.1267    raeburn  1955:         return if ($udom eq 'public');
1.860     raeburn  1956:         if (defined(&domain($udom,'primary'))) {
                   1957:             $uhome=&domain($udom,'primary');
                   1958:         } else {
1.874     albertel 1959:             undef($uhome);
1.860     raeburn  1960:         }
                   1961:     } else {
                   1962:         if (!$uhome) {
                   1963:             if (defined(&domain($udom,'primary'))) {
                   1964:                 $uhome=&domain($udom,'primary');
                   1965:             }
                   1966:         }
                   1967:     }
                   1968:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  1969:         my $rep;
                   1970:         if ($namespace =~ /^enc/) {
                   1971:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1972:         } else {
                   1973:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1974:         }
1.866     raeburn  1975:         my %returnhash;
1.875     albertel 1976:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1977:             return %returnhash;
                   1978:         }
1.806     raeburn  1979:         my @pairs=split(/\&/,$rep);
                   1980:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1981:             return @pairs;
                   1982:         }
                   1983:         my $i=0;
                   1984:         foreach my $item (@$storearr) {
                   1985:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1986:             $i++;
                   1987:         }
                   1988:         return %returnhash;
                   1989:     } else {
1.880     banghart 1990:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1991:     }
                   1992: }
                   1993: 
                   1994: # -------------------------------------------- put items in domain db files 
                   1995: 
                   1996: sub put_dom {
1.860     raeburn  1997:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1998:     if (!$udom) {
                   1999:         $udom=$env{'user.domain'};
                   2000:         if (defined(&domain($udom,'primary'))) {
                   2001:             $uhome=&domain($udom,'primary');
                   2002:         } else {
1.874     albertel 2003:             undef($uhome);
1.860     raeburn  2004:         }
                   2005:     } else {
                   2006:         if (!$uhome) {
                   2007:             if (defined(&domain($udom,'primary'))) {
                   2008:                 $uhome=&domain($udom,'primary');
                   2009:             }
                   2010:         }
                   2011:     } 
                   2012:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2013:         my $items='';
                   2014:         foreach my $item (keys(%$storehash)) {
                   2015:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2016:         }
                   2017:         $items=~s/\&$//;
1.1344    raeburn  2018:         if ($namespace =~ /^enc/) {
                   2019:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2020:         } else {
                   2021:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2022:         }
1.806     raeburn  2023:     } else {
1.860     raeburn  2024:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2025:     }
                   2026: }
                   2027: 
1.1023    raeburn  2028: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2029: sub newput_dom {
1.1023    raeburn  2030:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2031:     my $result;
                   2032:     if (!$udom) {
                   2033:         $udom=$env{'user.domain'};
                   2034:     }
1.1023    raeburn  2035:     if ($udom) {
                   2036:         my $uname = &get_domainconfiguser($udom);
                   2037:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2038:     }
                   2039:     return $result;
                   2040: }
                   2041: 
1.1023    raeburn  2042: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2043: sub del_dom {
1.1023    raeburn  2044:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2045:     if (ref($storearr) eq 'ARRAY') {
                   2046:         if (!$udom) {
                   2047:             $udom=$env{'user.domain'};
                   2048:         }
1.1023    raeburn  2049:         if ($udom) {
                   2050:             my $uname = &get_domainconfiguser($udom); 
                   2051:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2052:         }
                   2053:     }
                   2054: }
                   2055: 
1.1023    raeburn  2056: # ----------------------------------construct domainconfig user for a domain 
                   2057: sub get_domainconfiguser {
                   2058:     my ($udom) = @_;
                   2059:     return $udom.'-domainconfig';
                   2060: }
                   2061: 
1.837     raeburn  2062: sub retrieve_inst_usertypes {
                   2063:     my ($udom) = @_;
                   2064:     my (%returnhash,@order);
1.989     raeburn  2065:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2066:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2067:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2068:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2069:     } else {
                   2070:         if (defined(&domain($udom,'primary'))) {
                   2071:             my $uhome=&domain($udom,'primary');
                   2072:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2073:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2074:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2075:                 return (\%returnhash,\@order);
                   2076:             }
                   2077:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2078:             my @pairs=split(/\&/,$hashitems);
                   2079:             foreach my $item (@pairs) {
                   2080:                 my ($key,$value)=split(/=/,$item,2);
                   2081:                 $key = &unescape($key);
                   2082:                 next if ($key =~ /^error: 2 /);
                   2083:                 $returnhash{$key}=&thaw_unescape($value);
                   2084:             }
                   2085:             my @esc_order = split(/\&/,$orderitems);
                   2086:             foreach my $item (@esc_order) {
                   2087:                 push(@order,&unescape($item));
                   2088:             }
                   2089:         } else {
1.1256    raeburn  2090:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2091:         }
1.1256    raeburn  2092:         return (\%returnhash,\@order);
1.837     raeburn  2093:     }
                   2094: }
                   2095: 
1.868     raeburn  2096: sub is_domainimage {
                   2097:     my ($url) = @_;
1.1306    raeburn  2098:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2099:         if (&domain($1) ne '') {
                   2100:             return '1';
                   2101:         }
                   2102:     }
                   2103:     return;
                   2104: }
                   2105: 
1.899     raeburn  2106: sub inst_directory_query {
                   2107:     my ($srch) = @_;
                   2108:     my $udom = $srch->{'srchdomain'};
                   2109:     my %results;
                   2110:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2111:     my $outcome;
1.899     raeburn  2112:     if ($homeserver ne '') {
1.1357    raeburn  2113:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2114:             if ($srch->{'srchby'} eq 'email') {
                   2115:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2116:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2117:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2118:                     (($major == 2) && ($minor < 12))) {
                   2119:                     return;
                   2120:                 }
                   2121:             }
                   2122:         }
1.904     albertel 2123: 	my $queryid=&reply("querysend:instdirsearch:".
                   2124: 			   &escape($srch->{'srchby'}).':'.
                   2125: 			   &escape($srch->{'srchterm'}).':'.
                   2126: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2127: 	my $host=&hostname($homeserver);
                   2128: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2129: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2130: 	    return;
                   2131: 	}
                   2132: 	my $response = &get_query_reply($queryid);
                   2133: 	my $maxtries = 5;
                   2134: 	my $tries = 1;
                   2135: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2136: 	    $response = &get_query_reply($queryid);
                   2137: 	    $tries ++;
                   2138: 	}
                   2139: 
                   2140:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2141:             if ($response eq 'unavailable') {
                   2142:                 $outcome = $response;
                   2143:             } else {
                   2144:                 $outcome = 'ok';
                   2145:                 my @matches = split(/\n/,$response);
                   2146:                 foreach my $match (@matches) {
                   2147:                     my ($key,$value) = split(/=/,$match);
                   2148:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2149:                 }
1.899     raeburn  2150:             }
                   2151:         }
                   2152:     }
1.909     raeburn  2153:     return ($outcome,%results);
1.899     raeburn  2154: }
                   2155: 
                   2156: sub usersearch {
                   2157:     my ($srch) = @_;
                   2158:     my $dom = $srch->{'srchdomain'};
                   2159:     my %results;
                   2160:     my %libserv = &all_library();
                   2161:     my $query = 'usersearch';
                   2162:     foreach my $tryserver (keys(%libserv)) {
                   2163:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2164:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2165:                 if ($srch->{'srchby'} eq 'email') {
                   2166:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2167:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2168:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2169:                              (($major == 2) && ($minor < 12)));
                   2170:                 }
                   2171:             }
1.899     raeburn  2172:             my $host=&hostname($tryserver);
                   2173:             my $queryid=
1.911     raeburn  2174:                 &reply("querysend:".&escape($query).':'.
                   2175:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2176:                        &escape($srch->{'srchtype'}).':'.
                   2177:                        &escape($srch->{'srchterm'}),$tryserver);
                   2178:             if ($queryid !~/^\Q$host\E\_/) {
                   2179:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2180:                 next;
1.899     raeburn  2181:             }
                   2182:             my $reply = &get_query_reply($queryid);
                   2183:             my $maxtries = 1;
                   2184:             my $tries = 1;
                   2185:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2186:                 $reply = &get_query_reply($queryid);
                   2187:                 $tries ++;
                   2188:             }
                   2189:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2190:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2191:             } else {
1.911     raeburn  2192:                 my @matches;
                   2193:                 if ($reply =~ /\n/) {
                   2194:                     @matches = split(/\n/,$reply);
                   2195:                 } else {
                   2196:                     @matches = split(/\&/,$reply);
                   2197:                 }
1.899     raeburn  2198:                 foreach my $match (@matches) {
                   2199:                     my ($uname,$udom,%userhash);
1.911     raeburn  2200:                     foreach my $entry (split(/:/,$match)) {
                   2201:                         my ($key,$value) =
                   2202:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2203:                         $userhash{$key} = $value;
                   2204:                         if ($key eq 'username') {
                   2205:                             $uname = $value;
                   2206:                         } elsif ($key eq 'domain') {
                   2207:                             $udom = $value;
1.911     raeburn  2208:                         }
1.899     raeburn  2209:                     }
                   2210:                     $results{$uname.':'.$udom} = \%userhash;
                   2211:                 }
                   2212:             }
                   2213:         }
                   2214:     }
                   2215:     return %results;
                   2216: }
                   2217: 
1.912     raeburn  2218: sub get_instuser {
                   2219:     my ($udom,$uname,$id) = @_;
                   2220:     my $homeserver = &domain($udom,'primary');
                   2221:     my ($outcome,%results);
                   2222:     if ($homeserver ne '') {
                   2223:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2224:                            &escape($id).':'.&escape($udom),$homeserver);
                   2225:         my $host=&hostname($homeserver);
                   2226:         if ($queryid !~/^\Q$host\E\_/) {
                   2227:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2228:             return;
                   2229:         }
                   2230:         my $response = &get_query_reply($queryid);
                   2231:         my $maxtries = 5;
                   2232:         my $tries = 1;
                   2233:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2234:             $response = &get_query_reply($queryid);
                   2235:             $tries ++;
                   2236:         }
                   2237:         if (!&error($response) && $response ne 'refused') {
                   2238:             if ($response eq 'unavailable') {
                   2239:                 $outcome = $response;
                   2240:             } else {
                   2241:                 $outcome = 'ok';
                   2242:                 my @matches = split(/\n/,$response);
                   2243:                 foreach my $match (@matches) {
                   2244:                     my ($key,$value) = split(/=/,$match);
                   2245:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2246:                 }
                   2247:             }
                   2248:         }
                   2249:     }
                   2250:     my %userinfo;
                   2251:     if (ref($results{$uname}) eq 'HASH') {
                   2252:         %userinfo = %{$results{$uname}};
                   2253:     } 
                   2254:     return ($outcome,%userinfo);
                   2255: }
                   2256: 
1.1290    raeburn  2257: sub get_multiple_instusers {
                   2258:     my ($udom,$users,$caller) = @_;
                   2259:     my ($outcome,$results);
                   2260:     if (ref($users) eq 'HASH') {
                   2261:         my $count = keys(%{$users}); 
                   2262:         my $requested = &freeze_escape($users);
                   2263:         my $homeserver = &domain($udom,'primary');
                   2264:         if ($homeserver ne '') {
                   2265:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2266:             my $host=&hostname($homeserver);
                   2267:             if ($queryid !~/^\Q$host\E\_/) {
                   2268:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2269:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2270:                 return ($outcome,$results);
                   2271:             }
                   2272:             my $response = &get_query_reply($queryid);
                   2273:             my $maxtries = 5;
                   2274:             if ($count > 100) {
                   2275:                 $maxtries = 1+int($count/20);
                   2276:             }
                   2277:             my $tries = 1;
                   2278:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2279:                 $response = &get_query_reply($queryid);
                   2280:                 $tries ++;
                   2281:             }
                   2282:             if ($response eq '') {
                   2283:                 $results = {};
                   2284:                 foreach my $key (keys(%{$users})) {
                   2285:                     my ($uname,$id);
                   2286:                     if ($caller eq 'id') {
                   2287:                         $id = $key;
                   2288:                     } else {
                   2289:                         $uname = $key;
                   2290:                     }
                   2291:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2292:                     $outcome = $resp;
1.1290    raeburn  2293:                     if ($resp eq 'ok') {
                   2294:                         %{$results} = (%{$results}, %info);
                   2295:                     } else {
                   2296:                         last;
                   2297:                     }
                   2298:                 }
                   2299:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2300:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2301:                     $outcome = $response;
                   2302:                 } else {
1.1291    raeburn  2303:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2304:                     if ($outcome eq 'ok') {
                   2305:                         $results = &thaw_unescape($userdata); 
                   2306:                     }
                   2307:                 }
                   2308:             }
                   2309:         }
                   2310:     }
                   2311:     return ($outcome,$results);
                   2312: }
                   2313: 
1.912     raeburn  2314: sub inst_rulecheck {
1.923     raeburn  2315:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2316:     my %returnhash;
                   2317:     if ($udom ne '') {
                   2318:         if (ref($rules) eq 'ARRAY') {
                   2319:             @{$rules} = map {&escape($_);} (@{$rules});
                   2320:             my $rulestr = join(':',@{$rules});
                   2321:             my $homeserver=&domain($udom,'primary');
                   2322:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2323:                 my $response;
                   2324:                 if ($item eq 'username') {                
                   2325:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2326:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2327:                                               $homeserver));
1.923     raeburn  2328:                 } elsif ($item eq 'id') {
                   2329:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2330:                                               ':'.&escape($id).':'.$rulestr,
                   2331:                                               $homeserver));
1.945     raeburn  2332:                 } elsif ($item eq 'selfcreate') {
                   2333:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2334:                                                &escape($udom).':'.&escape($uname).
                   2335:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2336:                 }
1.912     raeburn  2337:                 if ($response ne 'refused') {
                   2338:                     my @pairs=split(/\&/,$response);
                   2339:                     foreach my $item (@pairs) {
                   2340:                         my ($key,$value)=split(/=/,$item,2);
                   2341:                         $key = &unescape($key);
                   2342:                         next if ($key =~ /^error: 2 /);
                   2343:                         $returnhash{$key}=&thaw_unescape($value);
                   2344:                     }
                   2345:                 }
                   2346:             }
                   2347:         }
                   2348:     }
                   2349:     return %returnhash;
                   2350: }
                   2351: 
                   2352: sub inst_userrules {
1.923     raeburn  2353:     my ($udom,$check) = @_;
1.912     raeburn  2354:     my (%ruleshash,@ruleorder);
                   2355:     if ($udom ne '') {
                   2356:         my $homeserver=&domain($udom,'primary');
                   2357:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2358:             my $response;
                   2359:             if ($check eq 'id') {
                   2360:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2361:                                  $homeserver);
1.943     raeburn  2362:             } elsif ($check eq 'email') {
                   2363:                 $response=&reply('instemailrules:'.&escape($udom),
                   2364:                                  $homeserver);
1.923     raeburn  2365:             } else {
                   2366:                 $response=&reply('instuserrules:'.&escape($udom),
                   2367:                                  $homeserver);
                   2368:             }
1.912     raeburn  2369:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2370:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2371:                 ($response ne 'no_such_host')) {
                   2372:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2373:                 my @pairs=split(/\&/,$hashitems);
                   2374:                 foreach my $item (@pairs) {
                   2375:                     my ($key,$value)=split(/=/,$item,2);
                   2376:                     $key = &unescape($key);
                   2377:                     next if ($key =~ /^error: 2 /);
                   2378:                     $ruleshash{$key}=&thaw_unescape($value);
                   2379:                 }
                   2380:                 my @esc_order = split(/\&/,$orderitems);
                   2381:                 foreach my $item (@esc_order) {
                   2382:                     push(@ruleorder,&unescape($item));
                   2383:                 }
                   2384:             }
                   2385:         }
                   2386:     }
                   2387:     return (\%ruleshash,\@ruleorder);
                   2388: }
                   2389: 
1.976     raeburn  2390: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2391: 
                   2392: sub get_domain_defaults {
1.1240    raeburn  2393:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2394:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2395:     my $cachetime = 60*60*24;
1.1240    raeburn  2396:     unless ($ignore_cache) {
                   2397:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2398:         if (defined($cached)) {
                   2399:             if (ref($result) eq 'HASH') {
                   2400:                 return %{$result};
                   2401:             }
1.943     raeburn  2402:         }
                   2403:     }
                   2404:     my %domdefaults;
                   2405:     my %domconfig =
1.989     raeburn  2406:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2407:                                   'requestcourses','inststatus',
1.1183    raeburn  2408:                                   'coursedefaults','usersessions',
1.1258    raeburn  2409:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2410:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2411:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2412:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2413:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2414:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2415:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2416:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2417:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2418:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2419:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2420:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2421:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2422:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2423:     } else {
                   2424:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2425:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2426:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2427:     }
1.976     raeburn  2428:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2429:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2430:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2431:         } else {
                   2432:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2433:         }
1.1177    raeburn  2434:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2435:         foreach my $item (@usertools) {
                   2436:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2437:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2438:             }
                   2439:         }
1.1229    raeburn  2440:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2441:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2442:         }
1.976     raeburn  2443:     }
1.985     raeburn  2444:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2445:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2446:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2447:         }
                   2448:     }
1.1183    raeburn  2449:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2450:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2451:     }
1.989     raeburn  2452:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2453:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2454:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2455:         }
                   2456:     }
1.1047    raeburn  2457:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2458:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2459:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2460:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2461:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2462:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2463:         }
1.1254    raeburn  2464:         foreach my $type (@coursetypes) {
                   2465:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2466:                 unless ($type eq 'community') {
                   2467:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2468:                 }
                   2469:             }
                   2470:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2471:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2472:             }
1.1277    raeburn  2473:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2474:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2475:                     $domdefaults{$type.'postsubtimeout'} = 
                   2476:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2477:                 }
                   2478:             }
1.1230    raeburn  2479:         }
1.1286    raeburn  2480:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2481:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2482:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2483:                 if (@clonecodes) {
                   2484:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2485:                 }
                   2486:             }
                   2487:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2488:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2489:         }
1.1356    raeburn  2490:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2491:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2492:         } 
1.1047    raeburn  2493:     }
1.1073    raeburn  2494:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2495:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2496:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2497:         }
                   2498:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2499:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2500:         }
1.1279    raeburn  2501:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2502:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2503:         }
1.1073    raeburn  2504:     }
1.1254    raeburn  2505:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2506:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2507:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2508:                             'approval','limit');
                   2509:             foreach my $type (@coursetypes) {
                   2510:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2511:                     my @mgrdc = ();
                   2512:                     foreach my $item (@settings) {
                   2513:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2514:                             push(@mgrdc,$item);
                   2515:                         }
                   2516:                     }
                   2517:                     if (@mgrdc) {
                   2518:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2519:                     }
                   2520:                 }
                   2521:             }
                   2522:         }
                   2523:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2524:             foreach my $type (@coursetypes) {
                   2525:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2526:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2527:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2528:                     }
                   2529:                 }
                   2530:             }
                   2531:         }
                   2532:     }
1.1258    raeburn  2533:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2534:         $domdefaults{'catauth'} = 'std';
                   2535:         $domdefaults{'catunauth'} = 'std';
                   2536:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2537:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2538:         }
                   2539:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2540:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2541:         }
                   2542:     }
1.1315    raeburn  2543:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2544:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2545:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2546:         }
1.1338    raeburn  2547:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2548:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2549:         }
                   2550:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2551:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2552:         }
                   2553:     }
1.1320    raeburn  2554:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2555:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2556:         foreach my $prefix (@prefixes) {
                   2557:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2558:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2559:             }
                   2560:         }
                   2561:     }
1.1314    raeburn  2562:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2563:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2564:     }
1.1332    raeburn  2565:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2566:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2567:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2568:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2569:         }
                   2570:     }
1.1219    raeburn  2571:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2572:     return %domdefaults;
                   2573: }
                   2574: 
1.1311    raeburn  2575: sub course_portal_url {
                   2576:     my ($cnum,$cdom) = @_;
                   2577:     my $chome = &homeserver($cnum,$cdom);
                   2578:     my $hostname = &hostname($chome);
                   2579:     my $protocol = $protocol{$chome};
                   2580:     $protocol = 'http' if ($protocol ne 'https');
                   2581:     my %domdefaults = &get_domain_defaults($cdom);
                   2582:     my $firsturl;
                   2583:     if ($domdefaults{'portal_def'}) {
                   2584:         $firsturl = $domdefaults{'portal_def'};
                   2585:     } else {
                   2586:         $firsturl = $protocol.'://'.$hostname;
                   2587:     }
                   2588:     return $firsturl;
                   2589: }
                   2590: 
1.344     www      2591: # --------------------------------------------------- Assign a key to a student
                   2592: 
                   2593: sub assign_access_key {
1.364     www      2594: #
                   2595: # a valid key looks like uname:udom#comments
                   2596: # comments are being appended
                   2597: #
1.498     www      2598:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2599:     $kdom=
1.620     albertel 2600:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2601:     $knum=
1.620     albertel 2602:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2603:     $cdom=
1.620     albertel 2604:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2605:     $cnum=
1.620     albertel 2606:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2607:     $udom=$env{'user.name'} unless (defined($udom));
                   2608:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2609:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2610:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2611:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2612:                                                   # assigned to this person
                   2613:                                                   # - this should not happen,
1.345     www      2614:                                                   # unless something went wrong
                   2615:                                                   # the first time around
                   2616: # ready to assign
1.364     www      2617:         $logentry=$1.'; '.$logentry;
1.496     www      2618:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2619:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2620: # key now belongs to user
1.346     www      2621: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2622:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2623:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2624:                 return 'ok';
                   2625:             } else {
                   2626:                 return 
                   2627:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2628: 	    }
                   2629:         } else {
                   2630:             return 'error: Could not assign key, try again later.';
                   2631:         }
1.364     www      2632:     } elsif (!$existing{$ckey}) {
1.345     www      2633: # the key does not exist
                   2634: 	return 'error: The key does not exist';
                   2635:     } else {
                   2636: # the key is somebody else's
                   2637: 	return 'error: The key is already in use';
                   2638:     }
1.344     www      2639: }
                   2640: 
1.364     www      2641: # ------------------------------------------ put an additional comment on a key
                   2642: 
                   2643: sub comment_access_key {
                   2644: #
                   2645: # a valid key looks like uname:udom#comments
                   2646: # comments are being appended
                   2647: #
                   2648:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2649:     $cdom=
1.620     albertel 2650:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2651:     $cnum=
1.620     albertel 2652:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2653:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2654:     if ($existing{$ckey}) {
                   2655:         $existing{$ckey}.='; '.$logentry;
                   2656: # ready to assign
1.367     www      2657:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2658:                                                  $cdom,$cnum) eq 'ok') {
                   2659: 	    return 'ok';
                   2660:         } else {
                   2661: 	    return 'error: Count not store comment.';
                   2662:         }
                   2663:     } else {
                   2664: # the key does not exist
                   2665: 	return 'error: The key does not exist';
                   2666:     }
                   2667: }
                   2668: 
1.344     www      2669: # ------------------------------------------------------ Generate a set of keys
                   2670: 
                   2671: sub generate_access_keys {
1.364     www      2672:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2673:     $cdom=
1.620     albertel 2674:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2675:     $cnum=
1.620     albertel 2676:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2677:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2678:     unless (($cdom) && ($cnum)) { return 0; }
                   2679:     if ($number>10000) { return 0; }
                   2680:     sleep(2); # make sure don't get same seed twice
                   2681:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2682:     my $total=0;
                   2683:     for (my $i=1;$i<=$number;$i++) {
                   2684:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2685:                   sprintf("%lx",int(100000*rand)).'-'.
                   2686:                   sprintf("%lx",int(100000*rand));
                   2687:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2688:        $newkey=~s/0/h/g; # and also 0 and O
                   2689:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2690:        if ($existing{$newkey}) {
                   2691:            $i--;
                   2692:        } else {
1.364     www      2693: 	  if (&put('accesskeys',
                   2694:               { $newkey => '# generated '.localtime().
1.620     albertel 2695:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2696:                            '; '.$logentry },
                   2697: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2698:               $total++;
                   2699: 	  }
                   2700:        }
                   2701:     }
1.620     albertel 2702:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2703:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2704:     return $total;
                   2705: }
                   2706: 
                   2707: # ------------------------------------------------------- Validate an accesskey
                   2708: 
                   2709: sub validate_access_key {
                   2710:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2711:     $cdom=
1.620     albertel 2712:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2713:     $cnum=
1.620     albertel 2714:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2715:     $udom=$env{'user.domain'} unless (defined($udom));
                   2716:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2717:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2718:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2719: }
                   2720: 
                   2721: # ------------------------------------- Find the section of student in a course
1.652     albertel 2722: sub devalidate_getsection_cache {
                   2723:     my ($udom,$unam,$courseid)=@_;
                   2724:     my $hashid="$udom:$unam:$courseid";
                   2725:     &devalidate_cache_new('getsection',$hashid);
                   2726: }
1.298     matthew  2727: 
1.815     albertel 2728: sub courseid_to_courseurl {
                   2729:     my ($courseid) = @_;
                   2730:     #already url style courseid
                   2731:     return $courseid if ($courseid =~ m{^/});
                   2732: 
                   2733:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2734: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2735: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2736: 	return "/$cdom/$cnum";
                   2737:     }
                   2738: 
                   2739:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2740:     if (exists($courseinfo{'num'})) {
                   2741: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2742:     }
                   2743: 
                   2744:     return undef;
                   2745: }
                   2746: 
1.298     matthew  2747: sub getsection {
                   2748:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2749:     my $cachetime=1800;
1.551     albertel 2750: 
                   2751:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2752:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2753:     if (defined($cached)) { return $result; }
                   2754: 
1.298     matthew  2755:     my %Pending; 
                   2756:     my %Expired;
                   2757:     #
                   2758:     # Each role can either have not started yet (pending), be active, 
                   2759:     #    or have expired.
                   2760:     #
                   2761:     # If there is an active role, we are done.
                   2762:     #
                   2763:     # If there is more than one role which has not started yet, 
                   2764:     #     choose the one which will start sooner
                   2765:     # If there is one role which has not started yet, return it.
                   2766:     #
                   2767:     # If there is more than one expired role, choose the one which ended last.
                   2768:     # If there is a role which has expired, return it.
                   2769:     #
1.815     albertel 2770:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2771:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2772:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2773:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2774:         my $section=$1;
                   2775:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2776:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2777:         my $now=time;
1.548     albertel 2778:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2779:             $Expired{$end}=$section;
                   2780:             next;
                   2781:         }
1.548     albertel 2782:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2783:             $Pending{$start}=$section;
                   2784:             next;
                   2785:         }
1.599     albertel 2786:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2787:     }
                   2788:     #
                   2789:     # Presumedly there will be few matching roles from the above
                   2790:     # loop and the sorting time will be negligible.
                   2791:     if (scalar(keys(%Pending))) {
                   2792:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2793:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2794:     } 
                   2795:     if (scalar(keys(%Expired))) {
                   2796:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2797:         my $time = pop(@sorted);
1.599     albertel 2798:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2799:     }
1.599     albertel 2800:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2801: }
1.70      www      2802: 
1.599     albertel 2803: sub save_cache {
                   2804:     &purge_remembered();
1.722     albertel 2805:     #&Apache::loncommon::validate_page();
1.620     albertel 2806:     undef(%env);
1.780     albertel 2807:     undef($env_loaded);
1.599     albertel 2808: }
1.452     albertel 2809: 
1.599     albertel 2810: my $to_remember=-1;
                   2811: my %remembered;
                   2812: my %accessed;
                   2813: my $kicks=0;
                   2814: my $hits=0;
1.849     albertel 2815: sub make_key {
                   2816:     my ($name,$id) = @_;
1.872     albertel 2817:     if (length($id) > 65 
                   2818: 	&& length(&escape($id)) > 200) {
                   2819: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2820:     }
1.849     albertel 2821:     return &escape($name.':'.$id);
                   2822: }
                   2823: 
1.599     albertel 2824: sub devalidate_cache_new {
                   2825:     my ($name,$id,$debug) = @_;
                   2826:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2827:     my $remembered_id=$name.':'.$id;
1.849     albertel 2828:     $id=&make_key($name,$id);
1.599     albertel 2829:     $memcache->delete($id);
1.1319    damieng  2830:     delete($remembered{$remembered_id});
                   2831:     delete($accessed{$remembered_id});
1.599     albertel 2832: }
                   2833: 
                   2834: sub is_cached_new {
                   2835:     my ($name,$id,$debug) = @_;
1.1319    damieng  2836:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2837:     if (exists($remembered{$remembered_id})) {
                   2838: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2839: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2840: 	$hits++;
1.1319    damieng  2841: 	return ($remembered{$remembered_id},1);
1.599     albertel 2842:     }
1.1319    damieng  2843:     $id=&make_key($name,$id);
1.599     albertel 2844:     my $value = $memcache->get($id);
                   2845:     if (!(defined($value))) {
                   2846: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2847: 	return (undef,undef);
1.416     albertel 2848:     }
1.599     albertel 2849:     if ($value eq '__undef__') {
                   2850: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2851: 	$value=undef;
                   2852:     }
1.1319    damieng  2853:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2854:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2855:     return ($value,1);
                   2856: }
                   2857: 
                   2858: sub do_cache_new {
                   2859:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2860:     my $remembered_id=$name.':'.$id;
1.849     albertel 2861:     $id=&make_key($name,$id);
1.599     albertel 2862:     my $setvalue=$value;
                   2863:     if (!defined($setvalue)) {
                   2864: 	$setvalue='__undef__';
                   2865:     }
1.623     albertel 2866:     if (!defined($time) ) {
                   2867: 	$time=600;
                   2868:     }
1.599     albertel 2869:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2870:     my $result = $memcache->set($id,$setvalue,$time);
                   2871:     if (! $result) {
1.872     albertel 2872: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2873: 	$memcache->disconnect_all();
1.872     albertel 2874:     }
1.600     albertel 2875:     # need to make a copy of $value
1.1319    damieng  2876:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2877:     return $value;
                   2878: }
                   2879: 
                   2880: sub make_room {
1.1319    damieng  2881:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2882: 
1.1319    damieng  2883:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2884:                                     : $value;
1.599     albertel 2885:     if ($to_remember<0) { return; }
1.1319    damieng  2886:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2887:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2888:     my $to_kick;
                   2889:     my $max_time=0;
                   2890:     foreach my $other (keys(%accessed)) {
                   2891: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2892: 	    $to_kick=$other;
                   2893: 	    $max_time=&tv_interval($accessed{$other});
                   2894: 	}
                   2895:     }
                   2896:     delete($remembered{$to_kick});
                   2897:     delete($accessed{$to_kick});
                   2898:     $kicks++;
                   2899:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2900:     return;
                   2901: }
                   2902: 
1.599     albertel 2903: sub purge_remembered {
1.604     albertel 2904:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2905:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2906:     undef(%remembered);
                   2907:     undef(%accessed);
1.428     albertel 2908: }
1.70      www      2909: # ------------------------------------- Read an entry from a user's environment
                   2910: 
                   2911: sub userenvironment {
                   2912:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2913:     my $items;
                   2914:     foreach my $item (@what) {
                   2915:         $items.=&escape($item).'&';
                   2916:     }
                   2917:     $items=~s/\&$//;
1.70      www      2918:     my %returnhash=();
1.1009    raeburn  2919:     my $uhome = &homeserver($unam,$udom);
                   2920:     unless ($uhome eq 'no_host') {
                   2921:         my @answer=split(/\&/, 
                   2922:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2923:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2924:             return %returnhash;
                   2925:         }
1.1009    raeburn  2926:         my $i;
                   2927:         for ($i=0;$i<=$#what;$i++) {
                   2928: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2929:         }
1.70      www      2930:     }
                   2931:     return %returnhash;
1.1       albertel 2932: }
                   2933: 
1.617     albertel 2934: # ---------------------------------------------------------- Get a studentphoto
                   2935: sub studentphoto {
                   2936:     my ($udom,$unam,$ext) = @_;
                   2937:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2938:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2939:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2940:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2941:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2942:             } else {
                   2943:                 my ($result,$perm_reqd)=
1.707     albertel 2944: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2945:                 if ($result eq 'ok') {
                   2946:                     if (!($perm_reqd eq 'yes')) {
                   2947:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2948:                     }
                   2949:                 }
                   2950:             }
                   2951:         }
                   2952:     } else {
                   2953:         my ($result,$perm_reqd) = 
1.707     albertel 2954: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2955:         if ($result eq 'ok') {
                   2956:             if (!($perm_reqd eq 'yes')) {
                   2957:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2958:             }
                   2959:         }
                   2960:     }
                   2961:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2962: }
                   2963: 
                   2964: sub retrievestudentphoto {
                   2965:     my ($udom,$unam,$ext,$type) = @_;
                   2966:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2967:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2968:     if ($ret eq 'ok') {
                   2969:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2970:         if ($type eq 'thumbnail') {
                   2971:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2972:         }
                   2973:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2974:         return $tokenurl;
                   2975:     } else {
                   2976:         if ($type eq 'thumbnail') {
                   2977:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2978:         } else { 
                   2979:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2980:         }
1.617     albertel 2981:     }
                   2982: }
                   2983: 
1.263     www      2984: # -------------------------------------------------------------------- New chat
                   2985: 
                   2986: sub chatsend {
1.724     raeburn  2987:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2988:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2989:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2990:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2991:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2992: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2993: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2994: }
                   2995: 
                   2996: # ------------------------------------------ Find current version of a resource
                   2997: 
                   2998: sub getversion {
                   2999:     my $fname=&clutter(shift);
1.1189    raeburn  3000:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3001:     return &currentversion(&filelocation('',$fname));
                   3002: }
                   3003: 
                   3004: sub currentversion {
                   3005:     my $fname=shift;
                   3006:     my $author=$fname;
                   3007:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3008:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3009:     my $home=&homeserver($uname,$udom);
1.292     www      3010:     if ($home eq 'no_host') { 
                   3011:         return -1; 
                   3012:     }
1.1112    www      3013:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3014:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3015: 	return -1;
                   3016:     }
1.1112    www      3017:     return $answer;
1.263     www      3018: }
                   3019: 
1.1111    www      3020: #
                   3021: # Return special version number of resource if set by override, empty otherwise
                   3022: #
                   3023: sub usedversion {
                   3024:     my $fname=shift;
                   3025:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3026:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3027:     if ($urlversion) { return $urlversion; }
                   3028:     return '';
                   3029: }
                   3030: 
1.1       albertel 3031: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3032: 
1.1       albertel 3033: sub subscribe {
                   3034:     my $fname=shift;
1.761     raeburn  3035:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3036:     $fname=~s/[\n\r]//g;
1.1       albertel 3037:     my $author=$fname;
                   3038:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3039:     my ($udom,$uname)=split(/\//,$author);
                   3040:     my $home=homeserver($uname,$udom);
1.335     albertel 3041:     if ($home eq 'no_host') {
                   3042:         return 'not_found';
1.1       albertel 3043:     }
                   3044:     my $answer=reply("sub:$fname",$home);
1.64      www      3045:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3046: 	$answer.=' by '.$home;
                   3047:     }
1.1       albertel 3048:     return $answer;
                   3049: }
                   3050:     
1.8       www      3051: # -------------------------------------------------------------- Replicate file
                   3052: 
                   3053: sub repcopy {
                   3054:     my $filename=shift;
1.23      www      3055:     $filename=~s/\/+/\//g;
1.1142    raeburn  3056:     my $londocroot = $perlvar{'lonDocRoot'};
                   3057:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3058:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3059:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3060: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3061: 	return &repcopy_userfile($filename);
                   3062:     }
1.532     albertel 3063:     $filename=~s/[\n\r]//g;
1.8       www      3064:     my $transname="$filename.in.transfer";
1.828     www      3065: # FIXME: this should flock
1.607     raeburn  3066:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3067:     my $remoteurl=subscribe($filename);
1.64      www      3068:     if ($remoteurl =~ /^con_lost by/) {
                   3069: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3070:            return 'unavailable';
1.8       www      3071:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3072: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3073: 	   return 'not_found';
1.64      www      3074:     } elsif ($remoteurl =~ /^rejected by/) {
                   3075: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3076:            return 'forbidden';
1.20      www      3077:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3078:            return 'ok';
1.8       www      3079:     } else {
1.290     www      3080:         my $author=$filename;
                   3081:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3082:         my ($udom,$uname)=split(/\//,$author);
                   3083:         my $home=homeserver($uname,$udom);
                   3084:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3085:            my @parts=split(/\//,$filename);
                   3086:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3087:            if ($path ne "$londocroot/res") {
1.8       www      3088:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3089: 	       return 'bad_request';
1.8       www      3090:            }
                   3091:            my $count;
                   3092:            for ($count=5;$count<$#parts;$count++) {
                   3093:                $path.="/$parts[$count]";
                   3094:                if ((-e $path)!=1) {
                   3095: 		   mkdir($path,0777);
                   3096:                }
                   3097:            }
                   3098:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3099:            my $response;
                   3100:            if ($remoteurl =~ m{/raw/}) {
                   3101:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3102:            } else {
                   3103:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3104:            }
1.8       www      3105:            if ($response->is_error()) {
                   3106: 	       unlink($transname);
                   3107:                my $message=$response->status_line;
1.672     albertel 3108:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3109:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3110:                return 'unavailable';
1.8       www      3111:            } else {
1.16      www      3112: 	       if ($remoteurl!~/\.meta$/) {
                   3113:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3114:                   my $mresponse;
                   3115:                   if ($remoteurl =~ m{/raw/}) {
                   3116:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3117:                   } else {
                   3118:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3119:                   }
1.16      www      3120:                   if ($mresponse->is_error()) {
                   3121: 		      unlink($filename.'.meta');
                   3122:                       &logthis(
1.672     albertel 3123:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3124:                   }
                   3125: 	       }
1.8       www      3126:                rename($transname,$filename);
1.607     raeburn  3127:                return 'ok';
1.8       www      3128:            }
1.290     www      3129:        }
1.8       www      3130:     }
1.330     www      3131: }
                   3132: 
                   3133: # ------------------------------------------------ Get server side include body
                   3134: sub ssi_body {
1.381     albertel 3135:     my ($filelink,%form)=@_;
1.606     matthew  3136:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3137:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3138:     }
1.953     www      3139:     my $output='';
                   3140:     my $response;
1.980     raeburn  3141:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3142:        ($output,$response)=&externalssi($filelink);
1.953     www      3143:     } else {
1.1004    droeschl 3144:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3145:        $filelink .= 'inhibitmenu=yes';
1.953     www      3146:        ($output,$response)=&ssi($filelink,%form);
                   3147:     }
1.778     albertel 3148:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3149:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3150:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3151:     if (wantarray) {
                   3152:         return ($output, $response);
                   3153:     } else {
                   3154:         return $output;
                   3155:     }
1.8       www      3156: }
                   3157: 
1.15      www      3158: # --------------------------------------------------------- Server Side Include
                   3159: 
1.782     albertel 3160: sub absolute_url {
                   3161:     my ($host_name) = @_;
                   3162:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3163:     if ($host_name eq '') {
                   3164: 	$host_name = $ENV{'SERVER_NAME'};
                   3165:     }
                   3166:     return $protocol.$host_name;
                   3167: }
                   3168: 
1.942     foxr     3169: #
                   3170: #   Server side include.
                   3171: # Parameters:
                   3172: #  fn     Possibly encrypted resource name/id.
                   3173: #  form   Hash that describes how the rendering should be done
                   3174: #         and other things.
1.944     foxr     3175: # Returns:
1.950     raeburn  3176: #   Scalar context: The content of the response.
                   3177: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3178: #     
1.15      www      3179: sub ssi {
                   3180: 
1.944     foxr     3181:     my ($fn,%form)=@_;
1.23      www      3182:     my $request;
1.711     albertel 3183: 
                   3184:     $form{'no_update_last_known'}=1;
1.895     albertel 3185:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3186:     if (%form) {
1.782     albertel 3187:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3188:       $request->content(join('&',map { 
                   3189:             my $name = escape($_);
                   3190:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3191:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3192:             : &escape($form{$_}) );    
                   3193:         } keys(%form)));
1.23      www      3194:     } else {
1.782     albertel 3195:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3196:     }
                   3197: 
1.15      www      3198:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3199:     my $lonhost = $perlvar{'lonHostID'};
1.1385  ! raeburn  3200:     my $islocal;
        !          3201:     if (($env{'request.course.id'}) &&
        !          3202:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
        !          3203:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
        !          3204:         ($form{'grade_symb'} ne '') &&
        !          3205:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
        !          3206:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
        !          3207:         $islocal = 1;
        !          3208:     }
1.1384    raeburn  3209:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385  ! raeburn  3210:                                                 '','','',$islocal);
1.1182    foxr     3211: 
1.944     foxr     3212:     if (wantarray) {
1.1345    raeburn  3213: 	return ($response->content, $response);
1.944     foxr     3214:     } else {
1.1345    raeburn  3215: 	return $response->content;
1.942     foxr     3216:     }
1.324     www      3217: }
                   3218: 
                   3219: sub externalssi {
                   3220:     my ($url)=@_;
                   3221:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3222:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3223:     if (wantarray) {
                   3224:         return ($response->content, $response);
                   3225:     } else {
                   3226:         return $response->content;
                   3227:     }
1.15      www      3228: }
1.254     www      3229: 
1.1354    raeburn  3230: 
                   3231: # If the local copy of a replicated resource is outdated, trigger a  
                   3232: # connection from the homeserver to flush the delayed queue. If no update 
                   3233: # happens, remove local copies of outdated resource (and corresponding
                   3234: # metadata file).
                   3235: 
1.1352    raeburn  3236: sub remove_stale_resfile {
                   3237:     my ($url) = @_;
1.1354    raeburn  3238:     my $removed;
1.1352    raeburn  3239:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3240:         my $audom = $1;
                   3241:         my $auname = $2;
1.1353    raeburn  3242:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3243:             my $homeserver = &homeserver($auname,$audom);
                   3244:             unless (($homeserver eq 'no_host') ||
                   3245:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3246:                 my $fname = &filelocation('',$url);
                   3247:                 if (-e $fname) {
                   3248:                     my $protocol = $protocol{$homeserver};
                   3249:                     $protocol = 'http' if ($protocol ne 'https');
                   3250:                     my $hostname = &hostname($homeserver);
                   3251:                     if ($hostname) {
                   3252:                         my $uri = &declutter($url);
                   3253:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3254:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3255:                         if ($response->is_success()) {
                   3256:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3257:                             my $locmodtime = (stat($fname))[9];
                   3258:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3259:                                 my $stale;
                   3260:                                 my $answer = &reply('pong',$homeserver);
                   3261:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3262:                                     sleep(0.2);
                   3263:                                     $locmodtime = (stat($fname))[9];
                   3264:                                     if ($locmodtime < $remmodtime) {
                   3265:                                         my $posstransfer = $fname.'.in.transfer';
                   3266:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3267:                                             $removed = 1;
                   3268:                                         } else {
                   3269:                                             $stale = 1;
                   3270:                                         }
                   3271:                                     } else {
                   3272:                                         $removed = 1;
                   3273:                                     }
                   3274:                                 } else {
                   3275:                                     $stale = 1;
                   3276:                                 }
                   3277:                                 if ($stale) {
                   3278:                                     unlink($fname);
                   3279:                                     if ($uri!~/\.meta$/) {
                   3280:                                         unlink($fname.'.meta');
                   3281:                                     }
                   3282:                                     &reply("unsub:$fname",$homeserver);
                   3283:                                     $removed = 1;
1.1352    raeburn  3284:                                 }
                   3285:                             }
                   3286:                         }
                   3287:                     }
                   3288:                 }
                   3289:             }
                   3290:         }
                   3291:     }
1.1354    raeburn  3292:     return $removed;
1.1352    raeburn  3293: }
                   3294: 
1.492     albertel 3295: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3296: 
                   3297: sub allowuploaded {
                   3298:     my ($srcurl,$url)=@_;
                   3299:     $url=&clutter(&declutter($url));
                   3300:     my $dir=$url;
                   3301:     $dir=~s/\/[^\/]+$//;
                   3302:     my %httpref=();
                   3303:     my $httpurl=&hreflocation('',$url);
                   3304:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3305:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3306: }
1.477     raeburn  3307: 
1.1193    raeburn  3308: #
                   3309: # Determine if the current user should be able to edit a particular resource,
                   3310: # when viewing in course context.
                   3311: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3312: #     Functions.
                   3313: # (b) When displaying folder contents in course editor, used to determine if
                   3314: #     "Edit" link will be displayed alongside resource.
                   3315: #
1.1196    raeburn  3316: #  input: six args -- filename (decluttered), course number, course domain,
                   3317: #                   url, symb (if registered) and group (if this is a group
                   3318: #                   item -- e.g., bulletin board, group page etc.).
                   3319: #  output: array of five scalars -- 
1.1193    raeburn  3320: #          $cfile -- url for file editing if editable on current server
                   3321: #          $home -- homeserver of resource (i.e., for author if published,
                   3322: #                                           or course if uploaded.).
                   3323: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3324: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3325: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3326: #
                   3327: 
                   3328: sub can_edit_resource {
1.1194    raeburn  3329:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3330:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3331: #
                   3332: # For aboutme pages user can only edit his/her own.
                   3333: #
1.1199    raeburn  3334:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3335:         my ($sdom,$sname) = ($1,$2);
                   3336:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3337:             $home = $env{'user.home'};
                   3338:             $cfile = $resurl;
                   3339:             if ($env{'form.forceedit'}) {
                   3340:                 $forceview = 1;
                   3341:             } else {
                   3342:                 $forceedit = 1;
                   3343:             }
                   3344:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3345:         } else {
                   3346:             return;
                   3347:         }
                   3348:     }
                   3349: 
                   3350:     if ($env{'request.course.id'}) {
                   3351:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3352:         if ($group ne '') {
                   3353: # if this is a group homepage or group bulletin board, check group privs
                   3354:             my $allowed = 0;
1.1197    raeburn  3355:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3356:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3357:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3358:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3359:                     $allowed = 1;
                   3360:                 }
1.1197    raeburn  3361:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3362:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3363:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3364:                     $allowed = 1;
                   3365:                 }
                   3366:             }
                   3367:             if ($allowed) {
                   3368:                 $home=&homeserver($cnum,$cdom);
                   3369:                 if ($env{'form.forceedit'}) {
                   3370:                     $forceview = 1;
                   3371:                 } else {
                   3372:                     $forceedit = 1;
                   3373:                 }
                   3374:                 $cfile = $resurl;
                   3375:             } else {
                   3376:                 return;
                   3377:             }
                   3378:         } else {
1.1208    raeburn  3379:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3380:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3381:                     return;
                   3382:                 }
                   3383:             } elsif (!$crsedit) {
1.1194    raeburn  3384: #
                   3385: # No edit allowed where CC has switched to student role.
                   3386: #
                   3387:                 return;
                   3388:             }
                   3389:         }
                   3390:     }
                   3391: 
1.1193    raeburn  3392:     if ($file ne '') {
                   3393:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3394:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3395:                 $uploaded = 1;
                   3396:                 $incourse = 1;
1.1193    raeburn  3397:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3398:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3399:                     if ($env{'form.forceedit'}) {
                   3400:                         $forceview = 1;
                   3401:                     } else {
                   3402:                         $forceedit = 1;
                   3403:                     }
1.1194    raeburn  3404:                 }
                   3405:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3406:                 $incourse = 1;
                   3407:                 if ($env{'form.forceedit'}) {
                   3408:                     $forceview = 1;
                   3409:                 } else {
                   3410:                     $forceedit = 1;
                   3411:                 }
                   3412:                 $cfile = $resurl;
                   3413:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3414:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3415:                     $incourse = 1;
                   3416:                     if ($env{'form.forceedit'}) {
                   3417:                         $forceview = 1;
                   3418:                     } else {
                   3419:                         $forceedit = 1;
                   3420:                     }
                   3421:                     $cfile = $resurl;
1.1199    raeburn  3422:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3423:                     $incourse = 1;
                   3424:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3425:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3426:                     $incourse = 1;
1.1199    raeburn  3427:                     if ($env{'form.forceedit'}) {
                   3428:                         $forceview = 1;
                   3429:                     } else {
                   3430:                         $forceedit = 1;
                   3431:                     }
                   3432:                     $cfile = $resurl;
1.1343    raeburn  3433:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3434:                     $incourse = 1;
                   3435:                     if ($env{'form.forceedit'}) {
                   3436:                         $forceview = 1;
                   3437:                     } else {
                   3438:                         $forceedit = 1;
                   3439:                     }
                   3440:                     $cfile = $resurl;
1.1208    raeburn  3441:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3442:                     $incourse = 1;
                   3443:                     if ($env{'form.forceedit'}) {
                   3444:                         $forceview = 1;
                   3445:                     } else {
                   3446:                         $forceedit = 1;
                   3447:                     }
                   3448:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3449:                 }
                   3450:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3451:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3452:                 if (&is_on_map($template)) { 
                   3453:                     $incourse = 1;
                   3454:                     $forceview = 1;
                   3455:                     $cfile = $template;
1.1193    raeburn  3456:                 }
1.1199    raeburn  3457:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3458:                     $incourse = 1;
                   3459:                     if ($env{'form.forceedit'}) {
                   3460:                         $forceview = 1;
                   3461:                     } else {
                   3462:                         $forceedit = 1;
                   3463:                     }
                   3464:                     $cfile = $resurl;
1.1343    raeburn  3465:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3466:                 $incourse = 1;
                   3467:                 if ($env{'form.forceedit'}) {
                   3468:                     $forceview = 1;
                   3469:                 } else {
                   3470:                     $forceedit = 1;
                   3471:                 }
                   3472:                 $cfile = $resurl;
1.1199    raeburn  3473:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3474:                 $incourse = 1;
                   3475:                 $forceview = 1;
                   3476:                 if ($symb) {
                   3477:                     my ($map,$id,$res)=&decode_symb($symb);
                   3478:                     $env{'request.symb'} = $symb;
                   3479:                     $cfile = &clutter($res);
                   3480:                 } else {
                   3481:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3482:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3483:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3484:                         $cfile = '/adm/wrapper'.$escfile;
                   3485:                     } else {
                   3486:                         $escfile =~ s{^http://}{};
                   3487:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3488:                     }
1.1199    raeburn  3489:                 }
1.1234    raeburn  3490:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3491:                 if ($env{'form.forceedit'}) {
                   3492:                     $forceview = 1;
                   3493:                 } else {
                   3494:                     $forceedit = 1;
                   3495:                 }
                   3496:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3497:             }
                   3498:         }
1.1194    raeburn  3499:         if ($uploaded || $incourse) {
                   3500:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3501:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3502:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3503:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3504:             # Check that the user has permission to edit this resource
                   3505:             my $setpriv = 1;
                   3506:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3507:             if (defined($cfudom)) {
                   3508:                 $home=&homeserver($cfuname,$cfudom);
                   3509:                 $cfile=$file;
                   3510:             }
                   3511:         }
1.1194    raeburn  3512:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3513:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3514:             my @ids=&current_machine_ids();
                   3515:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3516:                 $switchserver=1;
                   3517:             }
                   3518:         }
                   3519:     }
1.1194    raeburn  3520:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3521: }
                   3522: 
                   3523: sub is_course_upload {
                   3524:     my ($file,$cnum,$cdom) = @_;
                   3525:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3526:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3527:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3528:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3529:         return 1;
                   3530:     }
                   3531:     return;
                   3532: }
                   3533: 
1.1194    raeburn  3534: sub in_course {
1.1195    raeburn  3535:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3536:     if ($hideprivileged) {
                   3537:         my $skipuser;
1.1219    raeburn  3538:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3539:         my @possdoms = ($cdom);  
                   3540:         if ($coursehash{'checkforpriv'}) { 
                   3541:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3542:         }
                   3543:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3544:             $skipuser = 1;
                   3545:             if ($coursehash{'nothideprivileged'}) {
                   3546:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3547:                     my $user;
                   3548:                     if ($item =~ /:/) {
                   3549:                         $user = $item;
                   3550:                     } else {
                   3551:                         $user = join(':',split(/[\@]/,$item));
                   3552:                     }
                   3553:                     if ($user eq $uname.':'.$udom) {
                   3554:                         undef($skipuser);
                   3555:                         last;
                   3556:                     }
                   3557:                 }
                   3558:             }
                   3559:             if ($skipuser) {
                   3560:                 return 0;
                   3561:             }
                   3562:         }
                   3563:     }
1.1194    raeburn  3564:     $type ||= 'any';
                   3565:     if (!defined($cdom) || !defined($cnum)) {
                   3566:         my $cid  = $env{'request.course.id'};
                   3567:         $cdom = $env{'course.'.$cid.'.domain'};
                   3568:         $cnum = $env{'course.'.$cid.'.num'};
                   3569:     }
                   3570:     my $typesref;
1.1195    raeburn  3571:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3572:         $typesref = ['active','previous','future'];
                   3573:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3574:         $typesref = [$type];
                   3575:     }
                   3576:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3577:                               $typesref,undef,[$cdom]);
                   3578:     my ($tmp) = keys(%roles);
                   3579:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3580:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3581:     if (@course_roles > 0) {
                   3582:         return 1;
                   3583:     }
                   3584:     return 0;
                   3585: }
                   3586: 
1.478     albertel 3587: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3588: # input: action, courseID, current domain, intended
1.637     raeburn  3589: #        path to file, source of file, instruction to parse file for objects,
                   3590: #        ref to hash for embedded objects,
                   3591: #        ref to hash for codebase of java objects.
1.1095    raeburn  3592: #        reference to scalar to accommodate mime type determined
                   3593: #          from File::MMagic if $parser = parse.
1.637     raeburn  3594: #
1.485     raeburn  3595: # output: url to file (if action was uploaddoc), 
                   3596: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3597: #
1.478     albertel 3598: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3599: # course.
1.477     raeburn  3600: #
1.478     albertel 3601: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3602: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3603: #          course's home server.
1.477     raeburn  3604: #
1.478     albertel 3605: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3606: #          be copied from $source (current location) to 
                   3607: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3608: #         and will then be copied to
                   3609: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3610: #         course's home server.
1.485     raeburn  3611: #
1.481     raeburn  3612: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3613: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3614: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3615: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3616: #         in course's home server.
1.637     raeburn  3617: #
1.477     raeburn  3618: 
                   3619: sub process_coursefile {
1.1095    raeburn  3620:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3621:         $mimetype)=@_;
1.477     raeburn  3622:     my $fetchresult;
1.638     albertel 3623:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3624:     if ($action eq 'propagate') {
1.638     albertel 3625:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3626: 			     $home);
1.481     raeburn  3627:     } else {
1.477     raeburn  3628:         my $fpath = '';
                   3629:         my $fname = $file;
1.478     albertel 3630:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3631:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3632:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3633:         if ($action eq 'copy') {
                   3634:             if ($source eq '') {
                   3635:                 $fetchresult = 'no source file';
                   3636:                 return $fetchresult;
                   3637:             } else {
                   3638:                 my $destination = $filepath.'/'.$fname;
                   3639:                 rename($source,$destination);
                   3640:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3641:                                  $home);
1.481     raeburn  3642:             }
                   3643:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3644:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3645:             print $fh $env{'form.'.$source};
1.481     raeburn  3646:             close($fh);
1.637     raeburn  3647:             if ($parser eq 'parse') {
1.1024    raeburn  3648:                 my $mm = new File::MMagic;
1.1095    raeburn  3649:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3650:                 if ($type eq 'text/html') {
1.1024    raeburn  3651:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3652:                     unless ($parse_result eq 'ok') {
                   3653:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3654:                     }
1.637     raeburn  3655:                 }
1.1095    raeburn  3656:                 if (ref($mimetype)) {
                   3657:                     $$mimetype = $type;
                   3658:                 } 
1.637     raeburn  3659:             }
1.477     raeburn  3660:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3661:                                  $home);
1.481     raeburn  3662:             if ($fetchresult eq 'ok') {
                   3663:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3664:             } else {
                   3665:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3666:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3667:                 return '/adm/notfound.html';
                   3668:             }
1.477     raeburn  3669:         }
                   3670:     }
1.485     raeburn  3671:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3672:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3673:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3674:     }
                   3675:     return $fetchresult;
                   3676: }
                   3677: 
1.637     raeburn  3678: sub build_filepath {
                   3679:     my ($fpath) = @_;
                   3680:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3681:     unless ($fpath eq '') {
                   3682:         my @parts=split('/',$fpath);
                   3683:         foreach my $part (@parts) {
                   3684:             $filepath.= '/'.$part;
                   3685:             if ((-e $filepath)!=1) {
                   3686:                 mkdir($filepath,0777);
                   3687:             }
                   3688:         }
                   3689:     }
                   3690:     return $filepath;
                   3691: }
                   3692: 
                   3693: sub store_edited_file {
1.638     albertel 3694:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3695:     my $file = $primary_url;
                   3696:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3697:     my $fpath = '';
                   3698:     my $fname = $file;
                   3699:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3700:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3701:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3702:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3703:     print $fh $content;
                   3704:     close($fh);
1.638     albertel 3705:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3706:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3707: 			  $home);
1.637     raeburn  3708:     if ($$fetchresult eq 'ok') {
                   3709:         return '/uploaded/'.$fpath.'/'.$fname;
                   3710:     } else {
1.638     albertel 3711:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3712: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3713:         return '/adm/notfound.html';
                   3714:     }
                   3715: }
                   3716: 
1.531     albertel 3717: sub clean_filename {
1.831     albertel 3718:     my ($fname,$args)=@_;
1.315     www      3719: # Replace Windows backslashes by forward slashes
1.257     www      3720:     $fname=~s/\\/\//g;
1.831     albertel 3721:     if (!$args->{'keep_path'}) {
                   3722:         # Get rid of everything but the actual filename
                   3723: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3724:     }
1.315     www      3725: # Replace spaces by underscores
                   3726:     $fname=~s/\s+/\_/g;
                   3727: # Replace all other weird characters by nothing
1.831     albertel 3728:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3729: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3730: # numbers
                   3731:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3732:     return $fname;
                   3733: }
1.1051    raeburn  3734: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3735: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3736: # image with the same aspect ratio as the original, but with dimensions which do 
                   3737: # not exceed $resizewidth and $resizeheight.
                   3738:  
1.984     neumanie 3739: sub resizeImage {
1.1051    raeburn  3740:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3741:     my $ima = Image::Magick->new;
                   3742:     my $resized;
                   3743:     if (-e $img_path) {
                   3744:         $ima->Read($img_path);
                   3745:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3746:             my $width = $ima->Get('width');
                   3747:             my $height = $ima->Get('height');
                   3748:             if ($width > $resizewidth) {
                   3749: 	        my $factor = $width/$resizewidth;
                   3750:                 my $newheight = $height/$factor;
                   3751:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3752:                 $resized = 1;
                   3753:             }
                   3754:         }
                   3755:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3756:             my $width = $ima->Get('width');
                   3757:             my $height = $ima->Get('height');
                   3758:             if ($height > $resizeheight) {
                   3759:                 my $factor = $height/$resizeheight;
                   3760:                 my $newwidth = $width/$factor;
                   3761:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3762:                 $resized = 1;
                   3763:             }
                   3764:         }
                   3765:         if ($resized) {
                   3766:             $ima->Write($img_path);
                   3767:         }
                   3768:     }
                   3769:     return;
1.977     amueller 3770: }
                   3771: 
1.608     albertel 3772: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3773: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3774: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3775: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3776: #                                    canceloverwrite, or ''. 
                   3777: #                   if 'coursedoc': upload to the current course
                   3778: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3779: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3780: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3781: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3782: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3783: #        $allfiles - reference to hash for embedded objects
                   3784: #        $codebase - reference to hash for codebase of java objects
                   3785: #        $desuname - username for permanent storage of uploaded file
                   3786: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3787: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3788: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3789: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3790: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3791: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3792: #                    from File::MMagic.
1.858     raeburn  3793: # 
1.686     albertel 3794: # output: url of file in userspace, or error: <message> 
                   3795: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3796: 
1.531     albertel 3797: sub userfileupload {
1.1090    raeburn  3798:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3799:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3800:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3801:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3802:     $fname=&clean_filename($fname);
1.1090    raeburn  3803:     # See if there is anything left
1.257     www      3804:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3805:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3806:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3807:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3808:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3809:         my $now = time;
1.1090    raeburn  3810:         my $filepath;
1.1095    raeburn  3811:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3812:              $filepath = 'tmp/helprequests/'.$now;
                   3813:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3814:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3815:                          '_'.$env{'user.domain'}.'/pending';
                   3816:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3817:             my ($docuname,$docudom);
1.1350    raeburn  3818:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3819:                 $docudom = $destudom;
                   3820:             } else {
                   3821:                 $docudom = $env{'user.domain'};
                   3822:             }
1.1350    raeburn  3823:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3824:                 $docuname = $destuname;
                   3825:             } else {
                   3826:                 $docuname = $env{'user.name'};
                   3827:             }
                   3828:             if (exists($env{'form.group'})) {
                   3829:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3830:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3831:             }
                   3832:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3833:             if ($context eq 'canceloverwrite') {
                   3834:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3835:                 if (-e  $tempfile) {
                   3836:                     my @info = stat($tempfile);
                   3837:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3838:                         unlink($tempfile);
                   3839:                     }
                   3840:                 }
                   3841:                 return;
1.523     raeburn  3842:             }
                   3843:         }
1.1090    raeburn  3844:         # Create the directory if not present
1.741     raeburn  3845:         my @parts=split(/\//,$filepath);
                   3846:         my $fullpath = $perlvar{'lonDaemons'};
                   3847:         for (my $i=0;$i<@parts;$i++) {
                   3848:             $fullpath .= '/'.$parts[$i];
                   3849:             if ((-e $fullpath)!=1) {
                   3850:                 mkdir($fullpath,0777);
                   3851:             }
                   3852:         }
1.1359    raeburn  3853:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3854:         print $fh $env{'form.'.$formname};
                   3855:         close($fh);
1.1090    raeburn  3856:         if ($context eq 'existingfile') {
                   3857:             my @info = stat($fullpath.'/'.$fname);
                   3858:             return ($fullpath.'/'.$fname,$info[9]);
                   3859:         } else {
                   3860:             return $fullpath.'/'.$fname;
                   3861:         }
1.523     raeburn  3862:     }
1.995     raeburn  3863:     if ($subdir eq 'scantron') {
                   3864:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3865:     } else {
1.995     raeburn  3866:         $fname="$subdir/$fname";
                   3867:     }
1.1090    raeburn  3868:     if ($context eq 'coursedoc') {
1.638     albertel 3869: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3870: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3871:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3872:             return &finishuserfileupload($docuname,$docudom,
                   3873: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3874: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3875:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3876:         } else {
1.1218    raeburn  3877:             if ($env{'form.folder'}) {
                   3878:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3879:             }
1.638     albertel 3880:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3881: 				       $fname,$formname,$parser,
1.1095    raeburn  3882: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3883:         }
1.719     banghart 3884:     } elsif (defined($destuname)) {
                   3885:         my $docuname=$destuname;
                   3886:         my $docudom=$destudom;
1.860     raeburn  3887: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3888: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3889:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3890:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3891:     } else {
1.638     albertel 3892:         my $docuname=$env{'user.name'};
                   3893:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3894:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3895:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3896:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3897:         }
1.860     raeburn  3898: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3899: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3900:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3901:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3902:     }
1.271     www      3903: }
                   3904: 
                   3905: sub finishuserfileupload {
1.860     raeburn  3906:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3907:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3908:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3909:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3910:   
1.860     raeburn  3911:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3912:     $file=$fname;
                   3913:     if ($fname=~m|/|) {
                   3914:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3915: 	$path.=$fnamepath.'/';
                   3916:     }
1.259     www      3917:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3918:     my $count;
                   3919:     for ($count=4;$count<=$#parts;$count++) {
                   3920:         $filepath.="/$parts[$count]";
                   3921:         if ((-e $filepath)!=1) {
                   3922: 	    mkdir($filepath,0777);
                   3923:         }
                   3924:     }
1.984     neumanie 3925: 
1.258     www      3926: # Save the file
                   3927:     {
1.1359    raeburn  3928: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3929: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3930: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3931: 	    return '/adm/notfound.html';
                   3932: 	}
1.1090    raeburn  3933:         if ($context eq 'overwrite') {
1.1117    foxr     3934:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3935:             my $target = $filepath.'/'.$file;
                   3936:             if (-e $source) {
                   3937:                 my @info = stat($source);
                   3938:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3939:                     unless (&File::Copy::move($source,$target)) {
                   3940:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3941:                         return "Moving from $source failed";
                   3942:                     }
                   3943:                 } else {
                   3944:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3945:                 }
                   3946:             } else {
                   3947:                 return "Temporary file: $source missing";
                   3948:             }
                   3949:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3950: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3951: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3952: 	    return '/adm/notfound.html';
                   3953: 	}
1.570     albertel 3954: 	close(FH);
1.1051    raeburn  3955:         if ($resizewidth && $resizeheight) {
                   3956:             my $mm = new File::MMagic;
                   3957:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3958:             if ($mime_type =~ m{^image/}) {
                   3959: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3960:             }  
1.977     amueller 3961: 	}
1.258     www      3962:     }
1.1152    raeburn  3963:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3964:         if (ref($mimetype)) {
                   3965:             if ($$mimetype eq '') {
                   3966:                 my $mm = new File::MMagic;
                   3967:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3968:                 $$mimetype = $type;
                   3969:             }
                   3970:         }
                   3971:     }
1.637     raeburn  3972:     if ($parser eq 'parse') {
1.1152    raeburn  3973:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3974:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3975:                                                        $allfiles,$codebase);
                   3976:             unless ($parse_result eq 'ok') {
                   3977:                 &logthis('Failed to parse '.$filepath.$file.
                   3978: 	   	         ' for embedded media: '.$parse_result); 
                   3979:             }
1.637     raeburn  3980:         }
                   3981:     }
1.860     raeburn  3982:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3983:         my $input = $filepath.'/'.$file;
                   3984:         my $output = $filepath.'/'.'tn-'.$file;
                   3985:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  3986:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3987:         system({$args[0]} @args);
1.860     raeburn  3988:         if (-e $filepath.'/'.'tn-'.$file) {
                   3989:             $fetchthumb  = 1; 
                   3990:         }
                   3991:     }
1.858     raeburn  3992:  
1.259     www      3993: # Notify homeserver to grep it
                   3994: #
1.984     neumanie 3995:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3996:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3997:     if ($fetchresult eq 'ok') {
1.860     raeburn  3998:         if ($fetchthumb) {
                   3999:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4000:             if ($thumbresult ne 'ok') {
                   4001:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4002:                          $docuhome.': '.$thumbresult);
                   4003:             }
                   4004:         }
1.259     www      4005: #
1.258     www      4006: # Return the URL to it
1.494     albertel 4007:         return '/uploaded/'.$path.$file;
1.263     www      4008:     } else {
1.494     albertel 4009:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4010: 		 ': '.$fetchresult);
1.263     www      4011:         return '/adm/notfound.html';
1.858     raeburn  4012:     }
1.493     albertel 4013: }
                   4014: 
1.637     raeburn  4015: sub extract_embedded_items {
1.961     raeburn  4016:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4017:     my @state = ();
1.1164    raeburn  4018:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4019:     my %javafiles = (
                   4020:                       codebase => '',
                   4021:                       code => '',
                   4022:                       archive => ''
                   4023:                     );
                   4024:     my %mediafiles = (
                   4025:                       src => '',
                   4026:                       movie => '',
                   4027:                      );
1.648     raeburn  4028:     my $p;
                   4029:     if ($content) {
                   4030:         $p = HTML::LCParser->new($content);
                   4031:     } else {
1.961     raeburn  4032:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4033:     }
1.641     albertel 4034:     while (my $t=$p->get_token()) {
1.640     albertel 4035: 	if ($t->[0] eq 'S') {
                   4036: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4037: 	    push(@state, $tagname);
1.648     raeburn  4038:             if (lc($tagname) eq 'allow') {
                   4039:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4040:             }
1.640     albertel 4041: 	    if (lc($tagname) eq 'img') {
                   4042: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4043: 	    }
1.886     albertel 4044: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4045:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4046:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4047:                 }
1.886     albertel 4048: 	    }
1.645     raeburn  4049:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4050:                 my $src;
1.645     raeburn  4051:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4052:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4053:                 } else {
1.1164    raeburn  4054:                     if ($attr->{'src'} ne '') {
                   4055:                         $src = $attr->{'src'};
                   4056:                         &add_filetype($allfiles,$src,'src');
                   4057:                     }
                   4058:                 }
                   4059:                 my $text = $p->get_trimmed_text();
                   4060:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4061:                     my @swfargs = split(/,/,$1);
                   4062:                     foreach my $item (@swfargs) {
                   4063:                         $item =~ s/["']//g;
                   4064:                         $item =~ s/^\s+//;
                   4065:                         $item =~ s/\s+$//;
                   4066:                     }
                   4067:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4068:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4069:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4070:                         } else {
                   4071:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4072:                         }
                   4073:                     }
1.645     raeburn  4074:                 }
                   4075:             }
                   4076:             if (lc($tagname) eq 'link') {
                   4077:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4078:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4079:                 }
                   4080:             }
1.640     albertel 4081: 	    if (lc($tagname) eq 'object' ||
                   4082: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4083: 		foreach my $item (keys(%javafiles)) {
                   4084: 		    $javafiles{$item} = '';
                   4085: 		}
1.1164    raeburn  4086:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4087:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4088:                 }
1.640     albertel 4089: 	    }
                   4090: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4091: 		my $name = lc($attr->{'name'});
                   4092: 		foreach my $item (keys(%javafiles)) {
                   4093: 		    if ($name eq $item) {
                   4094: 			$javafiles{$item} = $attr->{'value'};
                   4095: 			last;
                   4096: 		    }
                   4097: 		}
1.1164    raeburn  4098:                 my $pathfrom;
1.640     albertel 4099: 		foreach my $item (keys(%mediafiles)) {
                   4100: 		    if ($name eq $item) {
1.1164    raeburn  4101:                         $pathfrom = $attr->{'value'};
                   4102:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4103: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4104: 			last;
                   4105: 		    }
                   4106: 		}
1.1164    raeburn  4107:                 if ($name eq 'flashvars') {
                   4108:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4109:                 }
                   4110:                 if ($pathfrom ne '') {
                   4111:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4112:                                          $pathfrom);
                   4113:                 }
1.640     albertel 4114: 	    }
                   4115: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4116: 		foreach my $item (keys(%javafiles)) {
                   4117: 		    if ($attr->{$item}) {
                   4118: 			$javafiles{$item} = $attr->{$item};
                   4119: 			last;
                   4120: 		    }
                   4121: 		}
                   4122: 		foreach my $item (keys(%mediafiles)) {
                   4123: 		    if ($attr->{$item}) {
                   4124: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4125: 			last;
                   4126: 		    }
                   4127: 		}
1.1164    raeburn  4128:                 if (lc($tagname) eq 'embed') {
                   4129:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4130:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4131:                                              $attr->{'src'});
                   4132:                     }
                   4133:                 }
1.640     albertel 4134: 	    }
1.1243    raeburn  4135:             if (lc($tagname) eq 'iframe') {
                   4136:                 my $src = $attr->{'src'} ;
                   4137:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4138:                     &add_filetype($allfiles,$src,'src');
                   4139:                 } elsif ($src =~ m{^/}) {
                   4140:                     if ($env{'request.course.id'}) {
                   4141:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4142:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4143:                         my $url = &hreflocation('',$fullpath);
                   4144:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4145:                             my $relpath = $1;
                   4146:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4147:                                 &add_filetype($allfiles,$1,'src');
                   4148:                             }
                   4149:                         }
                   4150:                     }
                   4151:                 }
                   4152:             }
1.1164    raeburn  4153:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4154:                 pop(@state);
1.1164    raeburn  4155:             }
1.640     albertel 4156: 	} elsif ($t->[0] eq 'E') {
                   4157: 	    my ($tagname) = ($t->[1]);
                   4158: 	    if ($javafiles{'codebase'} ne '') {
                   4159: 		$javafiles{'codebase'} .= '/';
                   4160: 	    }  
                   4161: 	    if (lc($tagname) eq 'applet' ||
                   4162: 		lc($tagname) eq 'object' ||
                   4163: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4164: 		) {
                   4165: 		foreach my $item (keys(%javafiles)) {
                   4166: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4167: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4168: 			&add_filetype($allfiles,$file,$item);
                   4169: 		    }
                   4170: 		}
                   4171: 	    } 
                   4172: 	    pop @state;
                   4173: 	}
                   4174:     }
1.1164    raeburn  4175:     foreach my $id (sort(keys(%flashvars))) {
                   4176:         if ($shockwave{$id} ne '') {
                   4177:             my @pairs = split(/\&/,$flashvars{$id});
                   4178:             foreach my $pair (@pairs) {
                   4179:                 my ($key,$value) = split(/\=/,$pair);
                   4180:                 if ($key eq 'thumb') {
                   4181:                     &add_filetype($allfiles,$value,$key);
                   4182:                 } elsif ($key eq 'content') {
                   4183:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4184:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4185:                     if ($ext ne '') {
                   4186:                         &add_filetype($allfiles,$path.$value,$ext);
                   4187:                     }
                   4188:                 }
                   4189:             }
                   4190:         }
                   4191:     }
1.637     raeburn  4192:     return 'ok';
                   4193: }
                   4194: 
1.639     albertel 4195: sub add_filetype {
                   4196:     my ($allfiles,$file,$type)=@_;
                   4197:     if (exists($allfiles->{$file})) {
                   4198: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4199: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4200: 	}
                   4201:     } else {
                   4202: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4203:     }
                   4204: }
                   4205: 
1.1164    raeburn  4206: sub embedded_dependency {
                   4207:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4208:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4209:         if (($identifier ne '') &&
                   4210:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4211:             ($pathfrom ne '')) {
                   4212:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4213:             foreach my $dep (@{$related->{$identifier}}) {
                   4214:                 &add_filetype($allfiles,$path.$dep,'object');
                   4215:             }
                   4216:         }
                   4217:     }
                   4218:     return;
                   4219: }
                   4220: 
1.493     albertel 4221: sub removeuploadedurl {
1.984     neumanie 4222:     my ($url)=@_;	
                   4223:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4224:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4225: }
                   4226: 
                   4227: sub removeuserfile {
                   4228:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4229:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4230:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4231:     if ($result eq 'ok') {	
1.798     raeburn  4232:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4233:             my $metafile = $fname.'.meta';
                   4234:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4235: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4236:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4237:             my $sqlresult = 
1.823     albertel 4238:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4239:                                         'portfolio_metadata',$group,
                   4240:                                         'delete');
1.798     raeburn  4241:         }
                   4242:     }
                   4243:     return $result;
1.257     www      4244: }
1.15      www      4245: 
1.530     albertel 4246: sub mkdiruserfile {
                   4247:     my ($docuname,$docudom,$dir)=@_;
                   4248:     my $home=&homeserver($docuname,$docudom);
                   4249:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4250: }
                   4251: 
1.531     albertel 4252: sub renameuserfile {
                   4253:     my ($docuname,$docudom,$old,$new)=@_;
                   4254:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4255:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4256:                         &escape("$old").':'.&escape("$new"),$home);
                   4257:     if ($result eq 'ok') {
                   4258:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4259:             my $oldmeta = $old.'.meta';
                   4260:             my $newmeta = $new.'.meta';
                   4261:             my $metaresult = 
                   4262:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4263: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4264:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4265:             my $sqlresult = 
1.823     albertel 4266:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4267:                                         'portfolio_metadata',$group,
                   4268:                                         'delete');
1.798     raeburn  4269:         }
                   4270:     }
                   4271:     return $result;
1.531     albertel 4272: }
                   4273: 
1.14      www      4274: # ------------------------------------------------------------------------- Log
                   4275: 
                   4276: sub log {
                   4277:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4278:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4279: }
                   4280: 
                   4281: # ------------------------------------------------------------------ Course Log
1.352     www      4282: #
                   4283: # This routine flushes several buffers of non-mission-critical nature
                   4284: #
1.157     www      4285: 
                   4286: sub flushcourselogs {
1.352     www      4287:     &logthis('Flushing log buffers');
                   4288: #
                   4289: # course logs
                   4290: # This is a log of all transactions in a course, which can be used
                   4291: # for data mining purposes
                   4292: #
                   4293: # It also collects the courseid database, which lists last transaction
                   4294: # times and course titles for all courseids
                   4295: #
                   4296:     my %courseidbuffer=();
1.921     raeburn  4297:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4298:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4299: 		          &escape($courselogs{$crsid}),
                   4300: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4301: 	    delete $courselogs{$crsid};
                   4302:         } else {
                   4303:             &logthis('Failed to flush log buffer for '.$crsid);
                   4304:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4305:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4306:                         " exceeded maximum size, deleting.</font>");
                   4307:                delete $courselogs{$crsid};
                   4308:             }
1.352     www      4309:         }
1.920     raeburn  4310:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4311:             'description' => $coursedescrbuf{$crsid},
                   4312:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4313:             'type'        => $coursetypebuf{$crsid},
                   4314:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4315:         };
1.191     harris41 4316:     }
1.352     www      4317: #
                   4318: # Write course id database (reverse lookup) to homeserver of courses 
                   4319: # Is used in pickcourse
                   4320: #
1.840     albertel 4321:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4322:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4323:                                     $courseidbuffer{$crs_home},
                   4324:                                     $crs_home,'timeonly');
1.352     www      4325:     }
                   4326: #
                   4327: # File accesses
                   4328: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4329: #
1.449     matthew  4330:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4331:         if ($entry =~ /___count$/) {
                   4332:             my ($dom,$name);
1.807     albertel 4333:             ($dom,$name,undef)=
1.811     albertel 4334: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4335:             if (! defined($dom) || $dom eq '' || 
                   4336:                 ! defined($name) || $name eq '') {
1.620     albertel 4337:                 my $cid = $env{'request.course.id'};
                   4338:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4339:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4340:             }
1.450     matthew  4341:             my $value = $accesshash{$entry};
                   4342:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4343:             my %temphash=($url => $value);
1.449     matthew  4344:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4345:             if ($result eq 'ok') {
                   4346:                 delete $accesshash{$entry};
                   4347:             }
                   4348:         } else {
1.811     albertel 4349:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4350:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4351:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4352:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4353:                 delete $accesshash{$entry};
                   4354:             }
1.185     www      4355:         }
1.191     harris41 4356:     }
1.352     www      4357: #
                   4358: # Roles
                   4359: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4360: #
1.800     albertel 4361:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4362:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4363: 	    split(/\:/,$entry);
                   4364:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4365:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4366:                 $rudom,$runame) eq 'ok') {
                   4367: 	    delete $userrolehash{$entry};
                   4368:         }
                   4369:     }
1.662     raeburn  4370: #
1.1334    raeburn  4371: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4372: #
                   4373:     my %domrolebuffer = ();
1.1000    raeburn  4374:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4375:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4376:         if ($domrolebuffer{$rudom}) {
                   4377:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4378:                       '='.&escape($domainrolehash{$entry});
                   4379:         } else {
                   4380:             $domrolebuffer{$rudom}.=&escape($entry).
                   4381:                       '='.&escape($domainrolehash{$entry});
                   4382:         }
                   4383:         delete $domainrolehash{$entry};
                   4384:     }
                   4385:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4386: 	my %servers;
                   4387: 	if (defined(&domain($dom,'primary'))) {
                   4388: 	    my $primary=&domain($dom,'primary');
                   4389: 	    my $hostname=&hostname($primary);
                   4390: 	    $servers{$primary} = $hostname;
                   4391: 	} else { 
                   4392: 	    %servers = &get_servers($dom,'library');
                   4393: 	}
1.841     albertel 4394: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4395: 	    if (&reply('domroleput:'.$dom.':'.
                   4396: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4397: 		last;
                   4398: 	    } else {  
1.841     albertel 4399: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4400: 	    }
1.662     raeburn  4401:         }
                   4402:     }
1.186     www      4403:     $dumpcount++;
1.157     www      4404: }
                   4405: 
                   4406: sub courselog {
                   4407:     my $what=shift;
1.158     www      4408:     $what=time.':'.$what;
1.620     albertel 4409:     unless ($env{'request.course.id'}) { return ''; }
                   4410:     $coursedombuf{$env{'request.course.id'}}=
                   4411:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4412:     $coursenumbuf{$env{'request.course.id'}}=
                   4413:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4414:     $coursehombuf{$env{'request.course.id'}}=
                   4415:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4416:     $coursedescrbuf{$env{'request.course.id'}}=
                   4417:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4418:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4419:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4420:     $courseownerbuf{$env{'request.course.id'}}=
                   4421:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4422:     $coursetypebuf{$env{'request.course.id'}}=
                   4423:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4424:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4425: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4426:     } else {
1.620     albertel 4427: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4428:     }
1.620     albertel 4429:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4430: 	&flushcourselogs();
                   4431:     }
1.158     www      4432: }
                   4433: 
                   4434: sub courseacclog {
                   4435:     my $fnsymb=shift;
1.620     albertel 4436:     unless ($env{'request.course.id'}) { return ''; }
                   4437:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4438:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4439:         $what.=':POST';
1.583     matthew  4440:         # FIXME: Probably ought to escape things....
1.800     albertel 4441: 	foreach my $key (keys(%env)) {
                   4442:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4443:                 my $formitem = $1;
                   4444:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4445:                     $what.=':'.$formitem.'='.$env{$key};
                   4446:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4447:                     $what.=':'.$formitem.'='.$env{$key};
                   4448:                 }
1.158     www      4449:             }
1.191     harris41 4450:         }
1.583     matthew  4451:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4452:         # FIXME: We should not be depending on a form parameter that someone
                   4453:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4454:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4455:             $what.= ':POST';
                   4456:             # FIXME: Probably ought to escape things....
                   4457:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4458:                                  'crsdiscuss') {
1.620     albertel 4459:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4460:             }
                   4461:         }
1.158     www      4462:     }
                   4463:     &courselog($what);
1.149     www      4464: }
                   4465: 
1.185     www      4466: sub countacc {
                   4467:     my $url=&declutter(shift);
1.458     matthew  4468:     return if (! defined($url) || $url eq '');
1.620     albertel 4469:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4470: #
                   4471: # Mark that this url was used in this course
                   4472: #
1.620     albertel 4473:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4474: #
                   4475: # Increase the access count for this resource in this child process
                   4476: #
1.281     www      4477:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4478:     $accesshash{$key}++;
1.185     www      4479: }
1.349     www      4480: 
1.361     www      4481: sub linklog {
                   4482:     my ($from,$to)=@_;
                   4483:     $from=&declutter($from);
                   4484:     $to=&declutter($to);
                   4485:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4486:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4487: }
1.1160    www      4488: 
                   4489: sub statslog {
                   4490:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4491:     if ($users<2) { return; }
                   4492:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4493:             'course'       => $env{'request.course.id'},
                   4494:             'sections'     => '"all"',
                   4495:             'num_students' => $users,
                   4496:             'part'         => $part,
                   4497:             'symb'         => $symb,
                   4498:             'mean_tries'   => $av_attempts,
                   4499:             'deg_of_diff'  => $degdiff});
                   4500:     foreach my $key (keys(%dynstore)) {
                   4501:         $accesshash{$key}=$dynstore{$key};
                   4502:     }
                   4503: }
1.361     www      4504:   
1.349     www      4505: sub userrolelog {
                   4506:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4507:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4508:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4509:        $userrolehash
                   4510:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4511:                     =$tend.':'.$tstart;
1.662     raeburn  4512:     }
1.1169    droeschl 4513:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4514:        $userrolehash
                   4515:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4516:                     =$tend.':'.$tstart;
                   4517:     }
1.1334    raeburn  4518:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4519:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4520:        $domainrolehash
                   4521:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4522:                     = $tend.':'.$tstart;
                   4523:     }
1.351     www      4524: }
                   4525: 
1.957     raeburn  4526: sub courserolelog {
                   4527:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4528:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4529:         my $cdom = $1;
                   4530:         my $cnum = $2;
                   4531:         my $sec = $3;
                   4532:         my $namespace = 'rolelog';
                   4533:         my %storehash = (
                   4534:                            role    => $trole,
                   4535:                            start   => $tstart,
                   4536:                            end     => $tend,
                   4537:                            selfenroll => $selfenroll,
                   4538:                            context    => $context,
                   4539:                         );
                   4540:         if ($trole eq 'gr') {
                   4541:             $namespace = 'groupslog';
                   4542:             $storehash{'group'} = $sec;
                   4543:         } else {
                   4544:             $storehash{'section'} = $sec;
                   4545:         }
1.1188    raeburn  4546:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4547:                    $domain,$cnum,$cdom);
1.1184    raeburn  4548:         if (($trole ne 'st') || ($sec ne '')) {
                   4549:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4550:         }
                   4551:     }
                   4552:     return;
                   4553: }
                   4554: 
1.1184    raeburn  4555: sub domainrolelog {
                   4556:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4557:     if ($area =~ m{^/($match_domain)/$}) {
                   4558:         my $cdom = $1;
                   4559:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4560:         my $namespace = 'rolelog';
                   4561:         my %storehash = (
                   4562:                            role    => $trole,
                   4563:                            start   => $tstart,
                   4564:                            end     => $tend,
                   4565:                            context => $context,
                   4566:                         );
1.1188    raeburn  4567:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4568:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4569:     }
                   4570:     return;
                   4571: 
                   4572: }
                   4573: 
                   4574: sub coauthorrolelog {
                   4575:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4576:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4577:         my $audom = $1;
                   4578:         my $auname = $2;
                   4579:         my $namespace = 'rolelog';
                   4580:         my %storehash = (
                   4581:                            role    => $trole,
                   4582:                            start   => $tstart,
                   4583:                            end     => $tend,
                   4584:                            context => $context,
                   4585:                         );
1.1188    raeburn  4586:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4587:                    $domain,$auname,$audom);
1.1184    raeburn  4588:     }
                   4589:     return;
                   4590: }
                   4591: 
1.351     www      4592: sub get_course_adv_roles {
1.948     raeburn  4593:     my ($cid,$codes) = @_;
1.620     albertel 4594:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4595:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4596:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4597:     my %nothide=();
1.800     albertel 4598:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4599:         if ($user !~ /:/) {
                   4600: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4601:         } else {
                   4602:             $nothide{$user}=1;
                   4603:         }
1.470     www      4604:     }
1.1219    raeburn  4605:     my @possdoms = ($coursehash{'domain'});
                   4606:     if ($coursehash{'checkforpriv'}) {
                   4607:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4608:     }
1.351     www      4609:     my %returnhash=();
                   4610:     my %dumphash=
                   4611:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4612:     my $now=time;
1.997     raeburn  4613:     my %privileged;
1.1000    raeburn  4614:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4615: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4616:         if (($tstart) && ($tstart<0)) { next; }
                   4617:         if (($tend) && ($tend<$now)) { next; }
                   4618:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4619:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4620: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4621:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4622:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4623: 	if ($role eq 'cr') { next; }
1.948     raeburn  4624:         if ($codes) {
                   4625:             if ($section) { $role .= ':'.$section; }
                   4626:             if ($returnhash{$role}) {
                   4627:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4628:             } else {
                   4629:                 $returnhash{$role}=$username.':'.$domain;
                   4630:             }
1.351     www      4631:         } else {
1.988     raeburn  4632:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4633:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4634:             if ($returnhash{$key}) {
                   4635: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4636:             } else {
                   4637:                 $returnhash{$key}=$username.':'.$domain;
                   4638:             }
1.351     www      4639:         }
1.948     raeburn  4640:     }
1.400     www      4641:     return %returnhash;
                   4642: }
                   4643: 
                   4644: sub get_my_roles {
1.937     raeburn  4645:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4646:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4647:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4648:     my (%dumphash,%nothide);
1.1086    raeburn  4649:     if ($context eq 'userroles') {
1.1166    raeburn  4650:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4651:     } else {
1.1219    raeburn  4652:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4653:         if ($hidepriv) {
                   4654:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4655:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4656:                 if ($user !~ /:/) {
                   4657:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4658:                 } else {
                   4659:                     $nothide{$user} = 1;
                   4660:                 }
                   4661:             }
                   4662:         }
1.858     raeburn  4663:     }
1.400     www      4664:     my %returnhash=();
                   4665:     my $now=time;
1.999     raeburn  4666:     my %privileged;
1.800     albertel 4667:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4668:         my ($role,$tend,$tstart);
                   4669:         if ($context eq 'userroles') {
1.1149    raeburn  4670:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4671: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4672:         } else {
                   4673:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4674:         }
1.400     www      4675:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4676:         my $status = 'active';
1.939     raeburn  4677:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4678:             $status = 'previous';
                   4679:         } 
                   4680:         if (($tstart) && ($now<$tstart)) {
                   4681:             $status = 'future';
                   4682:         }
                   4683:         if (ref($types) eq 'ARRAY') {
                   4684:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4685:                 next;
                   4686:             } 
                   4687:         } else {
                   4688:             if ($status ne 'active') {
                   4689:                 next;
                   4690:             }
                   4691:         }
1.867     raeburn  4692:         my ($rolecode,$username,$domain,$section,$area);
                   4693:         if ($context eq 'userroles') {
1.1186    raeburn  4694:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4695:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4696:         } else {
                   4697:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4698:         }
1.832     raeburn  4699:         if (ref($roledoms) eq 'ARRAY') {
                   4700:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4701:                 next;
                   4702:             }
                   4703:         }
                   4704:         if (ref($roles) eq 'ARRAY') {
                   4705:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4706:                 if ($role =~ /^cr\//) {
                   4707:                     if (!grep(/^cr$/,@{$roles})) {
                   4708:                         next;
                   4709:                     }
1.1104    raeburn  4710:                 } elsif ($role =~ /^gr\//) {
                   4711:                     if (!grep(/^gr$/,@{$roles})) {
                   4712:                         next;
                   4713:                     }
1.922     raeburn  4714:                 } else {
                   4715:                     next;
                   4716:                 }
1.832     raeburn  4717:             }
1.867     raeburn  4718:         }
1.937     raeburn  4719:         if ($hidepriv) {
1.1219    raeburn  4720:             my @privroles = ('dc','su');
1.999     raeburn  4721:             if ($context eq 'userroles') {
1.1219    raeburn  4722:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4723:             } else {
1.1219    raeburn  4724:                 my $possdoms = [$domain];
                   4725:                 if (ref($roledoms) eq 'ARRAY') {
                   4726:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4727:                 }
1.1219    raeburn  4728:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4729:                     if (!$nothide{$username.':'.$domain}) {
                   4730:                         next;
                   4731:                     }
                   4732:                 }
1.937     raeburn  4733:             }
                   4734:         }
1.933     raeburn  4735:         if ($withsec) {
                   4736:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4737:                 $tstart.':'.$tend;
                   4738:         } else {
                   4739:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4740:         }
1.832     raeburn  4741:     }
1.373     www      4742:     return %returnhash;
1.399     www      4743: }
                   4744: 
1.1333    raeburn  4745: sub get_all_adhocroles {
                   4746:     my ($dom) = @_;
                   4747:     my @roles_by_num = ();
                   4748:     my %domdefaults = &get_domain_defaults($dom);
                   4749:     my (%description,%access_in_dom,%access_info);
                   4750:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4751:         my $count = 0;
                   4752:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4753:         my %ordered;
                   4754:         foreach my $role (sort(keys(%domcurrent))) {
                   4755:             my ($order,$desc,$access_in_dom);
                   4756:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4757:                 $order = $domcurrent{$role}{'order'};
                   4758:                 $desc = $domcurrent{$role}{'desc'};
                   4759:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4760:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4761:             }
                   4762:             if ($order eq '') {
                   4763:                 $order = $count;
                   4764:             }
                   4765:             $ordered{$order} = $role;
                   4766:             if ($desc ne '') {
                   4767:                 $description{$role} = $desc;
                   4768:             } else {
                   4769:                 $description{$role}= $role;
                   4770:             }
                   4771:             $count++;
                   4772:         }
                   4773:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4774:             push(@roles_by_num,$ordered{$item});
                   4775:         }
                   4776:     }
                   4777:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4778: }
                   4779: 
1.1332    raeburn  4780: sub get_my_adhocroles {
1.1333    raeburn  4781:     my ($cid,$checkreg) = @_;
                   4782:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4783:     if ($env{'request.course.id'} eq $cid) {
                   4784:         $cdom = $env{'course.'.$cid.'.domain'};
                   4785:         $cnum = $env{'course.'.$cid.'.num'};
                   4786:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4787:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4788:         $cdom = $1;
                   4789:         $cnum = $2;
                   4790:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4791:                                      $cdom,$cnum);
                   4792:     }
                   4793:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4794:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4795:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4796:         if ($rosterhash{$user} ne '') {
                   4797:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4798:             return ([],{}) if ($type eq 'auto');
                   4799:         }
                   4800:     }
                   4801:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4802:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4803:             my $then=$env{'user.login.time'};
                   4804:             my $update=$env{'user.update.time'};
1.1335    raeburn  4805:             if (!$update) {
                   4806:                 $update = $then;
                   4807:             }
                   4808:             my @liveroles;
1.1334    raeburn  4809:             foreach my $role ('dh','da') {
                   4810:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4811:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4812:                     my $limit = $update;
                   4813:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4814:                         $limit = $then;
                   4815:                     }
1.1335    raeburn  4816:                     my $activerole = 1;
                   4817:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4818:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4819:                     if ($activerole) {
                   4820:                         push(@liveroles,$role);
                   4821:                     }
1.1334    raeburn  4822:                 }
1.1332    raeburn  4823:             }
1.1335    raeburn  4824:             if (@liveroles) {
1.1332    raeburn  4825:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4826:                     my ($accessref,$accessinfo,%access_in_dom);
                   4827:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4828:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4829:                         if (@{$roles_by_num}) {
1.1332    raeburn  4830:                             my %settings;
                   4831:                             if ($env{'request.course.id'} eq $cid) {
                   4832:                                 foreach my $envkey (keys(%env)) {
                   4833:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4834:                                         $settings{$1} = $env{$envkey};
                   4835:                                     }
                   4836:                                 }
                   4837:                             } else {
                   4838:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4839:                             }
                   4840:                             my %setincrs;
                   4841:                             if ($settings{'internal.adhocaccess'}) {
                   4842:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4843:                             }
                   4844:                             my @statuses;
                   4845:                             if ($env{'environment.inststatus'}) {
                   4846:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4847:                             }
                   4848:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4849:                             if (ref($accessref) eq 'HASH') {
                   4850:                                 %access_in_dom = %{$accessref};
                   4851:                             }
                   4852:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4853:                                 my ($curraccess,@okstatus,@personnel);
                   4854:                                 if ($setincrs{$role}) {
                   4855:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4856:                                     if ($curraccess eq 'status') {
                   4857:                                         @okstatus = split(/\&/,$rest);
                   4858:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4859:                                         @personnel = split(/\&/,$rest);
                   4860:                                     }
                   4861:                                 } else {
                   4862:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4863:                                     if (ref($accessinfo) eq 'HASH') {
                   4864:                                         if ($curraccess eq 'status') {
                   4865:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4866:                                                 @okstatus = @{$accessinfo->{$role}};
                   4867:                                             }
                   4868:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4869:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4870:                                                 @personnel = @{$accessinfo->{$role}};
                   4871:                                             }
1.1332    raeburn  4872:                                         }
                   4873:                                     }
                   4874:                                 }
                   4875:                                 if ($curraccess eq 'none') {
                   4876:                                     next;
                   4877:                                 } elsif ($curraccess eq 'all') {
                   4878:                                     push(@possroles,$role);
1.1336    raeburn  4879:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4880:                                     if (grep(/^dh$/,@liveroles)) {
                   4881:                                         push(@possroles,$role);
                   4882:                                     } else {
                   4883:                                         next;
                   4884:                                     }
1.1336    raeburn  4885:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4886:                                     if (grep(/^da$/,@liveroles)) {
                   4887:                                         push(@possroles,$role);
                   4888:                                     } else {
                   4889:                                         next;
                   4890:                                     }
1.1332    raeburn  4891:                                 } elsif ($curraccess eq 'status') {
                   4892:                                     if (@okstatus) {
                   4893:                                         if (!@statuses) {
                   4894:                                             if (grep(/^default$/,@okstatus)) {
                   4895:                                                 push(@possroles,$role);
                   4896:                                             }
                   4897:                                         } else {
                   4898:                                             foreach my $status (@okstatus) {
                   4899:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4900:                                                     push(@possroles,$role);
                   4901:                                                     last;
                   4902:                                                 }
                   4903:                                             }
                   4904:                                         }
                   4905:                                     }
                   4906:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4907:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4908:                                         if ($curraccess eq 'exc') {
                   4909:                                             push(@possroles,$role);
                   4910:                                         }
                   4911:                                     } elsif ($curraccess eq 'inc') {
                   4912:                                         push(@possroles,$role);
                   4913:                                     }
                   4914:                                 }
                   4915:                             }
                   4916:                         }
                   4917:                     }
                   4918:                 }
                   4919:             }
                   4920:         }
                   4921:     }
1.1333    raeburn  4922:     unless (ref($description) eq 'HASH') {
                   4923:         if (ref($roles_by_num) eq 'ARRAY') {
                   4924:             my %desc;
                   4925:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4926:             $description = \%desc;
                   4927:         } else {
                   4928:             $description = {};
                   4929:         }
                   4930:     }
                   4931:     return (\@possroles,$description);
1.1332    raeburn  4932: }
                   4933: 
1.399     www      4934: # ----------------------------------------------------- Frontpage Announcements
                   4935: #
                   4936: #
                   4937: 
                   4938: sub postannounce {
                   4939:     my ($server,$text)=@_;
1.844     albertel 4940:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4941:     unless ($text=~/\w/) { $text=''; }
                   4942:     return &reply('setannounce:'.&escape($text),$server);
                   4943: }
                   4944: 
                   4945: sub getannounce {
1.448     albertel 4946: 
1.1359    raeburn  4947:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4948: 	my $announcement='';
1.800     albertel 4949: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4950: 	close($fh);
1.399     www      4951: 	if ($announcement=~/\w/) { 
                   4952: 	    return 
                   4953:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4954:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4955: 	} else {
                   4956: 	    return '';
                   4957: 	}
                   4958:     } else {
                   4959: 	return '';
                   4960:     }
1.351     www      4961: }
1.353     www      4962: 
                   4963: # ---------------------------------------------------------- Course ID routines
                   4964: # Deal with domain's nohist_courseid.db files
                   4965: #
                   4966: 
                   4967: sub courseidput {
1.921     raeburn  4968:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4969:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4970:     my $outcome;
                   4971:     if ($caller eq 'timeonly') {
                   4972:         my $cids = '';
                   4973:         foreach my $item (keys(%$storehash)) {
                   4974:             $cids.=&escape($item).'&';
                   4975:         }
                   4976:         $cids=~s/\&$//;
                   4977:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4978:                           $coursehome);       
                   4979:     } else {
                   4980:         my $items = '';
                   4981:         foreach my $item (keys(%$storehash)) {
                   4982:             $items.= &escape($item).'='.
                   4983:                      &freeze_escape($$storehash{$item}).'&';
                   4984:         }
                   4985:         $items=~s/\&$//;
                   4986:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4987:                           $coursehome);
1.918     raeburn  4988:     }
                   4989:     if ($outcome eq 'unknown_cmd') {
                   4990:         my $what;
                   4991:         foreach my $cid (keys(%$storehash)) {
                   4992:             $what .= &escape($cid).'=';
1.921     raeburn  4993:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4994:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4995:             }
                   4996:             $what =~ s/\:$/&/;
                   4997:         }
                   4998:         $what =~ s/\&$//;  
                   4999:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5000:     } else {
                   5001:         return $outcome;
                   5002:     }
1.353     www      5003: }
                   5004: 
                   5005: sub courseiddump {
1.921     raeburn  5006:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5007:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5008:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5009:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5010:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5011:     my $as_hash = 1;
                   5012:     my %returnhash;
                   5013:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5014:     my %libserv = &all_library();
                   5015:     foreach my $tryserver (keys(%libserv)) {
                   5016:         if ( (  $hostidflag == 1 
                   5017: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5018: 	     || (!defined($hostidflag)) ) {
                   5019: 
1.918     raeburn  5020: 	    if (($domfilter eq '') ||
                   5021: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5022:                 my $rep;
                   5023:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5024:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5025:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5026:                                 &escape($descfilter), &escape($instcodefilter), 
                   5027:                                 &escape($ownerfilter), &escape($coursefilter),
                   5028:                                 &escape($typefilter), &escape($regexp_ok), 
                   5029:                                 $as_hash, &escape($selfenrollonly), 
                   5030:                                 &escape($catfilter), $showhidden, $caller, 
                   5031:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5032:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5033:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5034:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5035:                 } else {
                   5036:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5037:                              $sincefilter.':'.&escape($descfilter).':'.
                   5038:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5039:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5040:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5041:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5042:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5043:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5044:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5045:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5046:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5047:                 }
                   5048:                      
1.918     raeburn  5049:                 my @pairs=split(/\&/,$rep);
                   5050:                 foreach my $item (@pairs) {
                   5051:                     my ($key,$value)=split(/\=/,$item,2);
                   5052:                     $key = &unescape($key);
                   5053:                     next if ($key =~ /^error: 2 /);
                   5054:                     my $result = &thaw_unescape($value);
                   5055:                     if (ref($result) eq 'HASH') {
                   5056:                         $returnhash{$key}=$result;
                   5057:                     } else {
1.921     raeburn  5058:                         my @responses = split(/:/,$value);
                   5059:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5060:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5061:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5062:                         }
1.1008    raeburn  5063:                     }
1.353     www      5064:                 }
                   5065:             }
                   5066:         }
                   5067:     }
                   5068:     return %returnhash;
                   5069: }
                   5070: 
1.1055    raeburn  5071: sub courselastaccess {
                   5072:     my ($cdom,$cnum,$hostidref) = @_;
                   5073:     my %returnhash;
                   5074:     if ($cdom && $cnum) {
                   5075:         my $chome = &homeserver($cnum,$cdom);
                   5076:         if ($chome ne 'no_host') {
                   5077:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5078:             &extract_lastaccess(\%returnhash,$rep);
                   5079:         }
                   5080:     } else {
                   5081:         if (!$cdom) { $cdom=''; }
                   5082:         my %libserv = &all_library();
                   5083:         foreach my $tryserver (keys(%libserv)) {
                   5084:             if (ref($hostidref) eq 'ARRAY') {
                   5085:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5086:             } 
                   5087:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5088:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5089:                 &extract_lastaccess(\%returnhash,$rep);
                   5090:             }
                   5091:         }
                   5092:     }
                   5093:     return %returnhash;
                   5094: }
                   5095: 
                   5096: sub extract_lastaccess {
                   5097:     my ($returnhash,$rep) = @_;
                   5098:     if (ref($returnhash) eq 'HASH') {
                   5099:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5100:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5101:                  $rep eq '') {
                   5102:             my @pairs=split(/\&/,$rep);
                   5103:             foreach my $item (@pairs) {
                   5104:                 my ($key,$value)=split(/\=/,$item,2);
                   5105:                 $key = &unescape($key);
                   5106:                 next if ($key =~ /^error: 2 /);
                   5107:                 $returnhash->{$key} = &thaw_unescape($value);
                   5108:             }
                   5109:         }
                   5110:     }
                   5111:     return;
                   5112: }
                   5113: 
1.658     raeburn  5114: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5115: 
                   5116: sub dcmailput {
1.685     raeburn  5117:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5118:     my $status = &Apache::lonnet::critical(
1.740     www      5119:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5120:        &escape($message),$server);
1.662     raeburn  5121:     return $status;
                   5122: }
                   5123: 
1.658     raeburn  5124: sub dcmaildump {
                   5125:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5126:     my %returnhash=();
1.846     albertel 5127: 
                   5128:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5129:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5130:                                                          &escape($enddate).':';
                   5131: 	my @esc_senders=map { &escape($_)} @$senders;
                   5132: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5133: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5134:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5135:             if (($key) && ($value)) {
                   5136:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5137:             }
                   5138:         }
                   5139:     }
                   5140:     return %returnhash;
                   5141: }
1.662     raeburn  5142: # ---------------------------------------------------------- Domain roles
                   5143: 
                   5144: sub get_domain_roles {
                   5145:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5146:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5147:         $startdate = '.';
                   5148:     }
1.1018    raeburn  5149:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5150:         $enddate = '.';
                   5151:     }
1.922     raeburn  5152:     my $rolelist;
                   5153:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5154:         $rolelist = join('&',@{$roles});
1.922     raeburn  5155:     }
1.662     raeburn  5156:     my %personnel = ();
1.841     albertel 5157: 
                   5158:     my %servers = &get_servers($dom,'library');
                   5159:     foreach my $tryserver (keys(%servers)) {
                   5160: 	%{$personnel{$tryserver}}=();
                   5161: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5162: 					    &escape($startdate).':'.
                   5163: 					    &escape($enddate).':'.
                   5164: 					    &escape($rolelist), $tryserver))) {
                   5165: 	    my ($key,$value) = split(/\=/,$line,2);
                   5166: 	    if (($key) && ($value)) {
                   5167: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5168: 	    }
                   5169: 	}
1.662     raeburn  5170:     }
                   5171:     return %personnel;
                   5172: }
1.658     raeburn  5173: 
1.1332    raeburn  5174: sub get_active_domroles {
                   5175:     my ($dom,$roles) = @_;
                   5176:     return () unless (ref($roles) eq 'ARRAY');
                   5177:     my $now = time;
                   5178:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5179:     my %domroles;
                   5180:     foreach my $server (keys(%dompersonnel)) {
                   5181:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5182:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5183:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5184:         }
                   5185:     }
                   5186:     return %domroles;
                   5187: }
                   5188: 
1.1057    www      5189: # ----------------------------------------------------------- Interval timing 
1.149     www      5190: 
1.1153    www      5191: {
                   5192: # Caches needed for speedup of navmaps
                   5193: # We don't want to cache this for very long at all (5 seconds at most)
                   5194: # 
                   5195: # The user for whom we cache
                   5196: my $cachedkey='';
                   5197: # The cached times for this user
                   5198: my %cachedtimes=();
                   5199: # When this was last done
1.1282    raeburn  5200: my $cachedtime='';
1.1153    www      5201: 
                   5202: sub load_all_first_access {
1.1308    raeburn  5203:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5204:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5205:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5206:         (!$ignorecache)) {
1.1154    raeburn  5207:         return;
                   5208:     }
                   5209:     $cachedtime=time;
                   5210:     $cachedkey=$uname.':'.$udom;
                   5211:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5212: }
                   5213: 
1.504     albertel 5214: sub get_first_access {
1.1308    raeburn  5215:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5216:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5217:     if ($argsymb) { $symb=$argsymb; }
                   5218:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5219:     if ($argmap) { $map = $argmap; }
1.926     albertel 5220:     if ($type eq 'course') {
                   5221: 	$res='course';
                   5222:     } elsif ($type eq 'map') {
1.588     albertel 5223: 	$res=&symbread($map);
                   5224:     } else {
                   5225: 	$res=$symb;
                   5226:     }
1.1308    raeburn  5227:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5228:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5229: }
                   5230: 
                   5231: sub set_first_access {
1.1162    raeburn  5232:     my ($type,$interval)=@_;
1.790     albertel 5233:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5234:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5235:     if ($type eq 'course') {
                   5236: 	$res='course';
                   5237:     } elsif ($type eq 'map') {
1.588     albertel 5238: 	$res=&symbread($map);
                   5239:     } else {
                   5240: 	$res=$symb;
                   5241:     }
1.1153    www      5242:     $cachedkey='';
1.1162    raeburn  5243:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 5244:     if (!$firstaccess) {
1.1162    raeburn  5245:         my $start = time;
                   5246: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5247:                           $udom,$uname);
                   5248:         if ($putres eq 'ok') {
                   5249:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5250:                  $udom,$uname); 
                   5251:             &appenv(
                   5252:                      {
                   5253:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5254:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5255:                      }
                   5256:                   );
1.1365    raeburn  5257:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5258:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5259:             }
1.1162    raeburn  5260:         }
                   5261:         return $putres;
1.505     albertel 5262:     }
                   5263:     return 'already_set';
1.504     albertel 5264: }
1.1153    www      5265: }
1.1282    raeburn  5266: 
1.110     www      5267: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5268: 
                   5269: sub expirespread {
                   5270:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5271:     my $cid=$env{'request.course.id'}; 
1.110     www      5272:     if ($cid) {
                   5273:        my $now=time;
                   5274:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5275:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5276:                             $env{'course.'.$cid.'.num'}.
1.110     www      5277: 	        	    ':nohist_expirationdates:'.
                   5278:                             &escape($key).'='.$now,
1.620     albertel 5279:                             $env{'course.'.$cid.'.home'})
1.110     www      5280:     }
                   5281:     return 'ok';
1.14      www      5282: }
                   5283: 
1.109     www      5284: # ----------------------------------------------------- Devalidate Spreadsheets
                   5285: 
                   5286: sub devalidate {
1.325     www      5287:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5288:     my $cid=$env{'request.course.id'}; 
1.109     www      5289:     if ($cid) {
1.391     matthew  5290:         # delete the stored spreadsheets for
                   5291:         # - the student level sheet of this user in course's homespace
                   5292:         # - the assessment level sheet for this resource 
                   5293:         #   for this user in user's homespace
1.553     albertel 5294: 	# - current conditional state info
1.325     www      5295: 	my $key=$uname.':'.$udom.':';
1.109     www      5296:         my $status=
1.299     matthew  5297: 	    &del('nohist_calculatedsheets',
1.391     matthew  5298: 		 [$key.'studentcalc:'],
1.620     albertel 5299: 		 $env{'course.'.$cid.'.domain'},
                   5300: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5301: 		.' '.
                   5302: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5303: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5304:         unless ($status eq 'ok ok') {
                   5305:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5306:                     $uname.' at '.$udom.' for '.
1.109     www      5307: 		    $symb.': '.$status);
1.133     albertel 5308:         }
1.553     albertel 5309: 	&delenv('user.state.'.$cid);
1.109     www      5310:     }
                   5311: }
                   5312: 
1.265     albertel 5313: sub get_scalar {
                   5314:     my ($string,$end) = @_;
                   5315:     my $value;
                   5316:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5317: 	$value = $1;
                   5318:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5319: 	$value = $1;
                   5320:     }
                   5321:     return &unescape($value);
                   5322: }
                   5323: 
                   5324: sub array2str {
                   5325:   my (@array) = @_;
                   5326:   my $result=&arrayref2str(\@array);
                   5327:   $result=~s/^__ARRAY_REF__//;
                   5328:   $result=~s/__END_ARRAY_REF__$//;
                   5329:   return $result;
                   5330: }
                   5331: 
1.204     albertel 5332: sub arrayref2str {
                   5333:   my ($arrayref) = @_;
1.265     albertel 5334:   my $result='__ARRAY_REF__';
1.204     albertel 5335:   foreach my $elem (@$arrayref) {
1.265     albertel 5336:     if(ref($elem) eq 'ARRAY') {
                   5337:       $result.=&arrayref2str($elem).'&';
                   5338:     } elsif(ref($elem) eq 'HASH') {
                   5339:       $result.=&hashref2str($elem).'&';
                   5340:     } elsif(ref($elem)) {
                   5341:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5342:     } else {
                   5343:       $result.=&escape($elem).'&';
                   5344:     }
                   5345:   }
                   5346:   $result=~s/\&$//;
1.265     albertel 5347:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5348:   return $result;
                   5349: }
                   5350: 
1.168     albertel 5351: sub hash2str {
1.204     albertel 5352:   my (%hash) = @_;
                   5353:   my $result=&hashref2str(\%hash);
1.265     albertel 5354:   $result=~s/^__HASH_REF__//;
                   5355:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5356:   return $result;
                   5357: }
                   5358: 
                   5359: sub hashref2str {
                   5360:   my ($hashref)=@_;
1.265     albertel 5361:   my $result='__HASH_REF__';
1.800     albertel 5362:   foreach my $key (sort(keys(%$hashref))) {
                   5363:     if (ref($key) eq 'ARRAY') {
                   5364:       $result.=&arrayref2str($key).'=';
                   5365:     } elsif (ref($key) eq 'HASH') {
                   5366:       $result.=&hashref2str($key).'=';
                   5367:     } elsif (ref($key)) {
1.265     albertel 5368:       $result.='=';
1.800     albertel 5369:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5370:     } else {
1.1132    raeburn  5371: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5372:     }
                   5373: 
1.800     albertel 5374:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5375:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5376:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5377:       $result.=&hashref2str($hashref->{$key}).'&';
                   5378:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5379:        $result.='&';
1.800     albertel 5380:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5381:     } else {
1.800     albertel 5382:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5383:     }
                   5384:   }
1.168     albertel 5385:   $result=~s/\&$//;
1.265     albertel 5386:   $result .= '__END_HASH_REF__';
1.168     albertel 5387:   return $result;
                   5388: }
                   5389: 
                   5390: sub str2hash {
1.265     albertel 5391:     my ($string)=@_;
                   5392:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5393:     return %$hash;
                   5394: }
                   5395: 
                   5396: sub str2hashref {
1.168     albertel 5397:   my ($string) = @_;
1.265     albertel 5398: 
                   5399:   my %hash;
                   5400: 
                   5401:   if($string !~ /^__HASH_REF__/) {
                   5402:       if (! ($string eq '' || !defined($string))) {
                   5403: 	  $hash{'error'}='Not hash reference';
                   5404:       }
                   5405:       return (\%hash, $string);
                   5406:   }
                   5407: 
                   5408:   $string =~ s/^__HASH_REF__//;
                   5409: 
                   5410:   while($string !~ /^__END_HASH_REF__/) {
                   5411:       #key
                   5412:       my $key='';
                   5413:       if($string =~ /^__HASH_REF__/) {
                   5414:           ($key, $string)=&str2hashref($string);
                   5415:           if(defined($key->{'error'})) {
                   5416:               $hash{'error'}='Bad data';
                   5417:               return (\%hash, $string);
                   5418:           }
                   5419:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5420:           ($key, $string)=&str2arrayref($string);
                   5421:           if($key->[0] eq 'Array reference error') {
                   5422:               $hash{'error'}='Bad data';
                   5423:               return (\%hash, $string);
                   5424:           }
                   5425:       } else {
                   5426:           $string =~ s/^(.*?)=//;
1.267     albertel 5427: 	  $key=&unescape($1);
1.265     albertel 5428:       }
                   5429:       $string =~ s/^=//;
                   5430: 
                   5431:       #value
                   5432:       my $value='';
                   5433:       if($string =~ /^__HASH_REF__/) {
                   5434:           ($value, $string)=&str2hashref($string);
                   5435:           if(defined($value->{'error'})) {
                   5436:               $hash{'error'}='Bad data';
                   5437:               return (\%hash, $string);
                   5438:           }
                   5439:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5440:           ($value, $string)=&str2arrayref($string);
                   5441:           if($value->[0] eq 'Array reference error') {
                   5442:               $hash{'error'}='Bad data';
                   5443:               return (\%hash, $string);
                   5444:           }
                   5445:       } else {
                   5446: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5447:       }
                   5448:       $string =~ s/^&//;
                   5449: 
                   5450:       $hash{$key}=$value;
1.204     albertel 5451:   }
1.265     albertel 5452: 
                   5453:   $string =~ s/^__END_HASH_REF__//;
                   5454: 
                   5455:   return (\%hash, $string);
1.204     albertel 5456: }
                   5457: 
                   5458: sub str2array {
1.265     albertel 5459:     my ($string)=@_;
                   5460:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5461:     return @$array;
                   5462: }
                   5463: 
                   5464: sub str2arrayref {
1.204     albertel 5465:   my ($string) = @_;
1.265     albertel 5466:   my @array;
                   5467: 
                   5468:   if($string !~ /^__ARRAY_REF__/) {
                   5469:       if (! ($string eq '' || !defined($string))) {
                   5470: 	  $array[0]='Array reference error';
                   5471:       }
                   5472:       return (\@array, $string);
                   5473:   }
                   5474: 
                   5475:   $string =~ s/^__ARRAY_REF__//;
                   5476: 
                   5477:   while($string !~ /^__END_ARRAY_REF__/) {
                   5478:       my $value='';
                   5479:       if($string =~ /^__HASH_REF__/) {
                   5480:           ($value, $string)=&str2hashref($string);
                   5481:           if(defined($value->{'error'})) {
                   5482:               $array[0] ='Array reference error';
                   5483:               return (\@array, $string);
                   5484:           }
                   5485:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5486:           ($value, $string)=&str2arrayref($string);
                   5487:           if($value->[0] eq 'Array reference error') {
                   5488:               $array[0] ='Array reference error';
                   5489:               return (\@array, $string);
                   5490:           }
                   5491:       } else {
                   5492: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5493:       }
                   5494:       $string =~ s/^&//;
                   5495: 
                   5496:       push(@array, $value);
1.191     harris41 5497:   }
1.265     albertel 5498: 
                   5499:   $string =~ s/^__END_ARRAY_REF__//;
                   5500: 
                   5501:   return (\@array, $string);
1.168     albertel 5502: }
                   5503: 
1.167     albertel 5504: # -------------------------------------------------------------------Temp Store
                   5505: 
1.168     albertel 5506: sub tmpreset {
                   5507:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5508:   if (!$symb) {
                   5509:     $symb=&symbread();
1.620     albertel 5510:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5511:   }
                   5512:   $symb=escape($symb);
                   5513: 
1.620     albertel 5514:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5515:   $namespace=~s/\//\_/g;
                   5516:   $namespace=~s/\W//g;
                   5517: 
1.620     albertel 5518:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5519:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5520:   if ($domain eq 'public' && $stuname eq 'public') {
                   5521:       $stuname=$ENV{'REMOTE_ADDR'};
                   5522:   }
1.1117    foxr     5523:   my $path=LONCAPA::tempdir();
1.168     albertel 5524:   my %hash;
                   5525:   if (tie(%hash,'GDBM_File',
                   5526: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5527: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5528:     foreach my $key (keys(%hash)) {
1.180     albertel 5529:       if ($key=~ /:$symb/) {
1.168     albertel 5530: 	delete($hash{$key});
                   5531:       }
                   5532:     }
                   5533:   }
                   5534: }
                   5535: 
1.167     albertel 5536: sub tmpstore {
1.168     albertel 5537:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5538: 
                   5539:   if (!$symb) {
                   5540:     $symb=&symbread();
1.620     albertel 5541:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5542:   }
                   5543:   $symb=escape($symb);
                   5544: 
                   5545:   if (!$namespace) {
                   5546:     # I don't think we would ever want to store this for a course.
                   5547:     # it seems this will only be used if we don't have a course.
1.620     albertel 5548:     #$namespace=$env{'request.course.id'};
1.168     albertel 5549:     #if (!$namespace) {
1.620     albertel 5550:       $namespace=$env{'request.state'};
1.168     albertel 5551:     #}
                   5552:   }
                   5553:   $namespace=~s/\//\_/g;
                   5554:   $namespace=~s/\W//g;
1.620     albertel 5555:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5556:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5557:   if ($domain eq 'public' && $stuname eq 'public') {
                   5558:       $stuname=$ENV{'REMOTE_ADDR'};
                   5559:   }
1.168     albertel 5560:   my $now=time;
                   5561:   my %hash;
1.1117    foxr     5562:   my $path=LONCAPA::tempdir();
1.168     albertel 5563:   if (tie(%hash,'GDBM_File',
                   5564: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5565: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5566:     $hash{"version:$symb"}++;
                   5567:     my $version=$hash{"version:$symb"};
                   5568:     my $allkeys=''; 
                   5569:     foreach my $key (keys(%$storehash)) {
                   5570:       $allkeys.=$key.':';
1.591     albertel 5571:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5572:     }
                   5573:     $hash{"$version:$symb:timestamp"}=$now;
                   5574:     $allkeys.='timestamp';
                   5575:     $hash{"$version:keys:$symb"}=$allkeys;
                   5576:     if (untie(%hash)) {
                   5577:       return 'ok';
                   5578:     } else {
                   5579:       return "error:$!";
                   5580:     }
                   5581:   } else {
                   5582:     return "error:$!";
                   5583:   }
                   5584: }
1.167     albertel 5585: 
1.168     albertel 5586: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5587: 
1.168     albertel 5588: sub tmprestore {
                   5589:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5590: 
1.168     albertel 5591:   if (!$symb) {
                   5592:     $symb=&symbread();
1.620     albertel 5593:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5594:   }
                   5595:   $symb=escape($symb);
                   5596: 
1.620     albertel 5597:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5598: 
1.620     albertel 5599:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5600:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5601:   if ($domain eq 'public' && $stuname eq 'public') {
                   5602:       $stuname=$ENV{'REMOTE_ADDR'};
                   5603:   }
1.168     albertel 5604:   my %returnhash;
                   5605:   $namespace=~s/\//\_/g;
                   5606:   $namespace=~s/\W//g;
                   5607:   my %hash;
1.1117    foxr     5608:   my $path=LONCAPA::tempdir();
1.168     albertel 5609:   if (tie(%hash,'GDBM_File',
                   5610: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5611: 	  &GDBM_READER(),0640)) {
1.168     albertel 5612:     my $version=$hash{"version:$symb"};
                   5613:     $returnhash{'version'}=$version;
                   5614:     my $scope;
                   5615:     for ($scope=1;$scope<=$version;$scope++) {
                   5616:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5617:       my @keys=split(/:/,$vkeys);
                   5618:       my $key;
                   5619:       $returnhash{"$scope:keys"}=$vkeys;
                   5620:       foreach $key (@keys) {
1.591     albertel 5621: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5622: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5623:       }
                   5624:     }
1.168     albertel 5625:     if (!(untie(%hash))) {
                   5626:       return "error:$!";
                   5627:     }
                   5628:   } else {
                   5629:     return "error:$!";
                   5630:   }
                   5631:   return %returnhash;
1.167     albertel 5632: }
                   5633: 
1.9       www      5634: # ----------------------------------------------------------------------- Store
                   5635: 
                   5636: sub store {
1.1269    raeburn  5637:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5638:     my $home='';
                   5639: 
1.168     albertel 5640:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5641: 
1.213     www      5642:     $symb=&symbclean($symb);
1.122     albertel 5643:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5644: 
1.620     albertel 5645:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5646:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5647: 
                   5648:     &devalidate($symb,$stuname,$domain);
1.109     www      5649: 
                   5650:     $symb=escape($symb);
1.187     www      5651:     if (!$namespace) { 
1.620     albertel 5652:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5653:           return ''; 
                   5654:        } 
                   5655:     }
1.620     albertel 5656:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5657: 
                   5658:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5659:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5660: 
1.12      www      5661:     my $namevalue='';
1.800     albertel 5662:     foreach my $key (keys(%$storehash)) {
                   5663:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5664:     }
1.12      www      5665:     $namevalue=~s/\&$//;
1.187     www      5666:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5667:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5668: }
                   5669: 
1.47      www      5670: # -------------------------------------------------------------- Critical Store
                   5671: 
                   5672: sub cstore {
1.1269    raeburn  5673:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5674:     my $home='';
                   5675: 
1.168     albertel 5676:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5677: 
1.213     www      5678:     $symb=&symbclean($symb);
1.122     albertel 5679:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5680: 
1.620     albertel 5681:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5682:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5683: 
                   5684:     &devalidate($symb,$stuname,$domain);
1.109     www      5685: 
                   5686:     $symb=escape($symb);
1.187     www      5687:     if (!$namespace) { 
1.620     albertel 5688:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5689:           return ''; 
                   5690:        } 
                   5691:     }
1.620     albertel 5692:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5693: 
                   5694:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5695:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5696: 
1.47      www      5697:     my $namevalue='';
1.800     albertel 5698:     foreach my $key (keys(%$storehash)) {
                   5699:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5700:     }
1.47      www      5701:     $namevalue=~s/\&$//;
1.187     www      5702:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5703:     return critical
1.1269    raeburn  5704:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5705: }
                   5706: 
1.9       www      5707: # --------------------------------------------------------------------- Restore
                   5708: 
                   5709: sub restore {
1.124     www      5710:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5711:     my $home='';
                   5712: 
1.168     albertel 5713:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5714: 
1.122     albertel 5715:     if (!$symb) {
1.1224    raeburn  5716:         return if ($namespace eq 'courserequests');
                   5717:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5718:     } else {
1.1224    raeburn  5719:         unless ($namespace eq 'courserequests') {
                   5720:             $symb=&escape(&symbclean($symb));
                   5721:         }
1.122     albertel 5722:     }
1.188     www      5723:     if (!$namespace) { 
1.620     albertel 5724:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5725:           return ''; 
                   5726:        } 
                   5727:     }
1.620     albertel 5728:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5729:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5730:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5731:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5732: 
1.12      www      5733:     my %returnhash=();
1.800     albertel 5734:     foreach my $line (split(/\&/,$answer)) {
                   5735: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5736:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5737:     }
1.75      www      5738:     my $version;
                   5739:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5740:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5741:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5742:        }
1.75      www      5743:     }
1.13      www      5744:     return %returnhash;
1.34      www      5745: }
                   5746: 
                   5747: # ---------------------------------------------------------- Course Description
1.1118    foxr     5748: #
                   5749: #  
1.34      www      5750: 
                   5751: sub coursedescription {
1.731     albertel 5752:     my ($courseid,$args)=@_;
1.34      www      5753:     $courseid=~s/^\///;
1.49      www      5754:     $courseid=~s/\_/\//g;
1.34      www      5755:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5756:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5757:     my $normalid=$cdomain.'_'.$cnum;
                   5758:     # need to always cache even if we get errors otherwise we keep 
                   5759:     # trying and trying and trying to get the course description.
                   5760:     my %envhash=();
                   5761:     my %returnhash=();
1.731     albertel 5762:     
                   5763:     my $expiretime=600;
                   5764:     if ($env{'request.course.id'} eq $normalid) {
                   5765: 	$expiretime=120;
                   5766:     }
                   5767: 
                   5768:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5769:     if (!$args->{'freshen_cache'}
                   5770: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5771: 	foreach my $key (keys(%env)) {
                   5772: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5773: 	    my ($setting) = $1;
                   5774: 	    $returnhash{$setting} = $env{$key};
                   5775: 	}
                   5776: 	return %returnhash;
                   5777:     }
                   5778: 
1.1118    foxr     5779:     # get the data again
                   5780: 
1.731     albertel 5781:     if (!$args->{'one_time'}) {
                   5782: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5783:     }
1.811     albertel 5784: 
1.34      www      5785:     if ($chome ne 'no_host') {
1.302     albertel 5786:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5787:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5788: 	   my $username = $env{'user.name'}; # Defult username
                   5789: 	   if(defined $args->{'user'}) {
                   5790: 	       $username = $args->{'user'};
                   5791: 	   }
1.129     albertel 5792:            $returnhash{'home'}= $chome;
                   5793: 	   $returnhash{'domain'} = $cdomain;
                   5794: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5795:            if (!defined($returnhash{'type'})) {
                   5796:                $returnhash{'type'} = 'Course';
                   5797:            }
1.130     albertel 5798:            while (my ($name,$value) = each %returnhash) {
1.53      www      5799:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5800:            }
1.270     www      5801:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5802:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5803: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5804:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5805:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5806:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5807:        }
                   5808:     }
1.731     albertel 5809:     if (!$args->{'one_time'}) {
1.949     raeburn  5810: 	&appenv(\%envhash);
1.731     albertel 5811:     }
1.302     albertel 5812:     return %returnhash;
1.461     www      5813: }
                   5814: 
1.1080    raeburn  5815: sub update_released_required {
                   5816:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5817:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5818:         $cid = $env{'request.course.id'};
                   5819:         $cdom = $env{'course.'.$cid.'.domain'};
                   5820:         $cnum = $env{'course.'.$cid.'.num'};
                   5821:         $chome = $env{'course.'.$cid.'.home'};
                   5822:     }
                   5823:     if ($needsrelease) {
                   5824:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5825:         my $needsupdate;
                   5826:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5827:             $needsupdate = 1;
                   5828:         } else {
                   5829:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5830:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5831:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5832:                 $needsupdate = 1;
                   5833:             }
                   5834:         }
                   5835:         if ($needsupdate) {
                   5836:             my %needshash = (
                   5837:                              'internal.releaserequired' => $needsrelease,
                   5838:                             );
                   5839:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5840:             if ($putresult eq 'ok') {
                   5841:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5842:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5843:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5844:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5845:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5846:                 }
                   5847:             }
                   5848:         }
                   5849:     }
                   5850:     return;
                   5851: }
                   5852: 
1.461     www      5853: # -------------------------------------------------See if a user is privileged
                   5854: 
                   5855: sub privileged {
1.1219    raeburn  5856:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5857:     my $now = time;
1.1219    raeburn  5858:     my $roles;
                   5859:     if (ref($possroles) eq 'ARRAY') {
                   5860:         $roles = $possroles; 
                   5861:     } else {
                   5862:         $roles = ['dc','su'];
                   5863:     }
                   5864:     if (ref($possdomains) eq 'ARRAY') {
                   5865:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5866:         foreach my $dom (@{$possdomains}) {
                   5867:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5868:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5869:                 foreach my $role (@{$roles}) {
                   5870:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5871:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5872:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5873:                             return 1 unless (($end && $end < $now) ||
                   5874:                                              ($start && $start > $now));
                   5875:                         }
                   5876:                     }
                   5877:                 }
                   5878:             }
                   5879:         }
                   5880:     } else {
                   5881:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5882:         my $now = time;
1.1170    droeschl 5883: 
1.1275    musolffc 5884:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5885:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5886:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5887:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5888:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5889:             }
1.1219    raeburn  5890:         }
                   5891:     }
                   5892:     return 0;
                   5893: }
1.1170    droeschl 5894: 
1.1219    raeburn  5895: sub privileged_by_domain {
                   5896:     my ($domains,$roles) = @_;
                   5897:     my %privileged = ();
                   5898:     my $cachetime = 60*60*24;
                   5899:     my $now = time;
                   5900:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5901:         return %privileged;
                   5902:     }
                   5903:     foreach my $dom (@{$domains}) {
                   5904:         next if (ref($privileged{$dom}) eq 'HASH');
                   5905:         my $needroles;
                   5906:         foreach my $role (@{$roles}) {
                   5907:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5908:             if (defined($cached)) {
                   5909:                 if (ref($result) eq 'HASH') {
                   5910:                     $privileged{$dom}{$role} = $result;
                   5911:                 }
                   5912:             } else {
                   5913:                 $needroles = 1;
                   5914:             }
                   5915:         }
                   5916:         if ($needroles) {
                   5917:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5918:             $privileged{$dom} = {};
                   5919:             foreach my $server (keys(%dompersonnel)) {
                   5920:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5921:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5922:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5923:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5924:                         next if ($end && $end < $now);
                   5925:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5926:                             $dompersonnel{$server}{$item};
                   5927:                     }
                   5928:                 }
                   5929:             }
                   5930:             if (ref($privileged{$dom}) eq 'HASH') {
                   5931:                 foreach my $role (@{$roles}) {
                   5932:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5933:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5934:                     } else {
                   5935:                         my %hash = ();
                   5936:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5937:                     }
                   5938:                 }
                   5939:             }
                   5940:         }
                   5941:     }
                   5942:     return %privileged;
1.9       www      5943: }
1.1       albertel 5944: 
1.103     harris41 5945: # -------------------------------------------------------- Get user privileges
1.11      www      5946: 
                   5947: sub rolesinit {
1.1169    droeschl 5948:     my ($domain, $username) = @_;
                   5949:     my %userroles = ('user.login.time' => time);
                   5950:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5951: 
                   5952:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5953:     # also, blocking can be triggered by an activating timer
                   5954:     # it's saved in the user's %env.
                   5955:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5956:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5957:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5958:         %timerintchk, %timerintenv);
                   5959: 
1.1162    raeburn  5960:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5961:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5962:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5963:     }
1.1169    droeschl 5964: 
1.1162    raeburn  5965:     foreach my $key (keys(%timerinterval)) {
                   5966:         my ($cid,$rest) = split(/\0/,$key);
                   5967:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5968:     }
1.1169    droeschl 5969: 
1.11      www      5970:     my %allroles=();
1.1162    raeburn  5971:     my %allgroups=();
1.11      www      5972: 
1.1274    raeburn  5973:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5974:         my $role = $rolesdump{$area};
                   5975:         $area =~ s/\_\w\w$//;
                   5976: 
                   5977:         my ($trole, $tend, $tstart, $group_privs);
                   5978: 
                   5979:         if ($role =~ /^cr/) {
                   5980:         # Custom role, defined by a user 
                   5981:         # e.g., user.role.cr/msu/smith/mynewrole
                   5982:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5983:                 $trole = $1;
                   5984:                 ($tend, $tstart) = split('_', $2);
                   5985:             } else {
                   5986:                 $trole = $role;
                   5987:             }
                   5988:         } elsif ($role =~ m|^gr/|) {
                   5989:         # Role of member in a group, defined within a course/community
                   5990:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5991:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5992:             next if $tstart eq '-1';
                   5993:             ($trole, $group_privs) = split(/\//, $trole);
                   5994:             $group_privs = &unescape($group_privs);
                   5995:         } else {
                   5996:         # Just a normal role, defined in roles.tab
                   5997:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5998:         }
                   5999: 
                   6000:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6001:                  $username);
                   6002:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6003: 
                   6004:         # role expired or not available yet?
                   6005:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6006:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6007: 
                   6008:         next if $area eq '' or $trole eq '';
                   6009: 
                   6010:         my $spec = "$trole.$area";
                   6011:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6012: 
                   6013:         if ($trole =~ /^cr\//) {
                   6014:         # Custom role, defined by a user
                   6015:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6016:         } elsif ($trole eq 'gr') {
                   6017:         # Role of a member in a group, defined within a course/community
                   6018:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6019:             next;
                   6020:         } else {
                   6021:         # Normal role, defined in roles.tab
                   6022:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6023:         }
                   6024: 
                   6025:         my $cid = $tdomain.'_'.$trest;
                   6026:         unless ($firstaccchk{$cid}) {
                   6027:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6028:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6029:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6030:                         $coursetimerstarts{$cid}{$item}; 
                   6031:                 }
                   6032:             }
                   6033:             $firstaccchk{$cid} = 1;
                   6034:         }
                   6035:         unless ($timerintchk{$cid}) {
                   6036:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6037:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6038:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6039:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6040:                 }
1.12      www      6041:             }
1.1169    droeschl 6042:             $timerintchk{$cid} = 1;
1.191     harris41 6043:         }
1.11      www      6044:     }
1.1169    droeschl 6045: 
1.1341    raeburn  6046:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6047:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6048:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6049:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6050: 
1.1162    raeburn  6051:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6052: }
                   6053: 
1.567     raeburn  6054: sub set_arearole {
1.1215    raeburn  6055:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6056:     unless ($nolog) {
1.567     raeburn  6057: # log the associated role with the area
1.1215    raeburn  6058:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6059:     }
1.743     albertel 6060:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6061: }
                   6062: 
                   6063: sub custom_roleprivs {
                   6064:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6065:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6066:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6067:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6068:         my ($rdummy,$roledef)=
                   6069:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6070:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6071:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6072:             if (defined($syspriv)) {
1.1043    raeburn  6073:                 if ($trest =~ /^$match_community$/) {
                   6074:                     $syspriv =~ s/bre\&S//; 
                   6075:                 }
1.567     raeburn  6076:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6077:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6078:             }
                   6079:             if ($tdomain ne '') {
                   6080:                 if (defined($dompriv)) {
                   6081:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6082:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6083:                 }
                   6084:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6085:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6086:                         my $rolename = $1;
                   6087:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6088:                     }
1.567     raeburn  6089:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6090:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6091:                 }
                   6092:             }
                   6093:         }
                   6094:     }
                   6095: }
                   6096: 
1.1332    raeburn  6097: sub course_adhocrole_privs {
                   6098:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6099:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6100:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6101:         my (%currprivs,%storeprivs);
                   6102:         foreach my $item (split(/:/,$coursepriv)) {
                   6103:             my ($priv,$restrict) = split(/\&/,$item);
                   6104:             $currprivs{$priv} = $restrict;
                   6105:         }
                   6106:         my (%possadd,%possremove,%full);
                   6107:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6108:             my ($priv,$restrict)=split(/\&/,$item);
                   6109:             $full{$priv} = $restrict;
                   6110:         }
                   6111:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6112:              next if ($item eq '');
                   6113:              my ($rule,$rest) = split(/=/,$item);
                   6114:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6115:              foreach my $priv (split(/:/,$rest)) {
                   6116:                  if ($priv ne '') {
                   6117:                      if ($rule eq 'off') {
                   6118:                          $possremove{$priv} = 1;
                   6119:                      } else {
                   6120:                          $possadd{$priv} = 1;
                   6121:                      }
                   6122:                  }
                   6123:              }
                   6124:          }
                   6125:          foreach my $priv (sort(keys(%full))) {
                   6126:              if (exists($currprivs{$priv})) {
                   6127:                  unless (exists($possremove{$priv})) {
                   6128:                      $storeprivs{$priv} = $currprivs{$priv};
                   6129:                  }
                   6130:              } elsif (exists($possadd{$priv})) {
                   6131:                  $storeprivs{$priv} = $full{$priv};
                   6132:              }
                   6133:          }
                   6134:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6135:      }
                   6136:      return $coursepriv;
                   6137: }
                   6138: 
1.678     raeburn  6139: sub group_roleprivs {
                   6140:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6141:     my $access = 1;
                   6142:     my $now = time;
                   6143:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6144:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6145:     if ($access) {
1.811     albertel 6146:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6147:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6148:     }
                   6149: }
1.567     raeburn  6150: 
                   6151: sub standard_roleprivs {
                   6152:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6153:     if (defined($pr{$trole.':s'})) {
                   6154:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6155:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6156:     }
                   6157:     if ($tdomain ne '') {
                   6158:         if (defined($pr{$trole.':d'})) {
                   6159:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6160:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6161:         }
                   6162:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6163:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6164:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6165:         }
                   6166:     }
                   6167: }
                   6168: 
                   6169: sub set_userprivs {
1.1064    raeburn  6170:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6171:     my $author=0;
                   6172:     my $adv=0;
1.1341    raeburn  6173:     my $rar=0;
1.678     raeburn  6174:     my %grouproles = ();
                   6175:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6176:         my @groupkeys; 
1.1000    raeburn  6177:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6178:             push(@groupkeys,$role);
                   6179:         }
                   6180:         if (ref($groups_roles) eq 'HASH') {
                   6181:             foreach my $key (keys(%{$groups_roles})) {
                   6182:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6183:                     push(@groupkeys,$key);
                   6184:                 }
                   6185:             }
                   6186:         }
                   6187:         if (@groupkeys > 0) {
                   6188:             foreach my $role (@groupkeys) {
                   6189:                 my ($trole,$area,$sec,$extendedarea);
                   6190:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6191:                     $trole = $1;
                   6192:                     $area = $2;
                   6193:                     $sec = $3;
                   6194:                     $extendedarea = $area.$sec;
                   6195:                     if (exists($$allgroups{$area})) {
                   6196:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6197:                             my $spec = $trole.'.'.$extendedarea;
                   6198:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6199:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6200:                         }
1.678     raeburn  6201:                     }
                   6202:                 }
                   6203:             }
                   6204:         }
                   6205:     }
1.800     albertel 6206:     foreach my $group (keys(%grouproles)) {
                   6207:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6208:     }
1.800     albertel 6209:     foreach my $role (keys(%{$allroles})) {
                   6210:         my %thesepriv;
1.941     raeburn  6211:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6212:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6213:             if ($item ne '') {
                   6214:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6215:                 if ($restrictions eq '') {
                   6216:                     $thesepriv{$privilege}='F';
                   6217:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6218:                     $thesepriv{$privilege}.=$restrictions;
                   6219:                 }
                   6220:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6221:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6222:             }
                   6223:         }
                   6224:         my $thesestr='';
1.1104    raeburn  6225:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6226: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6227: 	}
                   6228:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6229:     }
1.1341    raeburn  6230:     return ($author,$adv,$rar);
1.567     raeburn  6231: }
                   6232: 
1.994     raeburn  6233: sub role_status {
1.1104    raeburn  6234:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6235:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6236:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6237:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6238:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6239:             $$where = '/'.$two;
1.994     raeburn  6240:             $$trolecode=$$role.'.'.$$where;
                   6241:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6242:             $$tstatus='is';
1.1104    raeburn  6243:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6244:                 $$tstatus='future';
1.1034    raeburn  6245:                 if ($$tstart<$now) {
                   6246:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6247:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6248:                             my (%allroles,%allgroups,$group_privs,
                   6249:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6250:                             my %userroles = (
                   6251:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6252:                             );
1.1064    raeburn  6253:                             @rolecodes = ('cm'); 
1.1002    raeburn  6254:                             my $spec=$$role.'.'.$$where;
                   6255:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6256:                             if ($$role =~ /^cr\//) {
                   6257:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6258:                                 push(@rolecodes,'cr');
1.1002    raeburn  6259:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6260:                                 push(@rolecodes,$$role);
1.1002    raeburn  6261:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6262:                                                     $env{'user.name'});
1.1064    raeburn  6263:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6264:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6265:                                 $group_privs = &unescape($group_privs);
                   6266:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6267:                                 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  6268:                                 &get_groups_roles($tdomain,$trest,
                   6269:                                                   \%course_roles,\@rolecodes,
                   6270:                                                   \%groups_roles);
1.1002    raeburn  6271:                             } else {
1.1064    raeburn  6272:                                 push(@rolecodes,$$role);
1.1002    raeburn  6273:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6274:                             }
1.1341    raeburn  6275:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6276:                                                                    \%groups_roles);
1.1064    raeburn  6277:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6278:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6279:                         }
                   6280:                     }
1.1034    raeburn  6281:                     $$tstatus = 'is';
1.1002    raeburn  6282:                 }
1.994     raeburn  6283:             }
                   6284:             if ($$tend) {
1.1104    raeburn  6285:                 if ($$tend<$update) {
1.994     raeburn  6286:                     $$tstatus='expired';
                   6287:                 } elsif ($$tend<$now) {
                   6288:                     $$tstatus='will_not';
                   6289:                 }
                   6290:             }
                   6291:         }
                   6292:     }
                   6293: }
                   6294: 
1.1104    raeburn  6295: sub get_groups_roles {
                   6296:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6297:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6298:                   (ref($rolecodes) eq 'ARRAY') && 
                   6299:                   (ref($groups_roles) eq 'HASH')); 
                   6300:     if (keys(%{$cdom_courseroles}) > 0) {
                   6301:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6302:         if ($cdom ne '' && $cnum ne '') {
                   6303:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6304:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6305:                     my $crsrole = $1;
                   6306:                     my $crssec = $2;
                   6307:                     if ($crsrole =~ /^cr/) {
                   6308:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6309:                             push(@{$rolecodes},'cr');
                   6310:                         }
                   6311:                     } else {
                   6312:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6313:                             push(@{$rolecodes},$crsrole);
                   6314:                         }
                   6315:                     }
                   6316:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6317:                     if ($crssec ne '') {
                   6318:                         $rolekey .= "/$crssec";
                   6319:                     }
                   6320:                     $rolekey .= './';
                   6321:                     $groups_roles->{$rolekey} = $rolecodes;
                   6322:                 }
                   6323:             }
                   6324:         }
                   6325:     }
                   6326:     return;
                   6327: }
                   6328: 
                   6329: sub delete_env_groupprivs {
                   6330:     my ($where,$courseroles,$possroles) = @_;
                   6331:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6332:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6333:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6334:         %{$courseroles->{$udom}} =
                   6335:             &get_my_roles('','','userroles',['active'],
                   6336:                           $possroles,[$udom],1);
                   6337:     }
                   6338:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6339:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6340:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6341:             my $area = '/'.$cdom.'/'.$cnum;
                   6342:             my $privkey = "user.priv.$crsrole.$area";
                   6343:             if ($crssec ne '') {
                   6344:                 $privkey .= '/'.$crssec;
                   6345:             }
                   6346:             $privkey .= ".$area/$group";
                   6347:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6348:         }
                   6349:     }
                   6350:     return;
                   6351: }
                   6352: 
1.994     raeburn  6353: sub check_adhoc_privs {
1.1329    raeburn  6354:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6355:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6356:     if ($sec) {
                   6357:         $cckey .= '/'.$sec;
                   6358:     } 
1.1185    raeburn  6359:     my $setprivs;
1.994     raeburn  6360:     if ($env{$cckey}) {
                   6361:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6362:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6363:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6364:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6365:             $setprivs = 1;
1.994     raeburn  6366:         }
                   6367:     } else {
1.1330    raeburn  6368:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6369:         $setprivs = 1;
1.994     raeburn  6370:     }
1.1185    raeburn  6371:     return $setprivs;
1.994     raeburn  6372: }
                   6373: 
                   6374: sub set_adhoc_privileges {
1.1326    raeburn  6375: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6376:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6377:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6378:     if ($sec ne '') {
                   6379:         $area .= '/'.$sec;
                   6380:     }
1.994     raeburn  6381:     my $spec = $role.'.'.$area;
                   6382:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6383:                                   $env{'user.name'},1);
1.1326    raeburn  6384:     my %rolehash = ();
1.1332    raeburn  6385:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6386:         my $rolename = $1;
1.1326    raeburn  6387:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6388:         my %domdef = &get_domain_defaults($dcdom);
                   6389:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6390:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6391:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6392:             }
                   6393:         }
1.1326    raeburn  6394:     } else {
                   6395:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6396:     }
1.1341    raeburn  6397:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6398:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6399:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6400:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6401:         &appenv( {'request.role'        => $spec,
                   6402:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6403:                   'request.course.sec'  => $sec,
1.1088    raeburn  6404:                  }
                   6405:                );
                   6406:         my $tadv=0;
                   6407:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6408:         &appenv({'request.role.adv'    => $tadv});
                   6409:     }
1.994     raeburn  6410: }
                   6411: 
1.12      www      6412: # --------------------------------------------------------------- get interface
                   6413: 
                   6414: sub get {
1.131     albertel 6415:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6416:    my $items='';
1.800     albertel 6417:    foreach my $item (@$storearr) {
                   6418:        $items.=&escape($item).'&';
1.191     harris41 6419:    }
1.12      www      6420:    $items=~s/\&$//;
1.620     albertel 6421:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6422:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6423:    my $uhome=&homeserver($uname,$udomain);
                   6424: 
1.133     albertel 6425:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6426:    my @pairs=split(/\&/,$rep);
1.273     albertel 6427:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6428:      return @pairs;
                   6429:    }
1.15      www      6430:    my %returnhash=();
1.42      www      6431:    my $i=0;
1.800     albertel 6432:    foreach my $item (@$storearr) {
                   6433:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6434:       $i++;
1.191     harris41 6435:    }
1.15      www      6436:    return %returnhash;
1.27      www      6437: }
                   6438: 
                   6439: # --------------------------------------------------------------- del interface
                   6440: 
                   6441: sub del {
1.133     albertel 6442:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6443:    my $items='';
1.800     albertel 6444:    foreach my $item (@$storearr) {
                   6445:        $items.=&escape($item).'&';
1.191     harris41 6446:    }
1.984     neumanie 6447: 
1.27      www      6448:    $items=~s/\&$//;
1.620     albertel 6449:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6450:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6451:    my $uhome=&homeserver($uname,$udomain);
                   6452:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6453: }
                   6454: 
                   6455: # -------------------------------------------------------------- dump interface
                   6456: 
1.1180    droeschl 6457: sub unserialize {
                   6458:     my ($rep, $escapedkeys) = @_;
                   6459: 
                   6460:     return {} if $rep =~ /^error/;
                   6461: 
                   6462:     my %returnhash=();
1.1252    raeburn  6463: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6464: 	    my ($key, $value) = split(/=/, $item, 2);
                   6465: 	    $key = unescape($key) unless $escapedkeys;
                   6466: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6467: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6468: 	}
                   6469:     #return %returnhash;
                   6470:     return \%returnhash;
                   6471: }        
                   6472: 
                   6473: # see Lond::dump_with_regexp
                   6474: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6475: sub dump {
1.1180    droeschl 6476:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6477:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6478:     if (!$uname) { $uname=$env{'user.name'}; }
                   6479:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6480: 
1.1266    raeburn  6481:     if ($regexp) {
                   6482:         $regexp=&escape($regexp);
                   6483:     } else {
                   6484:         $regexp='.';
                   6485:     }
1.1180    droeschl 6486:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6487:         # user is hosted on this machine
1.1266    raeburn  6488:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6489:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6490:         return %{unserialize($reply, $escapedkeys)};
                   6491:     }
1.1166    raeburn  6492:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6493:     my @pairs=split(/\&/,$rep);
                   6494:     my %returnhash=();
1.1098    foxr     6495:     if (!($rep =~ /^error/ )) {
                   6496: 	foreach my $item (@pairs) {
                   6497: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6498:         $key = unescape($key) unless $escapedkeys;
                   6499:         #$key = &unescape($key);
1.1098    foxr     6500: 	    next if ($key =~ /^error: 2 /);
                   6501: 	    $returnhash{$key}=&thaw_unescape($value);
                   6502: 	}
1.755     albertel 6503:     }
                   6504:     return %returnhash;
1.407     www      6505: }
                   6506: 
1.1098    foxr     6507: 
1.717     albertel 6508: # --------------------------------------------------------- dumpstore interface
                   6509: 
                   6510: sub dumpstore {
                   6511:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6512:    # same as dump but keys must be escaped. They may contain colon separated
                   6513:    # lists of values that may themself contain colons (e.g. symbs).
                   6514:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6515: }
                   6516: 
1.407     www      6517: # -------------------------------------------------------------- keys interface
                   6518: 
                   6519: sub getkeys {
                   6520:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6521:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6522:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6523:    my $uhome=&homeserver($uname,$udomain);
                   6524:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6525:    my @keyarray=();
1.800     albertel 6526:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6527:       next if ($key =~ /^error: 2 /);
1.800     albertel 6528:       push(@keyarray,&unescape($key));
1.407     www      6529:    }
                   6530:    return @keyarray;
1.318     matthew  6531: }
                   6532: 
1.319     matthew  6533: # --------------------------------------------------------------- currentdump
                   6534: sub currentdump {
1.328     matthew  6535:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6536:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6537:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6538:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6539:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6540:    my $rep;
                   6541: 
                   6542:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6543:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6544:                    $courseid)));
                   6545:    } else {
                   6546:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6547:    }
                   6548: 
1.318     matthew  6549:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6550:    #
1.318     matthew  6551:    my %returnhash=();
1.319     matthew  6552:    #
1.1343    raeburn  6553:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6554:        # an old lond will not know currentdump
                   6555:        # Do a dump and make it look like a currentdump
1.822     albertel 6556:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6557:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6558:        my %hash = @tmp;
                   6559:        @tmp=();
1.424     matthew  6560:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6561:    } else {
                   6562:        my @pairs=split(/\&/,$rep);
1.800     albertel 6563:        foreach my $pair (@pairs) {
                   6564:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6565:            my ($symb,$param) = split(/:/,$key);
                   6566:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6567:                                                         &thaw_unescape($value);
1.319     matthew  6568:        }
1.191     harris41 6569:    }
1.12      www      6570:    return %returnhash;
1.424     matthew  6571: }
                   6572: 
                   6573: sub convert_dump_to_currentdump{
                   6574:     my %hash = %{shift()};
                   6575:     my %returnhash;
                   6576:     # Code ripped from lond, essentially.  The only difference
                   6577:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6578:     # we might run in to problems with parameter names =~ /^v\./
                   6579:     while (my ($key,$value) = each(%hash)) {
                   6580:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6581: 	$symb  = &unescape($symb);
                   6582: 	$param = &unescape($param);
1.424     matthew  6583:         next if ($v eq 'version' || $symb eq 'keys');
                   6584:         next if (exists($returnhash{$symb}) &&
                   6585:                  exists($returnhash{$symb}->{$param}) &&
                   6586:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6587:         $returnhash{$symb}->{$param}=$value;
                   6588:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6589:     }
                   6590:     #
                   6591:     # Remove all of the keys in the hashes which keep track of
                   6592:     # the version of the parameter.
                   6593:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6594:         # use a foreach because we are going to delete from the hash.
                   6595:         foreach my $key (keys(%$param_hash)) {
                   6596:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6597:         }
                   6598:     }
                   6599:     return \%returnhash;
1.12      www      6600: }
                   6601: 
1.627     albertel 6602: # ------------------------------------------------------ critical inc interface
                   6603: 
                   6604: sub cinc {
                   6605:     return &inc(@_,'critical');
                   6606: }
                   6607: 
1.449     matthew  6608: # --------------------------------------------------------------- inc interface
                   6609: 
                   6610: sub inc {
1.627     albertel 6611:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6612:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6613:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6614:     my $uhome=&homeserver($uname,$udomain);
                   6615:     my $items='';
                   6616:     if (! ref($store)) {
                   6617:         # got a single value, so use that instead
                   6618:         $items = &escape($store).'=&';
                   6619:     } elsif (ref($store) eq 'SCALAR') {
                   6620:         $items = &escape($$store).'=&';        
                   6621:     } elsif (ref($store) eq 'ARRAY') {
                   6622:         $items = join('=&',map {&escape($_);} @{$store});
                   6623:     } elsif (ref($store) eq 'HASH') {
                   6624:         while (my($key,$value) = each(%{$store})) {
                   6625:             $items.= &escape($key).'='.&escape($value).'&';
                   6626:         }
                   6627:     }
                   6628:     $items=~s/\&$//;
1.627     albertel 6629:     if ($critical) {
                   6630: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6631:     } else {
                   6632: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6633:     }
1.449     matthew  6634: }
                   6635: 
1.12      www      6636: # --------------------------------------------------------------- put interface
                   6637: 
                   6638: sub put {
1.134     albertel 6639:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6640:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6641:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6642:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6643:    my $items='';
1.800     albertel 6644:    foreach my $item (keys(%$storehash)) {
                   6645:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6646:    }
1.12      www      6647:    $items=~s/\&$//;
1.134     albertel 6648:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6649: }
                   6650: 
1.631     albertel 6651: # ------------------------------------------------------------ newput interface
                   6652: 
                   6653: sub newput {
                   6654:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6655:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6656:    if (!$uname) { $uname=$env{'user.name'}; }
                   6657:    my $uhome=&homeserver($uname,$udomain);
                   6658:    my $items='';
                   6659:    foreach my $key (keys(%$storehash)) {
                   6660:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6661:    }
                   6662:    $items=~s/\&$//;
                   6663:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6664: }
                   6665: 
                   6666: # ---------------------------------------------------------  putstore interface
                   6667: 
1.524     raeburn  6668: sub putstore {
1.1269    raeburn  6669:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6670:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6671:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6672:    my $uhome=&homeserver($uname,$udomain);
                   6673:    my $items='';
1.715     albertel 6674:    foreach my $key (keys(%$storehash)) {
                   6675:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6676:    }
1.715     albertel 6677:    $items=~s/\&$//;
1.716     albertel 6678:    my $esc_symb=&escape($symb);
                   6679:    my $esc_v=&escape($version);
1.715     albertel 6680:    my $reply =
1.716     albertel 6681:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6682: 	      $uhome);
1.1269    raeburn  6683:    if (($tolog) && ($reply eq 'ok')) {
                   6684:        my $namevalue='';
                   6685:        foreach my $key (keys(%{$storehash})) {
                   6686:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6687:        }
                   6688:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6689:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6690:                      '&version='.$esc_v.
                   6691:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6692:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6693:    }
1.715     albertel 6694:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6695:        # gfall back to way things use to be done
1.715     albertel 6696:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6697: 			    $uname);
1.524     raeburn  6698:    }
1.715     albertel 6699:    return $reply;
                   6700: }
                   6701: 
                   6702: sub old_putstore {
1.716     albertel 6703:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6704:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6705:     if (!$uname) { $uname=$env{'user.name'}; }
                   6706:     my $uhome=&homeserver($uname,$udomain);
                   6707:     my %newstorehash;
1.800     albertel 6708:     foreach my $item (keys(%$storehash)) {
                   6709: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6710: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6711:     }
                   6712:     my $items='';
                   6713:     my %allitems = ();
1.800     albertel 6714:     foreach my $item (keys(%newstorehash)) {
                   6715: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6716: 	    my $key = $1.':keys:'.$2;
                   6717: 	    $allitems{$key} .= $3.':';
                   6718: 	}
1.800     albertel 6719: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6720:     }
1.800     albertel 6721:     foreach my $item (keys(%allitems)) {
                   6722: 	$allitems{$item} =~ s/\:$//;
                   6723: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6724:     }
                   6725:     $items=~s/\&$//;
                   6726:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6727: }
                   6728: 
1.47      www      6729: # ------------------------------------------------------ critical put interface
                   6730: 
                   6731: sub cput {
1.134     albertel 6732:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6733:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6734:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6735:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6736:    my $items='';
1.800     albertel 6737:    foreach my $item (keys(%$storehash)) {
                   6738:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6739:    }
1.47      www      6740:    $items=~s/\&$//;
1.134     albertel 6741:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6742: }
                   6743: 
                   6744: # -------------------------------------------------------------- eget interface
                   6745: 
                   6746: sub eget {
1.133     albertel 6747:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6748:    my $items='';
1.800     albertel 6749:    foreach my $item (@$storearr) {
                   6750:        $items.=&escape($item).'&';
1.191     harris41 6751:    }
1.12      www      6752:    $items=~s/\&$//;
1.620     albertel 6753:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6754:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6755:    my $uhome=&homeserver($uname,$udomain);
                   6756:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6757:    my @pairs=split(/\&/,$rep);
                   6758:    my %returnhash=();
1.42      www      6759:    my $i=0;
1.800     albertel 6760:    foreach my $item (@$storearr) {
                   6761:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6762:       $i++;
1.191     harris41 6763:    }
1.12      www      6764:    return %returnhash;
                   6765: }
                   6766: 
1.667     albertel 6767: # ------------------------------------------------------------ tmpput interface
                   6768: sub tmpput {
1.802     raeburn  6769:     my ($storehash,$server,$context)=@_;
1.667     albertel 6770:     my $items='';
1.800     albertel 6771:     foreach my $item (keys(%$storehash)) {
                   6772: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6773:     }
                   6774:     $items=~s/\&$//;
1.802     raeburn  6775:     if (defined($context)) {
                   6776:         $items .= ':'.&escape($context);
                   6777:     }
1.667     albertel 6778:     return &reply("tmpput:$items",$server);
                   6779: }
                   6780: 
                   6781: # ------------------------------------------------------------ tmpget interface
                   6782: sub tmpget {
1.688     albertel 6783:     my ($token,$server)=@_;
                   6784:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6785:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6786:     my %returnhash;
1.1328    raeburn  6787:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6788:         return %returnhash;
                   6789:     }
1.667     albertel 6790:     foreach my $item (split(/\&/,$rep)) {
                   6791: 	my ($key,$value)=split(/=/,$item);
                   6792: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6793:     }
                   6794:     return %returnhash;
                   6795: }
                   6796: 
1.1113    raeburn  6797: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6798: sub tmpdel {
                   6799:     my ($token,$server)=@_;
                   6800:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6801:     return &reply("tmpdel:$token",$server);
                   6802: }
                   6803: 
1.1198    raeburn  6804: # ------------------------------------------------------------ get_timebased_id 
                   6805: 
                   6806: sub get_timebased_id {
                   6807:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6808:         $maxtries) = @_;
                   6809:     my ($newid,$error,$dellock);
                   6810:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6811:         return ('','ok','invalid call to get suffix');
                   6812:     }
                   6813: 
                   6814: # set defaults for any optional args for which values were not supplied
                   6815:     if ($who eq '') {
                   6816:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6817:     }
                   6818:     if (!$locktries) {
                   6819:         $locktries = 3;
                   6820:     }
                   6821:     if (!$maxtries) {
                   6822:         $maxtries = 10;
                   6823:     }
                   6824:     
                   6825:     if (($cdom eq '') || ($cnum eq '')) {
                   6826:         if ($env{'request.course.id'}) {
                   6827:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6828:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6829:         }
                   6830:         if (($cdom eq '') || ($cnum eq '')) {
                   6831:             return ('','ok','call to get suffix not in course context');
                   6832:         }
                   6833:     }
                   6834: 
                   6835: # construct locking item
                   6836:     my $lockhash = {
                   6837:                       $prefix."\0".'locked_'.$keyid => $who,
                   6838:                    };
                   6839:     my $tries = 0;
                   6840: 
                   6841: # attempt to get lock on nohist_$namespace file
                   6842:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6843:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6844:         $tries ++;
                   6845:         sleep 1;
                   6846:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6847:     }
                   6848: 
                   6849: # attempt to get unique identifier, based on current timestamp
                   6850:     if ($gotlock eq 'ok') {
                   6851:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6852:         my $id = time;
                   6853:         $newid = $id;
1.1268    raeburn  6854:         if ($idtype eq 'addcode') {
                   6855:             $newid .= &sixnum_code();
                   6856:         }
1.1198    raeburn  6857:         my $idtries = 0;
                   6858:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6859:             if ($idtype eq 'concat') {
                   6860:                 $newid = $id.$idtries;
1.1268    raeburn  6861:             } elsif ($idtype eq 'addcode') {
                   6862:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6863:             } else {
                   6864:                 $newid ++;
                   6865:             }
                   6866:             $idtries ++;
                   6867:         }
                   6868:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6869:             my %new_item =  (
                   6870:                               $prefix."\0".$newid => $who,
                   6871:                             );
                   6872:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6873:                                                  $cdom,$cnum);
                   6874:             if ($putresult ne 'ok') {
                   6875:                 undef($newid);
                   6876:                 $error = 'error saving new item: '.$putresult;
                   6877:             }
                   6878:         } else {
1.1268    raeburn  6879:              undef($newid);
1.1198    raeburn  6880:              $error = ('error: no unique suffix available for the new item ');
                   6881:         }
                   6882: #  remove lock
                   6883:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6884:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6885:     } else {
                   6886:         $error = "error: could not obtain lockfile\n";
                   6887:         $dellock = 'ok';
1.1276    raeburn  6888:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6889:             $dellock = 'nolock';
                   6890:         }
1.1198    raeburn  6891:     }
                   6892:     return ($newid,$dellock,$error);
                   6893: }
                   6894: 
1.1268    raeburn  6895: sub sixnum_code {
                   6896:     my $code;
                   6897:     for (0..6) {
                   6898:         $code .= int( rand(9) );
                   6899:     }
                   6900:     return $code;
                   6901: }
                   6902: 
1.765     albertel 6903: # -------------------------------------------------- portfolio access checking
                   6904: 
                   6905: sub portfolio_access {
1.1270    raeburn  6906:     my ($requrl,$clientip) = @_;
1.765     albertel 6907:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6908:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6909:     if ($result) {
                   6910:         my %setters;
                   6911:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6912:             my ($startblock,$endblock) =
                   6913:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6914:             if ($startblock && $endblock) {
                   6915:                 return 'B';
                   6916:             }
                   6917:         } else {
                   6918:             my ($startblock,$endblock) =
                   6919:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6920:             if ($startblock && $endblock) {
                   6921:                 return 'B';
                   6922:             }
                   6923:         }
                   6924:     }
1.765     albertel 6925:     if ($result eq 'ok') {
1.766     albertel 6926:        return 'F';
1.765     albertel 6927:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6928:        return 'A';
1.765     albertel 6929:     }
1.766     albertel 6930:     return '';
1.765     albertel 6931: }
                   6932: 
                   6933: sub get_portfolio_access {
1.1270    raeburn  6934:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6935: 
                   6936:     if (!ref($access_hash)) {
                   6937: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6938: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6939: 						   $file_name);
                   6940: 	$access_hash = $access_controls{$file_name};
                   6941:     }
                   6942: 
1.1270    raeburn  6943:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6944:     my $now = time;
                   6945:     if (ref($access_hash) eq 'HASH') {
                   6946:         foreach my $key (keys(%{$access_hash})) {
                   6947:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6948:             if ($start > $now) {
                   6949:                 next;
                   6950:             }
                   6951:             if ($end && $end<$now) {
                   6952:                 next;
                   6953:             }
                   6954:             if ($scope eq 'public') {
                   6955:                 $public = $key;
                   6956:                 last;
                   6957:             } elsif ($scope eq 'guest') {
                   6958:                 $guest = $key;
                   6959:             } elsif ($scope eq 'domains') {
                   6960:                 push(@domains,$key);
                   6961:             } elsif ($scope eq 'users') {
                   6962:                 push(@users,$key);
                   6963:             } elsif ($scope eq 'course') {
                   6964:                 push(@courses,$key);
                   6965:             } elsif ($scope eq 'group') {
                   6966:                 push(@groups,$key);
1.1270    raeburn  6967:             } elsif ($scope eq 'ip') {
                   6968:                 push(@ips,$key);
1.765     albertel 6969:             }
                   6970:         }
                   6971:         if ($public) {
                   6972:             return 'ok';
1.1270    raeburn  6973:         } elsif (@ips > 0) {
                   6974:             my $allowed;
                   6975:             foreach my $ipkey (@ips) {
                   6976:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6977:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6978:                         $allowed = 1;
                   6979:                         last; 
                   6980:                     }
                   6981:                 }
                   6982:             }
                   6983:             if ($allowed) {
                   6984:                 return 'ok';
                   6985:             }
1.765     albertel 6986:         }
                   6987:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6988:             if ($guest) {
                   6989:                 return $guest;
                   6990:             }
                   6991:         } else {
                   6992:             if (@domains > 0) {
                   6993:                 foreach my $domkey (@domains) {
                   6994:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6995:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6996:                             return 'ok';
                   6997:                         }
                   6998:                     }
                   6999:                 }
                   7000:             }
                   7001:             if (@users > 0) {
                   7002:                 foreach my $userkey (@users) {
1.865     raeburn  7003:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7004:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7005:                             if (ref($item) eq 'HASH') {
                   7006:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7007:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7008:                                     return 'ok';
                   7009:                                 }
                   7010:                             }
                   7011:                         }
                   7012:                     } 
1.765     albertel 7013:                 }
                   7014:             }
                   7015:             my %roleshash;
                   7016:             my @courses_and_groups = @courses;
                   7017:             push(@courses_and_groups,@groups); 
                   7018:             if (@courses_and_groups > 0) {
                   7019:                 my (%allgroups,%allroles); 
                   7020:                 my ($start,$end,$role,$sec,$group);
                   7021:                 foreach my $envkey (%env) {
1.1060    raeburn  7022:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7023:                         my $cid = $2.'_'.$3; 
                   7024:                         if ($1 eq 'gr') {
                   7025:                             $group = $4;
                   7026:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7027:                         } else {
                   7028:                             if ($4 eq '') {
                   7029:                                 $sec = 'none';
                   7030:                             } else {
                   7031:                                 $sec = $4;
                   7032:                             }
                   7033:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7034:                         }
1.811     albertel 7035:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7036:                         my $cid = $2.'_'.$3;
                   7037:                         if ($4 eq '') {
                   7038:                             $sec = 'none';
                   7039:                         } else {
                   7040:                             $sec = $4;
                   7041:                         }
                   7042:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7043:                     }
                   7044:                 }
                   7045:                 if (keys(%allroles) == 0) {
                   7046:                     return;
                   7047:                 }
                   7048:                 foreach my $key (@courses_and_groups) {
                   7049:                     my %content = %{$$access_hash{$key}};
                   7050:                     my $cnum = $content{'number'};
                   7051:                     my $cdom = $content{'domain'};
                   7052:                     my $cid = $cdom.'_'.$cnum;
                   7053:                     if (!exists($allroles{$cid})) {
                   7054:                         next;
                   7055:                     }    
                   7056:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7057:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7058:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7059:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7060:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7061:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7062:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7063:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7064:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7065:                                         if (grep/^all$/,@sections) {
                   7066:                                             return 'ok';
                   7067:                                         } else {
                   7068:                                             if (grep/^$sec$/,@sections) {
                   7069:                                                 return 'ok';
                   7070:                                             }
                   7071:                                         }
                   7072:                                     }
                   7073:                                 }
                   7074:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7075:                                     if (grep/^none$/,@groups) {
                   7076:                                         return 'ok';
                   7077:                                     }
                   7078:                                 } else {
                   7079:                                     if (grep/^all$/,@groups) {
                   7080:                                         return 'ok';
                   7081:                                     } 
                   7082:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7083:                                         if (grep/^$group$/,@groups) {
                   7084:                                             return 'ok';
                   7085:                                         }
                   7086:                                     }
                   7087:                                 } 
                   7088:                             }
                   7089:                         }
                   7090:                     }
                   7091:                 }
                   7092:             }
                   7093:             if ($guest) {
                   7094:                 return $guest;
                   7095:             }
                   7096:         }
                   7097:     }
                   7098:     return;
                   7099: }
                   7100: 
                   7101: sub course_group_datechecker {
                   7102:     my ($dates,$now,$status) = @_;
                   7103:     my ($start,$end) = split(/\./,$dates);
                   7104:     if (!$start && !$end) {
                   7105:         return 'ok';
                   7106:     }
                   7107:     if (grep/^active$/,@{$status}) {
                   7108:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7109:             return 'ok';
                   7110:         }
                   7111:     }
                   7112:     if (grep/^previous$/,@{$status}) {
                   7113:         if ($end > $now ) {
                   7114:             return 'ok';
                   7115:         }
                   7116:     }
                   7117:     if (grep/^future$/,@{$status}) {
                   7118:         if ($start > $now) {
                   7119:             return 'ok';
                   7120:         }
                   7121:     }
                   7122:     return; 
                   7123: }
                   7124: 
                   7125: sub parse_portfolio_url {
                   7126:     my ($url) = @_;
                   7127: 
                   7128:     my ($type,$udom,$unum,$group,$file_name);
                   7129:     
1.823     albertel 7130:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7131: 	$type = 1;
                   7132:         $udom = $1;
                   7133:         $unum = $2;
                   7134:         $file_name = $3;
1.823     albertel 7135:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7136: 	$type = 2;
                   7137:         $udom = $1;
                   7138:         $unum = $2;
                   7139:         $group = $3;
                   7140:         $file_name = $3.'/'.$4;
                   7141:     }
                   7142:     if (wantarray) {
                   7143: 	return ($type,$udom,$unum,$file_name,$group);
                   7144:     }
                   7145:     return $type;
                   7146: }
                   7147: 
                   7148: sub is_portfolio_url {
                   7149:     my ($url) = @_;
                   7150:     return scalar(&parse_portfolio_url($url));
                   7151: }
                   7152: 
1.798     raeburn  7153: sub is_portfolio_file {
                   7154:     my ($file) = @_;
1.820     raeburn  7155:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7156:         return 1;
                   7157:     }
                   7158:     return;
                   7159: }
                   7160: 
1.976     raeburn  7161: sub usertools_access {
1.1084    raeburn  7162:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7163:     my ($access,%tools);
                   7164:     if ($context eq '') {
                   7165:         $context = 'tools';
                   7166:     }
                   7167:     if ($context eq 'requestcourses') {
                   7168:         %tools = (
                   7169:                       official   => 1,
                   7170:                       unofficial => 1,
1.1006    raeburn  7171:                       community  => 1,
1.1246    raeburn  7172:                       textbook   => 1,
1.1305    raeburn  7173:                       placement  => 1,
1.1368    raeburn  7174:                       lti        => 1,
1.985     raeburn  7175:                  );
1.1183    raeburn  7176:     } elsif ($context eq 'requestauthor') {
                   7177:         %tools = (
                   7178:                       requestauthor => 1,
                   7179:                  );
1.985     raeburn  7180:     } else {
                   7181:         %tools = (
                   7182:                       aboutme   => 1,
                   7183:                       blog      => 1,
1.1177    raeburn  7184:                       webdav    => 1,
1.985     raeburn  7185:                       portfolio => 1,
                   7186:                  );
                   7187:     }
1.976     raeburn  7188:     return if (!defined($tools{$tool}));
                   7189: 
1.1242    raeburn  7190:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7191:         $udom = $env{'user.domain'};
                   7192:         $uname = $env{'user.name'};
                   7193:     }
                   7194: 
1.978     raeburn  7195:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7196:         if ($action ne 'reload') {
1.985     raeburn  7197:             if ($context eq 'requestcourses') {
                   7198:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7199:             } elsif ($context eq 'requestauthor') {
                   7200:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7201:             } else {
                   7202:                 return $env{'environment.availabletools.'.$tool};
                   7203:             }
                   7204:         }
1.976     raeburn  7205:     }
                   7206: 
1.1183    raeburn  7207:     my ($toolstatus,$inststatus,$envkey);
                   7208:     if ($context eq 'requestauthor') {
                   7209:         $envkey = $context; 
                   7210:     } else {
                   7211:         $envkey = $context.'.'.$tool;
                   7212:     }
1.976     raeburn  7213: 
1.985     raeburn  7214:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7215:          ($action ne 'reload')) {
1.1183    raeburn  7216:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7217:         $inststatus = $env{'environment.inststatus'};
                   7218:     } else {
1.1084    raeburn  7219:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7220:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7221:             $inststatus = $userenvref->{'inststatus'};
                   7222:         } else {
1.1183    raeburn  7223:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7224:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7225:             $inststatus = $userenv{'inststatus'};
                   7226:         }
1.976     raeburn  7227:     }
                   7228: 
                   7229:     if ($toolstatus ne '') {
                   7230:         if ($toolstatus) {
                   7231:             $access = 1;
                   7232:         } else {
                   7233:             $access = 0;
                   7234:         }
                   7235:         return $access;
                   7236:     }
                   7237: 
1.1084    raeburn  7238:     my ($is_adv,%domdef);
                   7239:     if (ref($is_advref) eq 'HASH') {
                   7240:         $is_adv = $is_advref->{'is_adv'};
                   7241:     } else {
                   7242:         $is_adv = &is_advanced_user($udom,$uname);
                   7243:     }
                   7244:     if (ref($domdefref) eq 'HASH') {
                   7245:         %domdef = %{$domdefref};
                   7246:     } else {
                   7247:         %domdef = &get_domain_defaults($udom);
                   7248:     }
1.976     raeburn  7249:     if (ref($domdef{$tool}) eq 'HASH') {
                   7250:         if ($is_adv) {
                   7251:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7252:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7253:                     $access = 1;
                   7254:                 } else {
                   7255:                     $access = 0;
                   7256:                 }
                   7257:                 return $access;
                   7258:             }
                   7259:         }
                   7260:         if ($inststatus ne '') {
                   7261:             my ($hasaccess,$hasnoaccess);
                   7262:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7263:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7264:                     if ($domdef{$tool}{$affiliation}) {
                   7265:                         $hasaccess = 1;
                   7266:                     } else {
                   7267:                         $hasnoaccess = 1;
                   7268:                     }
                   7269:                 }
                   7270:             }
                   7271:             if ($hasaccess || $hasnoaccess) {
                   7272:                 if ($hasaccess) {
                   7273:                     $access = 1;
                   7274:                 } elsif ($hasnoaccess) {
                   7275:                     $access = 0; 
                   7276:                 }
                   7277:                 return $access;
                   7278:             }
                   7279:         } else {
                   7280:             if ($domdef{$tool}{'default'} ne '') {
                   7281:                 if ($domdef{$tool}{'default'}) {
                   7282:                     $access = 1;
                   7283:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7284:                     $access = 0;
                   7285:                 }
                   7286:                 return $access;
                   7287:             }
                   7288:         }
                   7289:     } else {
1.1177    raeburn  7290:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7291:             $access = 1;
                   7292:         } else {
                   7293:             $access = 0;
                   7294:         }
1.976     raeburn  7295:         return $access;
                   7296:     }
                   7297: }
                   7298: 
1.1050    raeburn  7299: sub is_course_owner {
                   7300:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7301:     if (($udom eq '') || ($uname eq '')) {
                   7302:         $udom = $env{'user.domain'};
                   7303:         $uname = $env{'user.name'};
                   7304:     }
                   7305:     unless (($udom eq '') || ($uname eq '')) {
                   7306:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7307:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7308:                 return 1;
                   7309:             } else {
                   7310:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7311:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7312:                     return 1;
                   7313:                 }
                   7314:             }
                   7315:         }
                   7316:     }
                   7317:     return;
                   7318: }
                   7319: 
1.976     raeburn  7320: sub is_advanced_user {
                   7321:     my ($udom,$uname) = @_;
1.1085    raeburn  7322:     if ($udom ne '' && $uname ne '') {
                   7323:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7324:             if (wantarray) {
                   7325:                 return ($env{'user.adv'},$env{'user.author'});
                   7326:             } else {
                   7327:                 return $env{'user.adv'};
                   7328:             }
1.1085    raeburn  7329:         }
                   7330:     }
1.976     raeburn  7331:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7332:     my %allroles;
1.1128    raeburn  7333:     my ($is_adv,$is_author);
1.976     raeburn  7334:     foreach my $role (keys(%roleshash)) {
                   7335:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7336:         my $area = '/'.$tdomain.'/'.$trest;
                   7337:         if ($sec ne '') {
                   7338:             $area .= '/'.$sec;
                   7339:         }
                   7340:         if (($area ne '') && ($trole ne '')) {
                   7341:             my $spec=$trole.'.'.$area;
                   7342:             if ($trole =~ /^cr\//) {
                   7343:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7344:             } elsif ($trole ne 'gr') {
                   7345:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7346:             }
1.1128    raeburn  7347:             if ($trole eq 'au') {
                   7348:                 $is_author = 1;
                   7349:             }
1.976     raeburn  7350:         }
                   7351:     }
                   7352:     foreach my $role (keys(%allroles)) {
                   7353:         last if ($is_adv);
                   7354:         foreach my $item (split(/:/,$allroles{$role})) {
                   7355:             if ($item ne '') {
                   7356:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7357:                 if ($privilege eq 'adv') {
                   7358:                     $is_adv = 1;
                   7359:                     last;
                   7360:                 }
                   7361:             }
                   7362:         }
                   7363:     }
1.1128    raeburn  7364:     if (wantarray) {
                   7365:         return ($is_adv,$is_author);
                   7366:     }
1.976     raeburn  7367:     return $is_adv;
                   7368: }
1.798     raeburn  7369: 
1.1035    raeburn  7370: sub check_can_request {
1.1368    raeburn  7371:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7372:     my $canreq = 0;
1.1368    raeburn  7373:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7374:         $uname = $env{'user.name'};
                   7375:         $udom = $env{'user.domain'};
                   7376:     }
1.1035    raeburn  7377:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7378:     my @options = ('approval','validate','autolimit');
                   7379:     my $optregex = join('|',@options);
                   7380:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7381:         foreach my $type (@{$types}) {
1.1368    raeburn  7382:             if (&usertools_access($uname,$udom,$type,undef,
                   7383:                                   'requestcourses')) {
1.1035    raeburn  7384:                 $canreq ++;
1.1036    raeburn  7385:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7386:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7387:                 }
1.1368    raeburn  7388:                 if ($dom eq $udom) {
1.1035    raeburn  7389:                     $can_request->{$type} = 1;
                   7390:                 }
                   7391:             }
1.1368    raeburn  7392:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7393:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7394:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7395:                 if (@curr > 0) {
1.1036    raeburn  7396:                     foreach my $item (@curr) {
                   7397:                         if (ref($request_domains) eq 'HASH') {
                   7398:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7399:                             if ($otherdom ne '') {
                   7400:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7401:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7402:                                         push(@{$request_domains->{$type}},$otherdom);
                   7403:                                     }
                   7404:                                 } else {
                   7405:                                     push(@{$request_domains->{$type}},$otherdom);
                   7406:                                 }
                   7407:                             }
                   7408:                         }
                   7409:                     }
1.1368    raeburn  7410:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7411:                         $canreq ++;
1.1035    raeburn  7412:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7413:                             $can_request->{$type} = 1;
                   7414:                         }
                   7415:                     }
                   7416:                 }
                   7417:             }
                   7418:         }
                   7419:     }
                   7420:     return $canreq;
                   7421: }
                   7422: 
1.341     www      7423: # ---------------------------------------------- Custom access rule evaluation
                   7424: 
                   7425: sub customaccess {
                   7426:     my ($priv,$uri)=@_;
1.807     albertel 7427:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7428:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7429:     $udom = &LONCAPA::clean_domain($udom);
                   7430:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7431:     my $access=0;
1.800     albertel 7432:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7433: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7434: 	if ($type eq 'user') {
                   7435: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7436: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7437: 		if ($tdom) {
                   7438: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7439: 		}
1.896     albertel 7440: 		if ($tuname) {
                   7441: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7442: 		}
                   7443: 		$access=($effect eq 'allow');
                   7444: 		last;
                   7445: 	    }
                   7446: 	} else {
                   7447: 	    if ($role) {
                   7448: 		if ($role ne $urole) { next; }
                   7449: 	    }
                   7450: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7451: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7452: 		if ($tdom) {
                   7453: 		    if ($tdom ne $udom) { next; }
                   7454: 		}
                   7455: 		if ($tcrs) {
                   7456: 		    if ($tcrs ne $ucrs) { next; }
                   7457: 		}
                   7458: 		if ($tsec) {
                   7459: 		    if ($tsec ne $usec) { next; }
                   7460: 		}
                   7461: 		$access=($effect eq 'allow');
                   7462: 		last;
                   7463: 	    }
                   7464: 	    if ($realm eq '' && $role eq '') {
                   7465: 		$access=($effect eq 'allow');
                   7466: 	    }
1.402     bowersj2 7467: 	}
1.341     www      7468:     }
                   7469:     return $access;
                   7470: }
                   7471: 
1.103     harris41 7472: # ------------------------------------------------- Check for a user privilege
1.12      www      7473: 
                   7474: sub allowed {
1.1281    raeburn  7475:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7476:     my $ver_orguri=$uri;
1.439     www      7477:     $uri=&deversion($uri);
1.152     www      7478:     my $orguri=$uri;
1.52      www      7479:     $uri=&declutter($uri);
1.809     raeburn  7480: 
1.810     raeburn  7481:     if ($priv eq 'evb') {
                   7482: # Evade communication block restrictions for specified role in a course
                   7483:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7484:             return $1;
                   7485:         } else {
                   7486:             return;
                   7487:         }
                   7488:     }
                   7489: 
1.620     albertel 7490:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7491: # Free bre access to adm and meta resources
1.1343    raeburn  7492:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7493: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7494: 	&& ($priv eq 'bre')) {
1.14      www      7495: 	return 'F';
1.159     www      7496:     }
                   7497: 
1.545     banghart 7498: # Free bre access to user's own portfolio contents
1.714     raeburn  7499:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7500:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7501: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7502:         my %setters;
                   7503:         my ($startblock,$endblock) = 
                   7504:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7505:         if ($startblock && $endblock) {
                   7506:             return 'B';
                   7507:         } else {
                   7508:             return 'F';
                   7509:         }
1.545     banghart 7510:     }
                   7511: 
1.762     raeburn  7512: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7513:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7514:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7515:         if (exists($env{'request.course.id'})) {
                   7516:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7517:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7518:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7519:                 my $courseprivid=$env{'request.course.id'};
                   7520:                 $courseprivid=~s/\_/\//;
                   7521:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7522:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7523:                     return $1; 
1.762     raeburn  7524:                 } else {
                   7525:                     if ($env{'request.course.sec'}) {
                   7526:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7527:                     }
                   7528:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7529:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7530:                         return $2;
                   7531:                     }
1.714     raeburn  7532:                 }
                   7533:             }
                   7534:         }
                   7535:     }
                   7536: 
1.159     www      7537: # Free bre to public access
                   7538: 
                   7539:     if ($priv eq 'bre') {
1.1362    raeburn  7540:         my $copyright;
                   7541:         unless ($uri =~ /ext\.tool/) {
                   7542:             $copyright=&metadata($uri,'copyright');
                   7543:         }
1.620     albertel 7544: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7545:            return 'F'; 
                   7546:         }
1.238     www      7547:         if ($copyright eq 'priv') {
                   7548:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7549: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7550: 		return '';
                   7551:             }
                   7552:         }
                   7553:         if ($copyright eq 'domain') {
                   7554:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7555: 	    unless (($env{'user.domain'} eq $1) ||
                   7556:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7557: 		return '';
                   7558:             }
1.262     matthew  7559:         }
1.620     albertel 7560:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7561:             # Library role, so allow browsing of resources in this domain.
                   7562:             return 'F';
1.238     www      7563:         }
1.341     www      7564:         if ($copyright eq 'custom') {
                   7565: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7566:         }
1.14      www      7567:     }
1.264     matthew  7568:     # Domain coordinator is trying to create a course
1.620     albertel 7569:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7570:         # uri is the requested domain in this case.
                   7571:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7572:         # a role of dc for the domain in question.
1.620     albertel 7573:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7574:     }
1.29      www      7575: 
1.52      www      7576:     my $thisallowed='';
                   7577:     my $statecond=0;
                   7578:     my $courseprivid='';
                   7579: 
1.1039    raeburn  7580:     my $ownaccess;
1.1043    raeburn  7581:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7582:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7583:         if ($uri eq '') {
                   7584:             $ownaccess = 1;
                   7585:         } else {
                   7586:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7587:                 my $udom = $env{'user.domain'};
                   7588:                 my $uname = $env{'user.name'};
                   7589:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7590:                     $ownaccess = 1;
1.1040    raeburn  7591:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7592:                     unless ($uri =~ m{\.\./}) {
                   7593:                         $ownaccess = 1;
                   7594:                     }
                   7595:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7596:                     my $now = time;
                   7597:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7598:                         my $adom = $1;
                   7599:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7600:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7601:                                 my ($start,$end) = split('.',$env{$key});
                   7602:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7603:                                     $ownaccess = 1;
                   7604:                                     last;
                   7605:                                 }
                   7606:                             }
                   7607:                         }
                   7608:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7609:                         my $adom = $1;
                   7610:                         my $aname = $2;
1.1042    raeburn  7611:                         foreach my $role ('ca','aa') { 
                   7612:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7613:                                 my ($start,$end) =
                   7614:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7615:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7616:                                     $ownaccess = 1;
                   7617:                                     last;
                   7618:                                 }
1.1039    raeburn  7619:                             }
                   7620:                         }
                   7621:                     }
                   7622:                 }
                   7623:             }
                   7624:         }
                   7625:     }
                   7626: 
1.52      www      7627: # Course
                   7628: 
1.620     albertel 7629:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7630:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7631:             $thisallowed.=$1;
                   7632:         }
1.52      www      7633:     }
1.29      www      7634: 
1.52      www      7635: # Domain
                   7636: 
1.620     albertel 7637:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7638:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7639:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7640:             $thisallowed.=$1;
                   7641:         }
1.12      www      7642:     }
1.52      www      7643: 
1.1141    raeburn  7644: # User who is not author or co-author might still be able to edit
                   7645: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7646:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7647:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7648:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7649:             $thisallowed.=$1;
                   7650:         }
                   7651:     }
                   7652: 
1.52      www      7653: # Course: uri itself is a course
1.66      www      7654:     my $courseuri=$uri;
                   7655:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7656:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7657: 
1.620     albertel 7658:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7659:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7660:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7661:             $thisallowed.=$1;
                   7662:         }
1.12      www      7663:     }
1.29      www      7664: 
1.665     albertel 7665: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7666: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7667:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7668: 	$thisallowed='';
1.671     raeburn  7669:         my ($match)=&is_on_map($uri);
                   7670:         if ($match) {
                   7671:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7672:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7673:                 my $value = $1;
                   7674:                 if ($noblockcheck) {
                   7675:                     $thisallowed.=$value;
1.1162    raeburn  7676:                 } else {
1.1281    raeburn  7677:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7678:                     if (@blockers > 0) {
                   7679:                         $thisallowed = 'B';
                   7680:                     } else {
                   7681:                         $thisallowed.=$value;
                   7682:                     }
1.1162    raeburn  7683:                 }
1.671     raeburn  7684:             }
                   7685:         } else {
1.705     albertel 7686:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7687:             if ($refuri) {
                   7688:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7689:                     $thisallowed='F';
1.671     raeburn  7690:                 } else {
                   7691:                     $refuri=&declutter($refuri);
                   7692:                     my ($match) = &is_on_map($refuri);
                   7693:                     if ($match) {
1.1281    raeburn  7694:                         if ($noblockcheck) {
                   7695:                             $thisallowed='F';
1.1162    raeburn  7696:                         } else {
1.1281    raeburn  7697:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7698:                             if (@blockers > 0) {
                   7699:                                 $thisallowed = 'B';
                   7700:                             } else {
                   7701:                                 $thisallowed='F';
                   7702:                             }
1.1162    raeburn  7703:                         }
1.671     raeburn  7704:                     }
1.669     raeburn  7705:                 }
1.671     raeburn  7706:             }
                   7707:         }
1.314     www      7708:     }
1.492     albertel 7709: 
1.766     albertel 7710:     if ($priv eq 'bre'
                   7711: 	&& $thisallowed ne 'F' 
                   7712: 	&& $thisallowed ne '2'
                   7713: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7714: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7715:     }
1.1250    raeburn  7716: 
1.52      www      7717: # Full access at system, domain or course-wide level? Exit.
1.29      www      7718:     if ($thisallowed=~/F/) {
                   7719: 	return 'F';
                   7720:     }
                   7721: 
1.52      www      7722: # If this is generating or modifying users, exit with special codes
1.29      www      7723: 
1.643     www      7724:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7725: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7726: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7727: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7728: 	    unless ($auname) { return $thisallowed; }
                   7729: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7730: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7731: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7732: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7733: 	}
1.52      www      7734: 	return $thisallowed;
                   7735:     }
                   7736: #
1.103     harris41 7737: # Gathered so far: system, domain and course wide privileges
1.52      www      7738: #
                   7739: # Course: See if uri or referer is an individual resource that is part of 
                   7740: # the course
                   7741: 
1.620     albertel 7742:     if ($env{'request.course.id'}) {
1.232     www      7743: 
1.620     albertel 7744:        $courseprivid=$env{'request.course.id'};
                   7745:        if ($env{'request.course.sec'}) {
                   7746:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7747:        }
                   7748:        $courseprivid=~s/\_/\//;
                   7749:        my $checkreferer=1;
1.232     www      7750:        my ($match,$cond)=&is_on_map($uri);
                   7751:        if ($match) {
                   7752:            $statecond=$cond;
1.620     albertel 7753:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7754:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7755:                my $value = $1;
                   7756:                if ($priv eq 'bre') {
1.1281    raeburn  7757:                    if ($noblockcheck) {
                   7758:                        $thisallowed.=$value;
1.1162    raeburn  7759:                    } else {
1.1281    raeburn  7760:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7761:                        if (@blockers > 0) {
                   7762:                            $thisallowed = 'B';
                   7763:                        } else {
                   7764:                            $thisallowed.=$value;
                   7765:                        }
1.1162    raeburn  7766:                    }
                   7767:                } else {
                   7768:                    $thisallowed.=$value;
                   7769:                }
1.52      www      7770:                $checkreferer=0;
                   7771:            }
1.29      www      7772:        }
1.83      www      7773:        
1.148     www      7774:        if ($checkreferer) {
1.620     albertel 7775: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7776:             unless ($refuri) {
1.800     albertel 7777:                 foreach my $key (keys(%env)) {
                   7778: 		    if ($key=~/^httpref\..*\*/) {
                   7779: 			my $pattern=$key;
1.156     www      7780:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7781:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7782:                         $pattern=~s/\//\\\//g;
1.152     www      7783:                         if ($orguri=~/$pattern/) {
1.800     albertel 7784: 			    $refuri=$env{$key};
1.148     www      7785:                         }
                   7786:                     }
1.191     harris41 7787:                 }
1.148     www      7788:             }
1.232     www      7789: 
1.148     www      7790:          if ($refuri) { 
1.152     www      7791: 	  $refuri=&declutter($refuri);
1.232     www      7792:           my ($match,$cond)=&is_on_map($refuri);
                   7793:             if ($match) {
                   7794:               my $refstatecond=$cond;
1.620     albertel 7795:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7796:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7797:                   my $value = $1;
                   7798:                   if ($priv eq 'bre') {
1.1281    raeburn  7799:                       if ($noblockcheck) {
                   7800:                           $thisallowed.=$value;
1.1162    raeburn  7801:                       } else {
1.1281    raeburn  7802:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7803:                           if (@blockers > 0) {
                   7804:                               $thisallowed = 'B';
                   7805:                           } else {
                   7806:                               $thisallowed.=$value;
                   7807:                           }
1.1162    raeburn  7808:                       }
                   7809:                   } else {
                   7810:                       $thisallowed.=$value;
                   7811:                   }
1.53      www      7812:                   $uri=$refuri;
                   7813:                   $statecond=$refstatecond;
1.52      www      7814:               }
                   7815:           }
1.148     www      7816:         }
1.29      www      7817:        }
1.52      www      7818:    }
1.29      www      7819: 
1.52      www      7820: #
1.103     harris41 7821: # Gathered now: all privileges that could apply, and condition number
1.52      www      7822: # 
                   7823: #
                   7824: # Full or no access?
                   7825: #
1.29      www      7826: 
1.52      www      7827:     if ($thisallowed=~/F/) {
                   7828: 	return 'F';
                   7829:     }
1.29      www      7830: 
1.52      www      7831:     unless ($thisallowed) {
                   7832:         return '';
                   7833:     }
1.29      www      7834: 
1.52      www      7835: # Restrictions exist, deal with them
                   7836: #
                   7837: #   C:according to course preferences
                   7838: #   R:according to resource settings
                   7839: #   L:unless locked
                   7840: #   X:according to user session state
                   7841: #
                   7842: 
                   7843: # Possibly locked functionality, check all courses
1.54      www      7844: # Locks might take effect only after 10 minutes cache expiration for other
                   7845: # courses, and 2 minutes for current course
1.52      www      7846: 
                   7847:     my $envkey;
                   7848:     if ($thisallowed=~/L/) {
1.1000    raeburn  7849:         foreach $envkey (keys(%env)) {
1.54      www      7850:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7851:                my $courseid=$2;
                   7852:                my $roleid=$1.'.'.$2;
1.92      www      7853:                $courseid=~s/^\///;
1.54      www      7854:                my $expiretime=600;
1.620     albertel 7855:                if ($env{'request.role'} eq $roleid) {
1.54      www      7856: 		  $expiretime=120;
                   7857:                }
                   7858: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7859:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7860:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7861: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7862:                }
1.620     albertel 7863:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7864:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7865: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7866:                        &log($env{'user.domain'},$env{'user.name'},
                   7867:                             $env{'user.home'},
1.57      www      7868:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7869:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7870:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7871: 		       return '';
                   7872:                    }
                   7873:                }
1.620     albertel 7874:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7875:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7876: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7877:                        &log($env{'user.domain'},$env{'user.name'},
                   7878:                             $env{'user.home'},
1.57      www      7879:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7880:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7881:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7882: 		       return '';
                   7883:                    }
                   7884:                }
                   7885: 	   }
1.29      www      7886:        }
1.52      www      7887:     }
                   7888:    
                   7889: #
                   7890: # Rest of the restrictions depend on selected course
                   7891: #
                   7892: 
1.620     albertel 7893:     unless ($env{'request.course.id'}) {
1.766     albertel 7894: 	if ($thisallowed eq 'A') {
                   7895: 	    return 'A';
1.814     raeburn  7896:         } elsif ($thisallowed eq 'B') {
                   7897:             return 'B';
1.766     albertel 7898: 	} else {
                   7899: 	    return '1';
                   7900: 	}
1.52      www      7901:     }
1.29      www      7902: 
1.52      www      7903: #
                   7904: # Now user is definitely in a course
                   7905: #
1.53      www      7906: 
                   7907: 
                   7908: # Course preferences
                   7909: 
                   7910:    if ($thisallowed=~/C/) {
1.620     albertel 7911:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7912:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7913:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7914: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7915: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7916: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7917: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7918: 			$env{'request.course.id'});
                   7919: 	   }
1.237     www      7920:            return '';
                   7921:        }
                   7922: 
1.620     albertel 7923:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7924: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7925: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7926: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7927: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7928: 			$env{'request.course.id'});
                   7929: 	   }
1.54      www      7930:            return '';
                   7931:        }
1.53      www      7932:    }
                   7933: 
                   7934: # Resource preferences
                   7935: 
                   7936:    if ($thisallowed=~/R/) {
1.620     albertel 7937:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7938:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7939: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7940: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7941: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7942: 	   }
                   7943: 	   return '';
1.54      www      7944:        }
1.53      www      7945:    }
1.30      www      7946: 
1.246     www      7947: # Restricted by state or randomout?
1.30      www      7948: 
1.52      www      7949:    if ($thisallowed=~/X/) {
1.620     albertel 7950:       if ($env{'acc.randomout'}) {
1.579     albertel 7951: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7952:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7953:             return ''; 
                   7954:          }
1.247     www      7955:       }
                   7956:       if (&condval($statecond)) {
1.52      www      7957: 	 return '2';
                   7958:       } else {
                   7959:          return '';
                   7960:       }
                   7961:    }
1.30      www      7962: 
1.766     albertel 7963:     if ($thisallowed eq 'A') {
                   7964: 	return 'A';
1.814     raeburn  7965:     } elsif ($thisallowed eq 'B') {
                   7966:         return 'B';
1.766     albertel 7967:     }
1.52      www      7968:    return 'F';
1.232     www      7969: }
1.1162    raeburn  7970: 
1.1192    raeburn  7971: # ------------------------------------------- Check construction space access
                   7972: 
                   7973: sub constructaccess {
                   7974:     my ($url,$setpriv)=@_;
                   7975: 
                   7976: # We do not allow editing of previous versions of files
                   7977:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7978: 
                   7979: # Get username and domain from URL
                   7980:     my ($ownername,$ownerdomain,$ownerhome);
                   7981: 
                   7982:     ($ownerdomain,$ownername) =
1.1325    raeburn  7983:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7984: 
                   7985: # The URL does not really point to any authorspace, forget it
                   7986:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7987: 
                   7988: # Now we need to see if the user has access to the authorspace of
                   7989: # $ownername at $ownerdomain
                   7990: 
                   7991:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7992: # Real author for this?
                   7993:        $ownerhome = $env{'user.home'};
                   7994:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7995:           return ($ownername,$ownerdomain,$ownerhome);
                   7996:        }
                   7997:     } else {
                   7998: # Co-author for this?
                   7999:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8000:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8001:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8002:             return ($ownername,$ownerdomain,$ownerhome);
                   8003:         }
1.1312    raeburn  8004:         if ($env{'request.course.id'}) {
                   8005:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8006:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8007:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8008:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8009:                     return ($ownername,$ownerdomain,$ownerhome);
                   8010:                 }
                   8011:             }
                   8012:         }
1.1192    raeburn  8013:     }
                   8014: 
                   8015: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8016: # we might as well leave
                   8017:    unless ($setpriv) { return ''; }
                   8018: 
                   8019: # Backdoor access?
                   8020:     my $allowed=&allowed('eco',$ownerdomain);
                   8021: # Nope
                   8022:     unless ($allowed) { return ''; }
                   8023: # Looks like we may have access, but could be locked by the owner of the construction space
                   8024:     if ($allowed eq 'U') {
                   8025:         my %blocked=&get('environment',['domcoord.author'],
                   8026:                          $ownerdomain,$ownername);
                   8027: # Is blocked by owner
                   8028:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8029:     }
                   8030:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8031: # Grant temporary access
                   8032:         my $then=$env{'user.login.time'};
1.1209    raeburn  8033:         my $update=$env{'user.update.time'};
1.1192    raeburn  8034:         if (!$update) { $update = $then; }
                   8035:         my $refresh=$env{'user.refresh.time'};
                   8036:         if (!$refresh) { $refresh = $update; }
                   8037:         my $now = time;
                   8038:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8039:                            $now,'ca','constructaccess');
                   8040:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8041:         return($ownername,$ownerdomain,$ownerhome);
                   8042:     }
                   8043: # No business here
                   8044:     return '';
                   8045: }
                   8046: 
1.1282    raeburn  8047: # ----------------------------------------------------------- Content Blocking
                   8048: 
                   8049: {
                   8050: # Caches for faster Course Contents display where content blocking
                   8051: # is in operation (i.e., interval param set) for timed quiz.
                   8052: #
                   8053: # User for whom data are being temporarily cached.
                   8054: my $cacheduser='';
                   8055: # Cached blockers for this user (a hash of blocking items). 
                   8056: my %cachedblockers=();
                   8057: # When the data were last cached.
                   8058: my $cachedlast='';
                   8059: 
                   8060: sub load_all_blockers {
                   8061:     my ($uname,$udom,$blocks)=@_;
                   8062:     if (($uname ne '') && ($udom ne '')) { 
                   8063:         if (($cacheduser eq $uname.':'.$udom) &&
                   8064:             (abs($cachedlast-time)<5)) {
                   8065:             return;
                   8066:         }
                   8067:     }
                   8068:     $cachedlast=time;
                   8069:     $cacheduser=$uname.':'.$udom;
                   8070:     %cachedblockers = &get_commblock_resources($blocks);
                   8071: }
                   8072: 
1.1162    raeburn  8073: sub get_comm_blocks {
                   8074:     my ($cdom,$cnum) = @_;
                   8075:     if ($cdom eq '' || $cnum eq '') {
                   8076:         return unless ($env{'request.course.id'});
                   8077:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8078:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8079:     }
                   8080:     my %commblocks;
                   8081:     my $hashid=$cdom.'_'.$cnum;
                   8082:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8083:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8084:         %commblocks = %{$blocksref};
                   8085:     } else {
                   8086:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8087:         my $cachetime = 600;
                   8088:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8089:     }
                   8090:     return %commblocks;
                   8091: }
                   8092: 
1.1282    raeburn  8093: sub get_commblock_resources {
                   8094:     my ($blocks) = @_;
                   8095:     my %blockers = ();
                   8096:     return %blockers unless ($env{'request.course.id'});
                   8097:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8098:     my %commblocks;
                   8099:     if (ref($blocks) eq 'HASH') {
                   8100:         %commblocks = %{$blocks};
                   8101:     } else {
                   8102:         %commblocks = &get_comm_blocks();
                   8103:     }
1.1282    raeburn  8104:     return %blockers unless (keys(%commblocks) > 0); 
                   8105:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8106:     return %blockers unless (ref($navmap));
1.1162    raeburn  8107:     my $now = time;
                   8108:     foreach my $block (keys(%commblocks)) {
                   8109:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8110:             my ($start,$end) = ($1,$2);
                   8111:             if ($start <= $now && $end >= $now) {
                   8112:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8113:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8114:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8115:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8116:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8117:                             }
                   8118:                         }
                   8119:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8120:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8121:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8122:                             }
                   8123:                         }
                   8124:                     }
                   8125:                 }
                   8126:             }
                   8127:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8128:             my $item = $1;
1.1163    raeburn  8129:             my @to_test;
1.1162    raeburn  8130:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8131:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8132:                     my @interval;
                   8133:                     my $type = 'map';
                   8134:                     if ($item eq 'course') {
                   8135:                         $type = 'course';
                   8136:                         @interval=&EXT("resource.0.interval");
                   8137:                     } else {
                   8138:                         if ($item =~ /___\d+___/) {
                   8139:                             $type = 'resource';
                   8140:                             @interval=&EXT("resource.0.interval",$item);
                   8141:                             if (ref($navmap)) {                        
                   8142:                                 my $res = $navmap->getBySymb($item); 
                   8143:                                 push(@to_test,$res);
                   8144:                             }
1.1162    raeburn  8145:                         } else {
1.1282    raeburn  8146:                             my $mapsymb = &symbread($item,1);
                   8147:                             if ($mapsymb) {
                   8148:                                 if (ref($navmap)) {
                   8149:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8150:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8151:                                     foreach my $res (@to_test) {
                   8152:                                         my $symb = $res->symb();
                   8153:                                         next if ($symb eq $mapsymb);
                   8154:                                         if ($symb ne '') {
                   8155:                                             @interval=&EXT("resource.0.interval",$symb);
                   8156:                                             if ($interval[1] eq 'map') {
                   8157:                                                 last;
1.1162    raeburn  8158:                                             }
                   8159:                                         }
                   8160:                                     }
                   8161:                                 }
                   8162:                             }
                   8163:                         }
1.1282    raeburn  8164:                     }
1.1310    raeburn  8165:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8166:                         my $timelimit = $1; 
1.1282    raeburn  8167:                         my $first_access;
                   8168:                         if ($type eq 'resource') {
                   8169:                             $first_access=&get_first_access($interval[1],$item);
                   8170:                         } elsif ($type eq 'map') {
                   8171:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8172:                         } else {
                   8173:                             $first_access=&get_first_access($interval[1]);
                   8174:                         }
                   8175:                         if ($first_access) {
1.1292    raeburn  8176:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8177:                             if ($timesup > $now) {
                   8178:                                 my $activeblock;
                   8179:                                 foreach my $res (@to_test) {
1.1283    raeburn  8180:                                     if ($res->answerable()) {
1.1282    raeburn  8181:                                         $activeblock = 1;
                   8182:                                         last;
                   8183:                                     }
                   8184:                                 }
                   8185:                                 if ($activeblock) {
                   8186:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8187:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8188:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8189:                                          }
                   8190:                                     }
                   8191:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8192:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8193:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8194:                                         }
1.1162    raeburn  8195:                                     }
                   8196:                                 }
                   8197:                             }
                   8198:                         }
                   8199:                     }
                   8200:                 }
                   8201:             }
                   8202:         }
                   8203:     }
1.1282    raeburn  8204:     return %blockers;
1.1162    raeburn  8205: }
                   8206: 
1.1282    raeburn  8207: sub has_comm_blocking {
                   8208:     my ($priv,$symb,$uri,$blocks) = @_;
                   8209:     my @blockers;
                   8210:     return unless ($env{'request.course.id'});
                   8211:     return unless ($priv eq 'bre');
                   8212:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8213:     return if ($env{'request.state'} eq 'construct');
                   8214:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8215:     return unless (keys(%cachedblockers) > 0);
                   8216:     my (%possibles,@symbs);
                   8217:     if (!$symb) {
                   8218:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8219:     }
1.1282    raeburn  8220:     if ($symb) {
                   8221:         @symbs = ($symb);
                   8222:     } elsif (keys(%possibles)) { 
                   8223:         @symbs = keys(%possibles);
                   8224:     }
                   8225:     my $noblock;
                   8226:     foreach my $symb (@symbs) {
                   8227:         last if ($noblock);
                   8228:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8229:         foreach my $block (keys(%cachedblockers)) {
                   8230:             if ($block =~ /^firstaccess____(.+)$/) {
                   8231:                 my $item = $1;
                   8232:                 if (($item eq $map) || ($item eq $symb)) {
                   8233:                     $noblock = 1;
                   8234:                     last;
                   8235:                 }
                   8236:             }
                   8237:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8238:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8239:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8240:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8241:                             push(@blockers,$block);
                   8242:                         }
                   8243:                     }
                   8244:                 }
1.1162    raeburn  8245:             }
1.1282    raeburn  8246:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8247:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8248:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8249:                         push(@blockers,$block);
                   8250:                     }
                   8251:                 }
1.1162    raeburn  8252:             }
                   8253:         }
                   8254:     }
1.1282    raeburn  8255:     return if ($noblock);
                   8256:     return @blockers;
                   8257: }
1.1162    raeburn  8258: }
                   8259: 
1.1282    raeburn  8260: # -------------------------------- Deversion and split uri into path an filename   
                   8261: 
1.1133    foxr     8262: #
1.1282    raeburn  8263: #   Removes the version from a URI and
1.1133    foxr     8264: #   splits it in to its filename and path to the filename.
                   8265: #   Seems like File::Basename could have done this more clearly.
                   8266: #   Parameters:
                   8267: #      $uri   - input URI
                   8268: #   Returns:
                   8269: #     Two element list consisting of 
                   8270: #     $pathname  - the URI up to and excluding the trailing /
                   8271: #     $filename  - The part of the URI following the last /
                   8272: #  NOTE:
                   8273: #    Another realization of this is simply:
                   8274: #    use File::Basename;
                   8275: #    ...
                   8276: #    $uri = shift;
                   8277: #    $filename = basename($uri);
                   8278: #    $path     = dirname($uri);
                   8279: #    return ($filename, $path);
                   8280: #
                   8281: #     The implementation below is probably faster however.
                   8282: #
1.710     albertel 8283: sub split_uri_for_cond {
                   8284:     my $uri=&deversion(&declutter(shift));
                   8285:     my @uriparts=split(/\//,$uri);
                   8286:     my $filename=pop(@uriparts);
                   8287:     my $pathname=join('/',@uriparts);
                   8288:     return ($pathname,$filename);
                   8289: }
1.232     www      8290: # --------------------------------------------------- Is a resource on the map?
                   8291: 
                   8292: sub is_on_map {
1.710     albertel 8293:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8294:     #Trying to find the conditional for the file
1.620     albertel 8295:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8296: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8297:     if ($match) {
1.289     bowersj2 8298: 	return (1,$1);
                   8299:     } else {
1.434     www      8300: 	return (0,0);
1.289     bowersj2 8301:     }
1.12      www      8302: }
                   8303: 
1.427     www      8304: # --------------------------------------------------------- Get symb from alias
                   8305: 
                   8306: sub get_symb_from_alias {
                   8307:     my $symb=shift;
                   8308:     my ($map,$resid,$url)=&decode_symb($symb);
                   8309: # Already is a symb
                   8310:     if ($url) { return $symb; }
                   8311: # Must be an alias
                   8312:     my $aliassymb='';
                   8313:     my %bighash;
1.620     albertel 8314:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8315:                             &GDBM_READER(),0640)) {
                   8316:         my $rid=$bighash{'mapalias_'.$symb};
                   8317: 	if ($rid) {
                   8318: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8319: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8320: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8321: 	}
                   8322:         untie %bighash;
                   8323:     }
                   8324:     return $aliassymb;
                   8325: }
                   8326: 
1.12      www      8327: # ----------------------------------------------------------------- Define Role
                   8328: 
                   8329: sub definerole {
                   8330:   if (allowed('mcr','/')) {
1.1326    raeburn  8331:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8332:     foreach my $role (split(':',$sysrole)) {
                   8333: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8334:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8335:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8336: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8337:                return "refused:s:$crole&$cqual"; 
                   8338:             }
                   8339:         }
1.191     harris41 8340:     }
1.800     albertel 8341:     foreach my $role (split(':',$domrole)) {
                   8342: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8343:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8344:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8345: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8346:                return "refused:d:$crole&$cqual"; 
                   8347:             }
                   8348:         }
1.191     harris41 8349:     }
1.800     albertel 8350:     foreach my $role (split(':',$courole)) {
                   8351: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8352:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8353:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8354: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8355:                return "refused:c:$crole&$cqual"; 
                   8356:             }
                   8357:         }
1.191     harris41 8358:     }
1.1326    raeburn  8359:     my $uhome;
                   8360:     if (($uname ne '') && ($udom ne '')) {
                   8361:         $uhome = &homeserver($uname,$udom);
                   8362:         return $uhome if ($uhome eq 'no_host');
                   8363:     } else {
                   8364:         $uname = $env{'user.name'};
                   8365:         $udom = $env{'user.domain'};
                   8366:         $uhome = $env{'user.home'};
                   8367:     }
1.620     albertel 8368:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8369:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8370:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8371:     return reply($command,$uhome);
1.12      www      8372:   } else {
                   8373:     return 'refused';
                   8374:   }
1.105     harris41 8375: }
                   8376: 
                   8377: # ---------------- Make a metadata query against the network of library servers
                   8378: 
                   8379: sub metadata_query {
1.1237    raeburn  8380:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8381:     my %rhash;
1.845     albertel 8382:     my %libserv = &all_library();
1.244     matthew  8383:     my @server_list = (defined($server_array) ? @$server_array
                   8384:                                               : keys(%libserv) );
                   8385:     for my $server (@server_list) {
1.1237    raeburn  8386:         my $domains = ''; 
                   8387:         if (ref($domains_hash) eq 'HASH') {
                   8388:             $domains = $domains_hash->{$server}; 
                   8389:         }
1.118     harris41 8390: 	unless ($custom or $customshow) {
1.1237    raeburn  8391: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8392: 	    $rhash{$server}=$reply;
                   8393: 	}
                   8394: 	else {
                   8395: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8396: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8397: 			     $server);
                   8398: 	    $rhash{$server}=$reply;
                   8399: 	}
1.112     harris41 8400:     }
1.118     harris41 8401:     return \%rhash;
1.240     www      8402: }
                   8403: 
                   8404: # ----------------------------------------- Send log queries and wait for reply
                   8405: 
                   8406: sub log_query {
                   8407:     my ($uname,$udom,$query,%filters)=@_;
                   8408:     my $uhome=&homeserver($uname,$udom);
                   8409:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8410:     my $uhost=&hostname($uhome);
1.800     albertel 8411:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8412:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8413:                        $uhome);
1.479     albertel 8414:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8415:     return get_query_reply($queryid);
                   8416: }
                   8417: 
1.818     raeburn  8418: # -------------------------- Update MySQL table for portfolio file
                   8419: 
                   8420: sub update_portfolio_table {
1.821     raeburn  8421:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8422:     if ($group ne '') {
                   8423:         $file_name =~s /^\Q$group\E//;
                   8424:     }
1.818     raeburn  8425:     my $homeserver = &homeserver($uname,$udom);
                   8426:     my $queryid=
1.821     raeburn  8427:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8428:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8429:     my $reply = &get_query_reply($queryid);
                   8430:     return $reply;
                   8431: }
                   8432: 
1.899     raeburn  8433: # -------------------------- Update MySQL allusers table
                   8434: 
                   8435: sub update_allusers_table {
                   8436:     my ($uname,$udom,$names) = @_;
                   8437:     my $homeserver = &homeserver($uname,$udom);
                   8438:     my $queryid=
                   8439:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8440:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8441:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8442:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8443:                'generation='.&escape($names->{'generation'}).'%%'.
                   8444:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8445:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8446:     return;
1.899     raeburn  8447: }
                   8448: 
1.508     raeburn  8449: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8450: 
                   8451: sub fetch_enrollment_query {
1.511     raeburn  8452:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8453:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8454:     my $maxtries = 1;
1.508     raeburn  8455:     if ($context eq 'automated') {
                   8456:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8457:         $sleep = 2;
                   8458:         $loopmax = 100;
1.547     raeburn  8459:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8460:     } else {
                   8461:         $homeserver = &homeserver($cnum,$dom);
                   8462:     }
1.838     albertel 8463:     my $host=&hostname($homeserver);
1.506     raeburn  8464:     my $cmd = '';
1.1000    raeburn  8465:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8466:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8467:     }
                   8468:     $cmd =~ s/%%$//;
                   8469:     $cmd = &escape($cmd);
                   8470:     my $query = 'fetchenrollment';
1.620     albertel 8471:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8472:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8473:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8474:         return 'error: '.$queryid;
                   8475:     }
1.1317    raeburn  8476:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8477:     my $tries = 1;
                   8478:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8479:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8480:         $tries ++;
                   8481:     }
1.526     raeburn  8482:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8483:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8484:     } else {
1.901     albertel 8485:         my @responses = split(/:/,$reply);
1.1322    raeburn  8486:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8487:             foreach my $line (@responses) {
                   8488:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8489:                 $$replyref{$key} = $value;
                   8490:             }
                   8491:         } else {
1.1117    foxr     8492:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8493:             foreach my $line (@responses) {
                   8494:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8495:                 $$replyref{$key} = $value;
                   8496:                 if ($value > 0) {
1.800     albertel 8497:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8498:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8499:                         my $destname = $pathname.'/'.$filename;
                   8500:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8501:                         if ($xml_classlist =~ /^error/) {
                   8502:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8503:                         } else {
1.1359    raeburn  8504:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8505:                                 print FILE &unescape($xml_classlist);
                   8506:                                 close(FILE);
1.526     raeburn  8507:                             } else {
                   8508:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8509:                             }
                   8510:                         }
                   8511:                     }
                   8512:                 }
                   8513:             }
                   8514:         }
                   8515:         return 'ok';
                   8516:     }
                   8517:     return 'error';
                   8518: }
                   8519: 
1.242     www      8520: sub get_query_reply {
1.1317    raeburn  8521:     my ($queryid,$sleep,$loopmax) = @_;;
                   8522:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8523:         $sleep = 0.2;
                   8524:     }
                   8525:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8526:         $loopmax = 100;
                   8527:     }
1.1117    foxr     8528:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8529:     my $reply='';
1.1317    raeburn  8530:     for (1..$loopmax) {
                   8531: 	sleep($sleep);
1.240     www      8532:         if (-e $replyfile.'.end') {
1.1359    raeburn  8533: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8534: 		$reply = join('',<$fh>);
                   8535: 		close($fh);
1.240     www      8536: 	   } else { return 'error: reply_file_error'; }
1.242     www      8537:            return &unescape($reply);
                   8538: 	}
1.240     www      8539:     }
1.242     www      8540:     return 'timeout:'.$queryid;
1.240     www      8541: }
                   8542: 
                   8543: sub courselog_query {
1.241     www      8544: #
                   8545: # possible filters:
                   8546: # url: url or symb
                   8547: # username
                   8548: # domain
                   8549: # action: view, submit, grade
                   8550: # start: timestamp
                   8551: # end: timestamp
                   8552: #
1.240     www      8553:     my (%filters)=@_;
1.620     albertel 8554:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8555:     if ($filters{'url'}) {
                   8556: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8557:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8558:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8559:     }
1.620     albertel 8560:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8561:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8562:     return &log_query($cname,$cdom,'courselog',%filters);
                   8563: }
                   8564: 
                   8565: sub userlog_query {
1.858     raeburn  8566: #
                   8567: # possible filters:
                   8568: # action: log check role
                   8569: # start: timestamp
                   8570: # end: timestamp
                   8571: #
1.240     www      8572:     my ($uname,$udom,%filters)=@_;
                   8573:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8574: }
                   8575: 
1.506     raeburn  8576: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8577: 
                   8578: sub auto_run {
1.508     raeburn  8579:     my ($cnum,$cdom) = @_;
1.876     raeburn  8580:     my $response = 0;
                   8581:     my $settings;
                   8582:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8583:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8584:         $settings = $domconfig{'autoenroll'};
                   8585:         if ($settings->{'run'} eq '1') {
                   8586:             $response = 1;
                   8587:         }
                   8588:     } else {
1.934     raeburn  8589:         my $homeserver;
                   8590:         if (&is_course($cdom,$cnum)) {
                   8591:             $homeserver = &homeserver($cnum,$cdom);
                   8592:         } else {
                   8593:             $homeserver = &domain($cdom,'primary');
                   8594:         }
                   8595:         if ($homeserver ne 'no_host') {
                   8596:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8597:         }
1.876     raeburn  8598:     }
1.506     raeburn  8599:     return $response;
                   8600: }
1.776     albertel 8601: 
1.506     raeburn  8602: sub auto_get_sections {
1.508     raeburn  8603:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8604:     my $homeserver;
                   8605:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8606:         $homeserver = &homeserver($cnum,$cdom);
                   8607:     }
                   8608:     if (!defined($homeserver)) { 
                   8609:         if ($cdom =~ /^$match_domain$/) {
                   8610:             $homeserver = &domain($cdom,'primary');
                   8611:         }
                   8612:     }
                   8613:     my @secs;
                   8614:     if (defined($homeserver)) {
                   8615:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8616:         unless ($response eq 'refused') {
                   8617:             @secs = split(/:/,$response);
                   8618:         }
1.506     raeburn  8619:     }
                   8620:     return @secs;
                   8621: }
1.776     albertel 8622: 
1.506     raeburn  8623: sub auto_new_course {
1.1099    raeburn  8624:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8625:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8626:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8627:     return $response;
                   8628: }
1.776     albertel 8629: 
1.506     raeburn  8630: sub auto_validate_courseID {
1.508     raeburn  8631:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8632:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8633:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8634:     return $response;
                   8635: }
1.776     albertel 8636: 
1.1007    raeburn  8637: sub auto_validate_instcode {
1.1020    raeburn  8638:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8639:     my ($homeserver,$response);
                   8640:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8641:         $homeserver = &homeserver($cnum,$cdom);
                   8642:     }
                   8643:     if (!defined($homeserver)) {
                   8644:         if ($cdom =~ /^$match_domain$/) {
                   8645:             $homeserver = &domain($cdom,'primary');
                   8646:         }
                   8647:     }
1.1065    raeburn  8648:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8649:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8650:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8651:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8652: }
                   8653: 
1.506     raeburn  8654: sub auto_create_password {
1.873     raeburn  8655:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8656:     my ($homeserver,$response);
1.506     raeburn  8657:     my $create_passwd = 0;
                   8658:     my $authchk = '';
1.873     raeburn  8659:     if ($udom =~ /^$match_domain$/) {
                   8660:         $homeserver = &domain($udom,'primary');
                   8661:     }
                   8662:     if ($homeserver eq '') {
                   8663:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8664:             $homeserver = &homeserver($cnum,$cdom);
                   8665:         }
                   8666:     }
                   8667:     if ($homeserver eq '') {
                   8668:         $authchk = 'nodomain';
1.506     raeburn  8669:     } else {
1.873     raeburn  8670:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8671:         if ($response eq 'refused') {
                   8672:             $authchk = 'refused';
                   8673:         } else {
1.901     albertel 8674:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8675:         }
1.506     raeburn  8676:     }
                   8677:     return ($authparam,$create_passwd,$authchk);
                   8678: }
                   8679: 
1.706     raeburn  8680: sub auto_photo_permission {
                   8681:     my ($cnum,$cdom,$students) = @_;
                   8682:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8683:     my ($outcome,$perm_reqd,$conditions) = 
                   8684: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8685:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8686: 	return (undef,undef);
                   8687:     }
1.706     raeburn  8688:     return ($outcome,$perm_reqd,$conditions);
                   8689: }
                   8690: 
                   8691: sub auto_checkphotos {
                   8692:     my ($uname,$udom,$pid) = @_;
                   8693:     my $homeserver = &homeserver($uname,$udom);
                   8694:     my ($result,$resulttype);
                   8695:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8696: 				   &escape($uname).':'.&escape($pid),
                   8697: 				   $homeserver));
1.709     albertel 8698:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8699: 	return (undef,undef);
                   8700:     }
1.706     raeburn  8701:     if ($outcome) {
                   8702:         ($result,$resulttype) = split(/:/,$outcome);
                   8703:     } 
                   8704:     return ($result,$resulttype);
                   8705: }
                   8706: 
                   8707: sub auto_photochoice {
                   8708:     my ($cnum,$cdom) = @_;
                   8709:     my $homeserver = &homeserver($cnum,$cdom);
                   8710:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8711: 						       &escape($cdom),
                   8712: 						       $homeserver)));
1.709     albertel 8713:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8714: 	return (undef,undef);
                   8715:     }
1.706     raeburn  8716:     return ($update,$comment);
                   8717: }
                   8718: 
                   8719: sub auto_photoupdate {
                   8720:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8721:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8722:     my $host=&hostname($homeserver);
1.706     raeburn  8723:     my $cmd = '';
                   8724:     my $maxtries = 1;
1.800     albertel 8725:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8726:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8727:     }
                   8728:     $cmd =~ s/%%$//;
                   8729:     $cmd = &escape($cmd);
                   8730:     my $query = 'institutionalphotos';
                   8731:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8732:     unless ($queryid=~/^\Q$host\E\_/) {
                   8733:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8734:         return 'error: '.$queryid;
                   8735:     }
                   8736:     my $reply = &get_query_reply($queryid);
                   8737:     my $tries = 1;
                   8738:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8739:         $reply = &get_query_reply($queryid);
                   8740:         $tries ++;
                   8741:     }
                   8742:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8743:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8744:     } else {
                   8745:         my @responses = split(/:/,$reply);
                   8746:         my $outcome = shift(@responses); 
                   8747:         foreach my $item (@responses) {
                   8748:             my ($key,$value) = split(/=/,$item);
                   8749:             $$photo{$key} = $value;
                   8750:         }
                   8751:         return $outcome;
                   8752:     }
                   8753:     return 'error';
                   8754: }
                   8755: 
1.521     raeburn  8756: sub auto_instcode_format {
1.793     albertel 8757:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8758: 	$cat_order) = @_;
1.521     raeburn  8759:     my $courses = '';
1.772     raeburn  8760:     my @homeservers;
1.521     raeburn  8761:     if ($caller eq 'global') {
1.841     albertel 8762: 	my %servers = &get_servers($codedom,'library');
                   8763: 	foreach my $tryserver (keys(%servers)) {
                   8764: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8765: 		push(@homeservers,$tryserver);
                   8766: 	    }
1.584     raeburn  8767:         }
1.1022    raeburn  8768:     } elsif ($caller eq 'requests') {
                   8769:         if ($codedom =~ /^$match_domain$/) {
                   8770:             my $chome = &domain($codedom,'primary');
                   8771:             unless ($chome eq 'no_host') {
                   8772:                 push(@homeservers,$chome);
                   8773:             }
                   8774:         }
1.521     raeburn  8775:     } else {
1.772     raeburn  8776:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8777:     }
1.793     albertel 8778:     foreach my $code (keys(%{$instcodes})) {
                   8779:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8780:     }
                   8781:     chop($courses);
1.772     raeburn  8782:     my $ok_response = 0;
                   8783:     my $response;
                   8784:     while (@homeservers > 0 && $ok_response == 0) {
                   8785:         my $server = shift(@homeservers); 
                   8786:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8787:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8788:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8789: 		split(/:/,$response);
1.772     raeburn  8790:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8791:             push(@{$codetitles},&str2array($codetitles_str));
                   8792:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8793:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8794:             $ok_response = 1;
                   8795:         }
                   8796:     }
                   8797:     if ($ok_response) {
1.521     raeburn  8798:         return 'ok';
1.772     raeburn  8799:     } else {
                   8800:         return $response;
1.521     raeburn  8801:     }
                   8802: }
                   8803: 
1.792     raeburn  8804: sub auto_instcode_defaults {
                   8805:     my ($domain,$returnhash,$code_order) = @_;
                   8806:     my @homeservers;
1.841     albertel 8807: 
                   8808:     my %servers = &get_servers($domain,'library');
                   8809:     foreach my $tryserver (keys(%servers)) {
                   8810: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8811: 	    push(@homeservers,$tryserver);
                   8812: 	}
1.792     raeburn  8813:     }
1.841     albertel 8814: 
1.792     raeburn  8815:     my $response;
1.841     albertel 8816:     foreach my $server (@homeservers) {
1.792     raeburn  8817:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8818:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8819: 	
                   8820: 	foreach my $pair (split(/\&/,$response)) {
                   8821: 	    my ($name,$value)=split(/\=/,$pair);
                   8822: 	    if ($name eq 'code_order') {
                   8823: 		@{$code_order} = split(/\&/,&unescape($value));
                   8824: 	    } else {
                   8825: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8826: 	    }
                   8827: 	}
                   8828: 	return 'ok';
1.792     raeburn  8829:     }
1.841     albertel 8830: 
                   8831:     return $response;
1.1003    raeburn  8832: }
                   8833: 
                   8834: sub auto_possible_instcodes {
1.1007    raeburn  8835:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8836:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8837:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8838:         return;
                   8839:     }
1.1003    raeburn  8840:     my (@homeservers,$uhome);
                   8841:     if (defined(&domain($domain,'primary'))) {
                   8842:         $uhome=&domain($domain,'primary');
                   8843:         push(@homeservers,&domain($domain,'primary'));
                   8844:     } else {
                   8845:         my %servers = &get_servers($domain,'library');
                   8846:         foreach my $tryserver (keys(%servers)) {
                   8847:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8848:                 push(@homeservers,$tryserver);
                   8849:             }
                   8850:         }
                   8851:     }
                   8852:     my $response;
                   8853:     foreach my $server (@homeservers) {
                   8854:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8855:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8856:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8857:             split(':',$response);
                   8858:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8859:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8860:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8861:             my ($name,$value)=split('=',$item);
                   8862:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8863:         }
                   8864:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8865:             my ($name,$value)=split('=',$item);
                   8866:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8867:         }
                   8868:         return 'ok';
                   8869:     }
                   8870:     return $response;
                   8871: }
1.792     raeburn  8872: 
1.1010    raeburn  8873: sub auto_courserequest_checks {
                   8874:     my ($dom) = @_;
1.1020    raeburn  8875:     my ($homeserver,%validations);
                   8876:     if ($dom =~ /^$match_domain$/) {
                   8877:         $homeserver = &domain($dom,'primary');
                   8878:     }
                   8879:     unless ($homeserver eq 'no_host') {
                   8880:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8881:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8882:             my @items = split(/&/,$response);
                   8883:             foreach my $item (@items) {
                   8884:                 my ($key,$value) = split('=',$item);
                   8885:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8886:             }
                   8887:         }
                   8888:     }
1.1010    raeburn  8889:     return %validations; 
                   8890: }
                   8891: 
1.1020    raeburn  8892: sub auto_courserequest_validation {
1.1255    raeburn  8893:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8894:     my ($homeserver,$response);
                   8895:     if ($dom =~ /^$match_domain$/) {
                   8896:         $homeserver = &domain($dom,'primary');
                   8897:     }
1.1255    raeburn  8898:     unless ($homeserver eq 'no_host') {
                   8899:         my $customdata;
                   8900:         if (ref($custominfo) eq 'HASH') {
                   8901:             $customdata = &freeze_escape($custominfo);
                   8902:         }
1.1020    raeburn  8903:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8904:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8905:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8906:                                     $customdata,$homeserver));
1.1020    raeburn  8907:     }
                   8908:     return $response;
                   8909: }
                   8910: 
1.777     albertel 8911: sub auto_validate_class_sec {
1.918     raeburn  8912:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8913:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8914:     my $ownerlist;
                   8915:     if (ref($owners) eq 'ARRAY') {
                   8916:         $ownerlist = join(',',@{$owners});
                   8917:     } else {
                   8918:         $ownerlist = $owners;
                   8919:     }
1.773     raeburn  8920:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8921:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8922:     return $response;
                   8923: }
                   8924: 
1.1367    raeburn  8925: sub auto_validate_instclasses {
                   8926:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8927:     my ($homeserver,%validations);
                   8928:     $homeserver = &homeserver($cnum,$cdom);
                   8929:     unless ($homeserver eq 'no_host') {
                   8930:         my $ownerlist;
                   8931:         if (ref($owners) eq 'ARRAY') {
                   8932:             $ownerlist = join(',',@{$owners});
                   8933:         } else {
                   8934:             $ownerlist = $owners;
                   8935:         }
                   8936:         if (ref($classesref) eq 'HASH') {
                   8937:             my $classes = &freeze_escape($classesref);
                   8938:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8939:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8940:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8941:                 my @items = split(/&/,$response);
                   8942:                 foreach my $item (@items) {
                   8943:                     my ($key,$value) = split('=',$item);
                   8944:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8945:                 }
                   8946:             }
                   8947:         }
                   8948:     }
                   8949:     return %validations;
                   8950: }
                   8951: 
1.1248    raeburn  8952: sub auto_crsreq_update {
                   8953:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8954:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8955:     my ($homeserver,%crsreqresponse);
                   8956:     if ($cdom =~ /^$match_domain$/) {
                   8957:         $homeserver = &domain($cdom,'primary');
                   8958:     }
                   8959:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8960:         my $info;
                   8961:         if (ref($inbound) eq 'HASH') {
                   8962:             $info = &freeze_escape($inbound);
                   8963:         }
                   8964:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8965:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8966:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8967:                             &escape($title).':'.&escape($code).':'.
                   8968:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8969:                             $homeserver);
1.1248    raeburn  8970:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8971:             my @items = split(/&/,$response);
                   8972:             foreach my $item (@items) {
                   8973:                 my ($key,$value) = split('=',$item);
                   8974:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8975:             }
                   8976:         }
                   8977:     }
                   8978:     return \%crsreqresponse;
                   8979: }
                   8980: 
1.1305    raeburn  8981: sub auto_export_grades {
1.1309    raeburn  8982:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8983:     my ($homeserver,%exportresponse);
                   8984:     if ($cdom =~ /^$match_domain$/) {
                   8985:         $homeserver = &domain($cdom,'primary');
                   8986:     }
                   8987:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8988:         my $info;
                   8989:         if (ref($inforef) eq 'HASH') {
                   8990:             $info = &freeze_escape($inforef);
                   8991:         }
                   8992:         if (ref($gradesref) eq 'HASH') {
                   8993:             my $grades = &freeze_escape($gradesref);
                   8994:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8995:                                 $info.':'.$grades,$homeserver);
                   8996:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8997:                 my @items = split(/&/,$response);
                   8998:                 foreach my $item (@items) {
                   8999:                     my ($key,$value) = split('=',$item);
                   9000:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9001:                 }
                   9002:             }
                   9003:         }
                   9004:     }
                   9005:     return \%exportresponse;
1.1305    raeburn  9006: }
                   9007: 
1.1287    raeburn  9008: sub check_instcode_cloning {
                   9009:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9010:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9011:         return;
                   9012:     }
                   9013:     my $canclone;
                   9014:     if (@{$code_order} > 0) {
                   9015:         my $instcoderegexp ='^';
                   9016:         my @clonecodes = split(/\&/,$cloner);
                   9017:         foreach my $item (@{$code_order}) {
                   9018:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9019:                 foreach my $pair (@clonecodes) {
                   9020:                     my ($key,$val) = split(/\=/,$pair,2);
                   9021:                     $val = &unescape($val);
                   9022:                     if ($key eq $item) {
                   9023:                         $instcoderegexp .= '('.$val.')';
                   9024:                         last;
                   9025:                     }
                   9026:                 }
                   9027:             } else {
                   9028:                 $instcoderegexp .= $codedefaults->{$item};
                   9029:             }
                   9030:         }
                   9031:         $instcoderegexp .= '$';
                   9032:         my (@from,@to);
                   9033:         eval {
                   9034:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9035:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9036:         };
                   9037:         if ((@from > 0) && (@to > 0)) {
                   9038:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9039:             if (!@diffs) {
                   9040:                 $canclone = 1;
                   9041:             }
                   9042:         }
                   9043:     }
                   9044:     return $canclone;
                   9045: }
                   9046: 
                   9047: sub default_instcode_cloning {
                   9048:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9049:     my (%codedefaults,@code_order,$canclone);
                   9050:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9051:         %codedefaults = %{$codedefaultsref};
                   9052:         @code_order = @{$codeorderref};
                   9053:     } elsif ($clonedom) {
                   9054:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9055:     }
                   9056:     if (($domdefclone) && (@code_order)) {
                   9057:         my @clonecodes = split(/\+/,$domdefclone);
                   9058:         my $instcoderegexp ='^';
                   9059:         foreach my $item (@code_order) {
                   9060:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9061:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9062:             } else {
                   9063:                 $instcoderegexp .= $codedefaults{$item};
                   9064:             }
                   9065:         }
                   9066:         $instcoderegexp .= '$';
                   9067:         my (@from,@to);
                   9068:         eval {
                   9069:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9070:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9071:         };
                   9072:         if ((@from > 0) && (@to > 0)) {
                   9073:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9074:             if (!@diffs) {
                   9075:                 $canclone = 1;
                   9076:             }
                   9077:         }
                   9078:     }
                   9079:     return $canclone;
                   9080: }
                   9081: 
1.679     raeburn  9082: # ------------------------------------------------------- Course Group routines
                   9083: 
                   9084: sub get_coursegroups {
1.809     raeburn  9085:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9086:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9087: }
                   9088: 
1.679     raeburn  9089: sub modify_coursegroup {
                   9090:     my ($cdom,$cnum,$groupsettings) = @_;
                   9091:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9092: }
                   9093: 
1.809     raeburn  9094: sub toggle_coursegroup_status {
                   9095:     my ($cdom,$cnum,$group,$action) = @_;
                   9096:     my ($from_namespace,$to_namespace);
                   9097:     if ($action eq 'delete') {
                   9098:         $from_namespace = 'coursegroups';
                   9099:         $to_namespace = 'deleted_groups';
                   9100:     } else {
                   9101:         $from_namespace = 'deleted_groups';
                   9102:         $to_namespace = 'coursegroups';
                   9103:     }
                   9104:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9105:     if (my $tmp = &error(%curr_group)) {
                   9106:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9107:         return ('read error',$tmp);
                   9108:     } else {
                   9109:         my %savedsettings = %curr_group; 
1.809     raeburn  9110:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9111:         my $deloutcome;
                   9112:         if ($result eq 'ok') {
1.809     raeburn  9113:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9114:         } else {
                   9115:             return ('write error',$result);
                   9116:         }
                   9117:         if ($deloutcome eq 'ok') {
                   9118:             return 'ok';
                   9119:         } else {
                   9120:             return ('delete error',$deloutcome);
                   9121:         }
                   9122:     }
                   9123: }
                   9124: 
1.679     raeburn  9125: sub modify_group_roles {
1.957     raeburn  9126:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9127:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9128:     my $role = 'gr/'.&escape($userprivs);
                   9129:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9130:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9131:     if ($result eq 'ok') {
                   9132:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9133:     }
1.679     raeburn  9134:     return $result;
                   9135: }
                   9136: 
                   9137: sub modify_coursegroup_membership {
                   9138:     my ($cdom,$cnum,$membership) = @_;
                   9139:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9140:     return $result;
                   9141: }
                   9142: 
1.682     raeburn  9143: sub get_active_groups {
                   9144:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9145:     my $now = time;
                   9146:     my %groups = ();
                   9147:     foreach my $key (keys(%env)) {
1.811     albertel 9148:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9149:             my ($start,$end) = split(/\./,$env{$key});
                   9150:             if (($end!=0) && ($end<$now)) { next; }
                   9151:             if (($start!=0) && ($start>$now)) { next; }
                   9152:             if ($1 eq $cdom && $2 eq $cnum) {
                   9153:                 $groups{$3} = $env{$key} ;
                   9154:             }
                   9155:         }
                   9156:     }
                   9157:     return %groups;
                   9158: }
                   9159: 
1.683     raeburn  9160: sub get_group_membership {
                   9161:     my ($cdom,$cnum,$group) = @_;
                   9162:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9163: }
                   9164: 
                   9165: sub get_users_groups {
                   9166:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9167:     my @usersgroups;
1.683     raeburn  9168:     my $cachetime=1800;
                   9169: 
                   9170:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9171:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9172:     if (defined($cached)) {
1.734     albertel 9173:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9174:     } else {  
                   9175:         $grouplist = '';
1.816     raeburn  9176:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9177:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9178:         my $access_end = $env{'course.'.$courseid.
                   9179:                               '.default_enrollment_end_date'};
                   9180:         my $now = time;
                   9181:         foreach my $key (keys(%roleshash)) {
                   9182:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9183:                 my $group = $1;
                   9184:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9185:                     my $start = $2;
                   9186:                     my $end = $1;
                   9187:                     if ($start == -1) { next; } # deleted from group
                   9188:                     if (($start!=0) && ($start>$now)) { next; }
                   9189:                     if (($end!=0) && ($end<$now)) {
                   9190:                         if ($access_end && $access_end < $now) {
                   9191:                             if ($access_end - $end < 86400) {
                   9192:                                 push(@usersgroups,$group);
1.733     raeburn  9193:                             }
                   9194:                         }
1.817     raeburn  9195:                         next;
1.733     raeburn  9196:                     }
1.817     raeburn  9197:                     push(@usersgroups,$group);
1.683     raeburn  9198:                 }
                   9199:             }
                   9200:         }
1.817     raeburn  9201:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9202:         $grouplist = join(':',@usersgroups);
                   9203:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9204:     }
1.733     raeburn  9205:     return @usersgroups;
1.683     raeburn  9206: }
                   9207: 
                   9208: sub devalidate_getgroups_cache {
                   9209:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9210:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9211: 
1.683     raeburn  9212:     my $hashid="$udom:$uname:$courseid";
                   9213:     &devalidate_cache_new('getgroups',$hashid);
                   9214: }
                   9215: 
1.12      www      9216: # ------------------------------------------------------------------ Plain Text
                   9217: 
                   9218: sub plaintext {
1.988     raeburn  9219:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9220:     if ($short =~ m{^cr/}) {
1.758     albertel 9221: 	return (split('/',$short))[-1];
                   9222:     }
1.742     raeburn  9223:     if (!defined($cid)) {
                   9224:         $cid = $env{'request.course.id'};
                   9225:     }
                   9226:     my %rolenames = (
1.1008    raeburn  9227:                       Course    => 'std',
                   9228:                       Community => 'alt1',
1.1305    raeburn  9229:                       Placement => 'std',
1.742     raeburn  9230:                     );
1.1037    raeburn  9231:     if ($cid ne '') {
                   9232:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9233:             unless ($forcedefault) {
                   9234:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9235:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9236:                 return &Apache::lonlocal::mt($roletext);
                   9237:             }
                   9238:         }
                   9239:     }
                   9240:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9241:         (defined($rolenames{$type})) && 
                   9242:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9243:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9244:     } elsif ($cid ne '') {
                   9245:         my $crstype = $env{'course.'.$cid.'.type'};
                   9246:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9247:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9248:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9249:         }
1.742     raeburn  9250:     }
1.1037    raeburn  9251:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9252: }
                   9253: 
                   9254: # ----------------------------------------------------------------- Assign Role
                   9255: 
                   9256: sub assignrole {
1.957     raeburn  9257:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9258:         $context)=@_;
1.21      www      9259:     my $mrole;
                   9260:     if ($role =~ /^cr\//) {
1.393     www      9261:         my $cwosec=$url;
1.811     albertel 9262:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9263: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9264:            my $refused = 1;
                   9265:            if ($context eq 'requestcourses') {
                   9266:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9267:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9268:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9269:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9270:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9271:                            if ($crsenv{'internal.courseowner'} eq
                   9272:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9273:                                $refused = '';
                   9274:                            }
                   9275:                        }
                   9276:                    }
                   9277:                }
                   9278:            }
                   9279:            if ($refused) {
                   9280:                &logthis('Refused custom assignrole: '.
                   9281:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9282:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9283:                return 'refused';
                   9284:            }
1.104     www      9285:         }
1.21      www      9286:         $mrole='cr';
1.678     raeburn  9287:     } elsif ($role =~ /^gr\//) {
                   9288:         my $cwogrp=$url;
1.811     albertel 9289:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9290:         unless (&allowed('mdg',$cwogrp)) {
                   9291:             &logthis('Refused group assignrole: '.
                   9292:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9293:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9294:             return 'refused';
                   9295:         }
                   9296:         $mrole='gr';
1.21      www      9297:     } else {
1.82      www      9298:         my $cwosec=$url;
1.811     albertel 9299:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9300:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9301:             my $refused;
                   9302:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9303:                 if (!(&allowed('c'.$role,$url))) {
                   9304:                     $refused = 1;
                   9305:                 }
                   9306:             } else {
                   9307:                 $refused = 1;
                   9308:             }
1.947     raeburn  9309:             if ($refused) {
1.1045    raeburn  9310:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9311:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9312:                     my %crsenv;
                   9313:                     if ($role eq 'cc' || $role eq 'co') {
                   9314:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9315:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9316:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9317:                                 if ($crsenv{'internal.courseowner'} eq 
                   9318:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9319:                                     $refused = '';
                   9320:                                 }
                   9321:                             }
                   9322:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9323:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9324:                                 if ($crsenv{'internal.courseowner'} eq 
                   9325:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9326:                                     $refused = '';
                   9327:                                 }
                   9328:                             }
                   9329:                         }
                   9330:                     }
1.1368    raeburn  9331:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9332:                     if ($role eq 'st') {
                   9333:                         $refused = '';
1.1377    raeburn  9334:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9335:                         $refused = '';
                   9336:                     }
1.1017    raeburn  9337:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9338:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9339:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9340:                         my $wrongcc;
                   9341:                         if ($cnum =~ /^$match_community$/) {
                   9342:                             $wrongcc = 1 if ($role eq 'cc');
                   9343:                         } else {
                   9344:                             $wrongcc = 1 if ($role eq 'co');
                   9345:                         }
                   9346:                         unless ($wrongcc) {
                   9347:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9348:                             if ($crsenv{'internal.courseowner'} eq 
                   9349:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9350:                                 $refused = '';
                   9351:                             }
1.1017    raeburn  9352:                         }
                   9353:                     }
1.1183    raeburn  9354:                 } elsif ($context eq 'requestauthor') {
                   9355:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9356:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9357:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9358:                             $refused = '';
                   9359:                         } else {
                   9360:                             my %domdefaults = &get_domain_defaults($udom);
                   9361:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9362:                                 my $checkbystatus;
                   9363:                                 if ($env{'user.adv'}) { 
                   9364:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9365:                                     if ($disposition eq 'automatic') {
                   9366:                                         $refused = '';
                   9367:                                     } elsif ($disposition eq '') {
                   9368:                                         $checkbystatus = 1;
                   9369:                                     } 
                   9370:                                 } else {
                   9371:                                     $checkbystatus = 1;
                   9372:                                 }
                   9373:                                 if ($checkbystatus) {
                   9374:                                     if ($env{'environment.inststatus'}) {
                   9375:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9376:                                         foreach my $type (@inststatuses) {
                   9377:                                             if (($type ne '') &&
                   9378:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9379:                                                 $refused = '';
                   9380:                                             }
                   9381:                                         }
                   9382:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9383:                                         $refused = '';
                   9384:                                     }
                   9385:                                 }
                   9386:                             }
                   9387:                         }
                   9388:                     }
1.1017    raeburn  9389:                 }
                   9390:                 if ($refused) {
1.947     raeburn  9391:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9392:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9393: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9394:                     return 'refused';
                   9395:                 }
1.932     raeburn  9396:             }
1.1131    raeburn  9397:         } elsif ($role eq 'au') {
                   9398:             if ($url ne '/'.$udom.'/') {
                   9399:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9400:                          ' to assign author role for '.$uname.':'.$udom.
                   9401:                          ' in domain: '.$url.' refused (wrong domain).');
                   9402:                 return 'refused';
                   9403:             }
1.104     www      9404:         }
1.21      www      9405:         $mrole=$role;
                   9406:     }
1.620     albertel 9407:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9408:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9409:     if ($end) { $command.='_'.$end; }
1.21      www      9410:     if ($start) {
                   9411: 	if ($end) { 
1.81      www      9412:            $command.='_'.$start; 
1.21      www      9413:         } else {
1.81      www      9414:            $command.='_0_'.$start;
1.21      www      9415:         }
                   9416:     }
1.739     raeburn  9417:     my $origstart = $start;
                   9418:     my $origend = $end;
1.957     raeburn  9419:     my $delflag;
1.357     www      9420: # actually delete
                   9421:     if ($deleteflag) {
1.373     www      9422: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9423: # modify command to delete the role
1.620     albertel 9424:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9425:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9426: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9427: # set start and finish to negative values for userrolelog
                   9428:            $start=-1;
                   9429:            $end=-1;
1.957     raeburn  9430:            $delflag = 1;
1.357     www      9431:         }
                   9432:     }
                   9433: # send command
1.349     www      9434:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9435: # log new user role if status is ok
1.349     www      9436:     if ($answer eq 'ok') {
1.663     raeburn  9437: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9438:         if (($role eq 'cc') || ($role eq 'in') ||
                   9439:             ($role eq 'ep') || ($role eq 'ad') ||
                   9440:             ($role eq 'ta') || ($role eq 'st') ||
                   9441:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9442:             ($role eq 'co')) {
1.1200    raeburn  9443: # for course roles, perform group memberships changes triggered by role change.
                   9444:             unless ($role =~ /^gr/) {
                   9445:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9446:                                                  $origstart,$selfenroll,$context);
                   9447:             }
1.1184    raeburn  9448:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9449:                            $selfenroll,$context);
                   9450:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9451:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9452:                  ($role eq 'da')) {
1.1184    raeburn  9453:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9454:                            $context);
                   9455:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9456:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9457:                              $context); 
                   9458:         }
1.1053    raeburn  9459:         if ($role eq 'cc') {
                   9460:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9461:         }
1.349     www      9462:     }
                   9463:     return $answer;
1.169     harris41 9464: }
                   9465: 
1.1053    raeburn  9466: sub autoupdate_coowners {
                   9467:     my ($url,$end,$start,$uname,$udom) = @_;
                   9468:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9469:     if (($cdom ne '') && ($cnum ne '')) {
                   9470:         my $now = time;
                   9471:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9472:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9473:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9474:             my $instcode = $coursehash{'internal.coursecode'};
                   9475:             if ($instcode ne '') {
1.1056    raeburn  9476:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9477:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9478:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9479:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9480:                         if ($result eq 'valid') {
                   9481:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9482:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9483:                                     push(@newcoowners,$coowner);
                   9484:                                 }
                   9485:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9486:                                     push(@newcoowners,$uname.':'.$udom);
                   9487:                                 }
                   9488:                                 @newcoowners = sort(@newcoowners);
                   9489:                             } else {
                   9490:                                 push(@newcoowners,$uname.':'.$udom);
                   9491:                             }
                   9492:                         } else {
                   9493:                             if ($coursehash{'internal.co-owners'}) {
                   9494:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9495:                                     unless ($coowner eq $uname.':'.$udom) {
                   9496:                                         push(@newcoowners,$coowner);
                   9497:                                     }
                   9498:                                 }
                   9499:                                 unless (@newcoowners > 0) {
                   9500:                                     $delcoowners = 1;
                   9501:                                     $coowners = '';
                   9502:                                 }
                   9503:                             }
                   9504:                         }
                   9505:                         if (@newcoowners || $delcoowners) {
                   9506:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9507:                                             $delcoowners,@newcoowners);
                   9508:                         }
                   9509:                     }
                   9510:                 }
                   9511:             }
                   9512:         }
                   9513:     }
                   9514: }
                   9515: 
                   9516: sub store_coowners {
                   9517:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9518:     my $cid = $cdom.'_'.$cnum;
                   9519:     my ($coowners,$delresult,$putresult);
                   9520:     if (@newcoowners) {
                   9521:         $coowners = join(',',@newcoowners);
                   9522:         my %coownershash = (
                   9523:                             'internal.co-owners' => $coowners,
                   9524:                            );
                   9525:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9526:         if ($putresult eq 'ok') {
                   9527:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9528:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9529:             }
                   9530:         }
                   9531:     }
                   9532:     if ($delcoowners) {
                   9533:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9534:         if ($delresult eq 'ok') {
                   9535:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9536:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9537:             }
                   9538:         }
                   9539:     }
                   9540:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9541:         my %crsinfo =
                   9542:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9543:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9544:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9545:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9546:         }
                   9547:     }
                   9548: }
                   9549: 
1.169     harris41 9550: # -------------------------------------------------- Modify user authentication
1.197     www      9551: # Overrides without validation
                   9552: 
1.169     harris41 9553: sub modifyuserauth {
                   9554:     my ($udom,$uname,$umode,$upass)=@_;
                   9555:     my $uhome=&homeserver($uname,$udom);
1.197     www      9556:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9557:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9558:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9559:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9560:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9561: 		     &escape($upass),$uhome);
1.620     albertel 9562:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9563:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9564:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9565:     &log($udom,,$uname,$uhome,
1.620     albertel 9566:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9567:                                      $env{'user.name'}.', '.$umode.
1.197     www      9568:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9569:     unless ($reply eq 'ok') {
1.197     www      9570:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9571: 	return 'error: '.$reply;
                   9572:     }   
1.170     harris41 9573:     return 'ok';
1.80      www      9574: }
                   9575: 
1.81      www      9576: # --------------------------------------------------------------- Modify a user
1.80      www      9577: 
1.81      www      9578: sub modifyuser {
1.206     matthew  9579:     my ($udom,    $uname, $uid,
                   9580:         $umode,   $upass, $first,
                   9581:         $middle,  $last,  $gene,
1.1058    raeburn  9582:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9583:     $udom= &LONCAPA::clean_domain($udom);
                   9584:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9585:     my $showcandelete = 'none';
                   9586:     if (ref($candelete) eq 'ARRAY') {
                   9587:         if (@{$candelete} > 0) {
                   9588:             $showcandelete = join(', ',@{$candelete});
                   9589:         }
                   9590:     }
1.81      www      9591:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9592:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9593: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9594:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9595:                                      ' desiredhome not specified'). 
1.620     albertel 9596:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9597:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9598:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9599:     my $newuser;
                   9600:     if ($uhome eq 'no_host') {
                   9601:         $newuser = 1;
1.1368    raeburn  9602:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9603:                 ($umode eq 'lti')) {
                   9604:             return 'error: more information needed to create new user';
                   9605:         }
1.1075    raeburn  9606:     }
1.80      www      9607: # ----------------------------------------------------------------- Create User
1.406     albertel 9608:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9609: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9610:         my $unhome='';
1.844     albertel 9611:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9612:             $unhome = $desiredhome;
1.620     albertel 9613: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9614: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9615:         } else { # load balancing routine for determining $unhome
1.81      www      9616:             my $loadm=10000000;
1.841     albertel 9617: 	    my %servers = &get_servers($udom,'library');
                   9618: 	    foreach my $tryserver (keys(%servers)) {
                   9619: 		my $answer=reply('load',$tryserver);
                   9620: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9621: 		    $loadm=$answer;
                   9622: 		    $unhome=$tryserver;
                   9623: 		}
1.80      www      9624: 	    }
                   9625:         }
                   9626:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9627: 	    return 'error: unable to find a home server for '.$uname.
                   9628:                    ' in domain '.$udom;
1.80      www      9629:         }
                   9630:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9631:                          &escape($upass),$unhome);
                   9632: 	unless ($reply eq 'ok') {
                   9633:             return 'error: '.$reply;
                   9634:         }   
1.230     stredwic 9635:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9636:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9637: 	    return 'error: unable verify users home machine.';
1.80      www      9638:         }
1.209     matthew  9639:     }   # End of creation of new user
1.80      www      9640: # ---------------------------------------------------------------------- Add ID
                   9641:     if ($uid) {
                   9642:        $uid=~tr/A-Z/a-z/;
                   9643:        my %uidhash=&idrget($udom,$uname);
1.196     www      9644:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9645:          && (!$forceid)) {
1.80      www      9646: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9647: 	      return 'error: user id "'.$uid.'" does not match '.
                   9648:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9649:           }
                   9650:        } else {
1.1300    raeburn  9651: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9652:        }
                   9653:     }
                   9654: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9655:     my @tmp=&get('environment',
1.899     raeburn  9656: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9657:                     'permanentemail','inststatus'],
1.134     albertel 9658: 		   $udom,$uname);
1.1075    raeburn  9659:     my (%names,%oldnames);
1.313     matthew  9660:     if ($tmp[0] =~ m/^error:.*/) { 
                   9661:         %names=(); 
                   9662:     } else {
                   9663:         %names = @tmp;
1.1075    raeburn  9664:         %oldnames = %names;
1.313     matthew  9665:     }
1.388     www      9666: #
1.1058    raeburn  9667: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9668: # of users did not contain them), do not overwrite existing values
                   9669: # unless field is in $candelete array ref.  
                   9670: #
                   9671: 
                   9672:     my @fields = ('firstname','middlename','lastname','generation',
                   9673:                   'permanentemail','id');
                   9674:     my %newvalues;
                   9675:     if (ref($candelete) eq 'ARRAY') {
                   9676:         foreach my $field (@fields) {
                   9677:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9678:                 if ($field eq 'firstname') {
                   9679:                     $names{$field} = $first;
                   9680:                 } elsif ($field eq 'middlename') {
                   9681:                     $names{$field} = $middle;
                   9682:                 } elsif ($field eq 'lastname') {
                   9683:                     $names{$field} = $last;
                   9684:                 } elsif ($field eq 'generation') { 
                   9685:                     $names{$field} = $gene;
                   9686:                 } elsif ($field eq 'permanentemail') {
                   9687:                     $names{$field} = $email;
                   9688:                 } elsif ($field eq 'id') {
                   9689:                     $names{$field}  = $uid;
                   9690:                 }
                   9691:             }
                   9692:         }
                   9693:     }
1.388     www      9694:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9695:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9696:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9697:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9698:     if ($email) {
                   9699:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9700:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9701:     }
1.899     raeburn  9702:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9703:     if (defined($inststatus)) {
                   9704:         $names{'inststatus'} = '';
                   9705:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9706:         if (ref($usertypes) eq 'HASH') {
                   9707:             my @okstatuses; 
                   9708:             foreach my $item (split(/:/,$inststatus)) {
                   9709:                 if (defined($usertypes->{$item})) {
                   9710:                     push(@okstatuses,$item);  
                   9711:                 }
                   9712:             }
                   9713:             if (@okstatuses) {
                   9714:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9715:             }
                   9716:         }
                   9717:     }
1.1075    raeburn  9718:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9719:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9720:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9721:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9722:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9723:     } else {
                   9724:         $logmsg .= ' during self creation';
                   9725:     }
1.1075    raeburn  9726:     my $changed;
                   9727:     if ($newuser) {
                   9728:         $changed = 1;
                   9729:     } else {
                   9730:         foreach my $field (@fields) {
                   9731:             if ($names{$field} ne $oldnames{$field}) {
                   9732:                 $changed = 1;
                   9733:                 last;
                   9734:             }
                   9735:         }
                   9736:     }
                   9737:     unless ($changed) {
                   9738:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9739:         &logthis($logmsg);
                   9740:         return 'ok';
                   9741:     }
                   9742:     my $reply = &put('environment', \%names, $udom,$uname);
                   9743:     if ($reply ne 'ok') { 
                   9744:         return 'error: '.$reply;
                   9745:     }
1.1087    raeburn  9746:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9747:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9748:     }
1.1075    raeburn  9749:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9750:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9751:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9752:     &logthis($logmsg);
1.134     albertel 9753:     return 'ok';
1.80      www      9754: }
                   9755: 
1.81      www      9756: # -------------------------------------------------------------- Modify student
1.80      www      9757: 
1.81      www      9758: sub modifystudent {
                   9759:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9760:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9761:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9762:     if (!$cid) {
1.620     albertel 9763: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9764: 	    return 'not_in_class';
                   9765: 	}
1.80      www      9766:     }
                   9767: # --------------------------------------------------------------- Make the user
1.81      www      9768:     my $reply=&modifyuser
1.209     matthew  9769: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9770:          $desiredhome,$email,$inststatus);
1.80      www      9771:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9772:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9773:     # student's environment
1.297     matthew  9774:     $uid = undef if (!$forceid);
1.455     albertel 9775:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9776:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9777:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9778:     return $reply;
                   9779: }
                   9780: 
                   9781: sub modify_student_enrollment {
1.1216    raeburn  9782:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9783:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9784:     my ($cdom,$cnum,$chome);
                   9785:     if (!$cid) {
1.620     albertel 9786: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9787: 	    return 'not_in_class';
                   9788: 	}
1.620     albertel 9789: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9790: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9791:     } else {
                   9792: 	($cdom,$cnum)=split(/_/,$cid);
                   9793:     }
1.620     albertel 9794:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9795:     if (!$chome) {
1.457     raeburn  9796: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9797:     }
1.455     albertel 9798:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9799:     # Make sure the user exists
1.81      www      9800:     my $uhome=&homeserver($uname,$udom);
                   9801:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9802: 	return 'error: no such user';
                   9803:     }
1.297     matthew  9804:     # Get student data if we were not given enough information
                   9805:     if (!defined($first)  || $first  eq '' || 
                   9806:         !defined($last)   || $last   eq '' || 
                   9807:         !defined($uid)    || $uid    eq '' || 
                   9808:         !defined($middle) || $middle eq '' || 
                   9809:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9810:         # They did not supply us with enough data to enroll the student, so
                   9811:         # we need to pick up more information.
1.297     matthew  9812:         my %tmp = &get('environment',
1.294     matthew  9813:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9814:                        ,$udom,$uname);
                   9815: 
1.800     albertel 9816:         #foreach my $key (keys(%tmp)) {
                   9817:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9818:         #}
1.294     matthew  9819:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9820:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9821:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9822:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9823:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9824:     }
1.556     albertel 9825:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9826:     my $user = "$uname:$udom";
                   9827:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9828:     my $reply=cput('classlist',
1.1148    raeburn  9829: 		   {$user => 
1.1314    raeburn  9830: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9831: 		   $cdom,$cnum);
1.1148    raeburn  9832:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9833:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9834:     } else { 
1.81      www      9835: 	return 'error: '.$reply;
                   9836:     }
1.297     matthew  9837:     # Add student role to user
1.83      www      9838:     my $uurl='/'.$cid;
1.81      www      9839:     $uurl=~s/\_/\//g;
                   9840:     if ($usec) {
                   9841: 	$uurl.='/'.$usec;
                   9842:     }
1.1148    raeburn  9843:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9844:                              $selfenroll,$context);
                   9845:     if ($result ne 'ok') {
                   9846:         if ($old_entry{$user} ne '') {
                   9847:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9848:         } else {
                   9849:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9850:         }
                   9851:     }
                   9852:     return $result; 
1.21      www      9853: }
                   9854: 
1.556     albertel 9855: sub format_name {
                   9856:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9857:     my $name;
                   9858:     if ($first ne 'lastname') {
                   9859: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9860:     } else {
                   9861: 	if ($lastname=~/\S/) {
                   9862: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9863: 	    $name=~s/\s+,/,/;
                   9864: 	} else {
                   9865: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9866: 	}
                   9867:     }
                   9868:     $name=~s/^\s+//;
                   9869:     $name=~s/\s+$//;
                   9870:     $name=~s/\s+/ /g;
                   9871:     return $name;
                   9872: }
                   9873: 
1.84      www      9874: # ------------------------------------------------- Write to course preferences
                   9875: 
                   9876: sub writecoursepref {
                   9877:     my ($courseid,%prefs)=@_;
                   9878:     $courseid=~s/^\///;
                   9879:     $courseid=~s/\_/\//g;
                   9880:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9881:     my $chome=homeserver($cnum,$cdomain);
                   9882:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9883: 	return 'error: no such course';
                   9884:     }
                   9885:     my $cstring='';
1.800     albertel 9886:     foreach my $pref (keys(%prefs)) {
                   9887: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9888:     }
1.84      www      9889:     $cstring=~s/\&$//;
                   9890:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9891: }
                   9892: 
                   9893: # ---------------------------------------------------------- Make/modify course
                   9894: 
                   9895: sub createcourse {
1.741     raeburn  9896:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9897:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9898:     $url=&declutter($url);
                   9899:     my $cid='';
1.1028    raeburn  9900:     if ($context eq 'requestcourses') {
                   9901:         my $can_create = 0;
                   9902:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9903:         if ($udom eq $ownerdom) {
                   9904:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9905:                                   $context)) {
                   9906:                 $can_create = 1;
                   9907:             }
                   9908:         } else {
                   9909:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9910:                                            $category);
                   9911:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9912:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9913:                 if (@curr > 0) {
                   9914:                     my @options = qw(approval validate autolimit);
                   9915:                     my $optregex = join('|',@options);
                   9916:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9917:                         $can_create = 1;
                   9918:                     }
                   9919:                 }
                   9920:             }
                   9921:         }
                   9922:         if ($can_create) {
                   9923:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9924:                 unless (&allowed('ccc',$udom)) {
                   9925:                     return 'refused'; 
                   9926:                 }
1.1017    raeburn  9927:             }
                   9928:         } else {
                   9929:             return 'refused';
                   9930:         }
1.1028    raeburn  9931:     } elsif (!&allowed('ccc',$udom)) {
                   9932:         return 'refused';
1.84      www      9933:     }
1.1011    raeburn  9934: # --------------------------------------------------------------- Get Unique ID
                   9935:     my $uname;
                   9936:     if ($cnum =~ /^$match_courseid$/) {
                   9937:         my $chome=&homeserver($cnum,$udom,'true');
                   9938:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9939:             $uname = $cnum;
                   9940:         } else {
1.1038    raeburn  9941:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9942:         }
                   9943:     } else {
1.1038    raeburn  9944:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9945:     }
                   9946:     return $uname if ($uname =~ /^error/);
                   9947: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9948:     if (!defined($course_server)) {
                   9949:         if (defined(&domain($udom,'primary'))) {
                   9950:             $course_server = &domain($udom,'primary');
                   9951:         } else {
                   9952:             $course_server = $env{'user.home'}; 
                   9953:         }
                   9954:     }
                   9955:     my %host_servers =
                   9956:         &Apache::lonnet::get_servers($udom,'library');
                   9957:     unless ($host_servers{$course_server}) {
                   9958:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9959:     }
1.84      www      9960: # ------------------------------------------------------------- Make the course
                   9961:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9962:                       $course_server);
1.84      www      9963:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9964:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9965:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9966: 	return 'error: no such course';
                   9967:     }
1.271     www      9968: # ----------------------------------------------------------------- Course made
1.516     raeburn  9969: # log existence
1.1029    raeburn  9970:     my $now = time;
1.918     raeburn  9971:     my $newcourse = {
                   9972:                     $udom.'_'.$uname => {
1.921     raeburn  9973:                                      description => $description,
                   9974:                                      inst_code   => $inst_code,
                   9975:                                      owner       => $course_owner,
                   9976:                                      type        => $crstype,
1.1029    raeburn  9977:                                      creator     => $env{'user.name'}.':'.
                   9978:                                                     $env{'user.domain'},
                   9979:                                      created     => $now,
                   9980:                                      context     => $context,
1.918     raeburn  9981:                                                 },
                   9982:                     };
1.921     raeburn  9983:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9984: # set toplevel url
1.271     www      9985:     my $topurl=$url;
                   9986:     unless ($nonstandard) {
                   9987: # ------------------------------------------ For standard courses, make top url
                   9988:         my $mapurl=&clutter($url);
1.278     www      9989:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9990:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9991: <map>
                   9992: <resource id="1" type="start"></resource>
                   9993: <resource id="2" src="$mapurl"></resource>
                   9994: <resource id="3" type="finish"></resource>
                   9995: <link index="1" from="1" to="2"></link>
                   9996: <link index="2" from="2" to="3"></link>
                   9997: </map>
                   9998: ENDINITMAP
                   9999:         $topurl=&declutter(
1.638     albertel 10000:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10001:                           );
                   10002:     }
                   10003: # ----------------------------------------------------------- Write preferences
1.84      www      10004:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10005:                      ('description'              => $description,
                   10006:                       'url'                      => $topurl,
                   10007:                       'internal.creator'         => $env{'user.name'}.':'.
                   10008:                                                     $env{'user.domain'},
                   10009:                       'internal.created'         => $now,
                   10010:                       'internal.creationcontext' => $context)
                   10011:                     );
1.84      www      10012:     return '/'.$udom.'/'.$uname;
                   10013: }
                   10014: 
1.1011    raeburn  10015: # ------------------------------------------------------------------- Create ID
                   10016: sub generate_coursenum {
1.1038    raeburn  10017:     my ($udom,$crstype) = @_;
1.1011    raeburn  10018:     my $domdesc = &domain($udom);
                   10019:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10020:     my $first;
                   10021:     if ($crstype eq 'Community') {
                   10022:         $first = '0';
                   10023:     } else {
                   10024:         $first = int(1+rand(9)); 
                   10025:     } 
                   10026:     my $uname=$first.
1.1011    raeburn  10027:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10028:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10029:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10030: # ----------------------------------------------- Make sure that does not exist
                   10031:     my $uhome=&homeserver($uname,$udom,'true');
                   10032:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10033:         if ($crstype eq 'Community') {
                   10034:             $first = '0';
                   10035:         } else {
                   10036:             $first = int(1+rand(9));
                   10037:         }
                   10038:         $uname=$first.
1.1011    raeburn  10039:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10040:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10041:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10042:         $uhome=&homeserver($uname,$udom,'true');
                   10043:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10044:             return 'error: unable to generate unique course-ID';
                   10045:         }
                   10046:     }
                   10047:     return $uname;
                   10048: }
                   10049: 
1.813     albertel 10050: sub is_course {
1.1167    droeschl 10051:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10052:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10053: 
1.1381    raeburn  10054:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10055:     my $uhome=&homeserver($cnum,$cdom);
                   10056:     my $iscourse;
                   10057:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10058:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10059:     } else {
                   10060:         my $hashid = $cdom.':'.$cnum;
                   10061:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10062:         unless (defined($cached)) {
                   10063:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10064:                                         $cnum,undef,undef,'.');
                   10065:             $iscourse = 0;
                   10066:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10067:                 $iscourse = 1;
                   10068:             }
                   10069:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10070:         }
                   10071:     }
                   10072:     return unless ($iscourse);
1.1167    droeschl 10073:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10074: }
                   10075: 
1.1015    raeburn  10076: sub store_userdata {
                   10077:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10078:     my $result;
1.1016    raeburn  10079:     if ($datakey ne '') {
1.1013    raeburn  10080:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10081:             if ($udom eq '' || $uname eq '') {
                   10082:                 $udom = $env{'user.domain'};
                   10083:                 $uname = $env{'user.name'};
                   10084:             }
                   10085:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10086:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10087:                 $result = 'error: no_host';
                   10088:             } else {
                   10089:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10090:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10091: 
                   10092:                 my $namevalue='';
                   10093:                 foreach my $key (keys(%{$storehash})) {
                   10094:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10095:                 }
                   10096:                 $namevalue=~s/\&$//;
1.1224    raeburn  10097:                 unless ($namespace eq 'courserequests') {
                   10098:                     $datakey = &escape($datakey);
                   10099:                 }
1.1105    raeburn  10100:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10101:                                   $namevalue,$uhome);
1.1013    raeburn  10102:             }
                   10103:         } else {
                   10104:             $result = 'error: data to store was not a hash reference'; 
                   10105:         }
                   10106:     } else {
                   10107:         $result= 'error: invalid requestkey'; 
                   10108:     }
                   10109:     return $result;
                   10110: }
                   10111: 
1.21      www      10112: # ---------------------------------------------------------- Assign Custom Role
                   10113: 
                   10114: sub assigncustomrole {
1.957     raeburn  10115:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10116:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10117:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10118: }
                   10119: 
                   10120: # ----------------------------------------------------------------- Revoke Role
                   10121: 
                   10122: sub revokerole {
1.957     raeburn  10123:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10124:     my $now=time;
1.965     raeburn  10125:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10126: }
                   10127: 
                   10128: # ---------------------------------------------------------- Revoke Custom Role
                   10129: 
                   10130: sub revokecustomrole {
1.957     raeburn  10131:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10132:     my $now=time;
1.357     www      10133:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10134:            $deleteflag,$selfenroll,$context);
1.17      www      10135: }
                   10136: 
1.533     banghart 10137: # ------------------------------------------------------------ Disk usage
1.535     albertel 10138: sub diskusage {
1.955     raeburn  10139:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10140:     $directorypath =~ s/\/$//;
                   10141:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10142:                        .&escape($getpropath).':'.&escape($uname).':'
                   10143:                        .&escape($udom),homeserver($uname,$udom));
                   10144:     if ($listing eq 'unknown_cmd') {
                   10145:         if ($getpropath) {
                   10146:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10147:         }
                   10148:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10149:     }
1.514     albertel 10150:     return $listing;
1.512     banghart 10151: }
                   10152: 
1.566     banghart 10153: sub is_locked {
1.1096    raeburn  10154:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10155:     my @check;
                   10156:     my $is_locked;
1.1093    raeburn  10157:     push (@check,$file_name);
1.613     albertel 10158:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10159: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10160:     my ($tmp)=keys(%locked);
                   10161:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10162:     
1.566     banghart 10163:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10164:         $is_locked = 'false';
                   10165:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10166:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10167:                $is_locked = 'true';
1.1096    raeburn  10168:                if (ref($which) eq 'ARRAY') {
                   10169:                    push(@{$which},$entry);
                   10170:                } else {
                   10171:                    last;
                   10172:                }
1.745     raeburn  10173:            }
                   10174:        }
1.566     banghart 10175:     } else {
                   10176:         $is_locked = 'false';
                   10177:     }
1.1093    raeburn  10178:     return $is_locked;
1.566     banghart 10179: }
                   10180: 
1.759     albertel 10181: sub declutter_portfile {
                   10182:     my ($file) = @_;
1.833     albertel 10183:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10184:     return $file;
                   10185: }
                   10186: 
1.559     banghart 10187: # ------------------------------------------------------------- Mark as Read Only
                   10188: 
                   10189: sub mark_as_readonly {
                   10190:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10191:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10192:     my ($tmp)=keys(%current_permissions);
                   10193:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10194:     foreach my $file (@{$files}) {
1.759     albertel 10195: 	$file = &declutter_portfile($file);
1.561     banghart 10196:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10197:     }
1.613     albertel 10198:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10199:     return;
                   10200: }
                   10201: 
1.572     banghart 10202: # ------------------------------------------------------------Save Selected Files
                   10203: 
                   10204: sub save_selected_files {
                   10205:     my ($user, $path, @files) = @_;
                   10206:     my $filename = $user."savedfiles";
1.573     banghart 10207:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10208:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10209:     foreach my $file (@files) {
1.620     albertel 10210:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10211:     }
                   10212:     foreach my $file (@other_files) {
1.574     banghart 10213:         print (OUT $file."\n");
1.572     banghart 10214:     }
1.574     banghart 10215:     close (OUT);
1.572     banghart 10216:     return 'ok';
                   10217: }
                   10218: 
1.574     banghart 10219: sub clear_selected_files {
                   10220:     my ($user) = @_;
                   10221:     my $filename = $user."savedfiles";
1.1359    raeburn  10222:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10223:     print (OUT undef);
                   10224:     close (OUT);
                   10225:     return ("ok");    
                   10226: }
                   10227: 
1.572     banghart 10228: sub files_in_path {
                   10229:     my ($user, $path) = @_;
                   10230:     my $filename = $user."savedfiles";
                   10231:     my %return_files;
1.1359    raeburn  10232:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10233:     while (my $line_in = <IN>) {
1.574     banghart 10234:         chomp ($line_in);
                   10235:         my @paths_and_file = split (m!/!, $line_in);
                   10236:         my $file_part = pop (@paths_and_file);
                   10237:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10238:         $path_part.='/';
                   10239:         my $path_and_file = $path_part.$file_part;
                   10240:         if ($path_part eq $path) {
                   10241:             $return_files{$file_part}= 'selected';
                   10242:         }
                   10243:     }
1.574     banghart 10244:     close (IN);
                   10245:     return (\%return_files);
1.572     banghart 10246: }
                   10247: 
                   10248: # called in portfolio select mode, to show files selected NOT in current directory
                   10249: sub files_not_in_path {
                   10250:     my ($user, $path) = @_;
                   10251:     my $filename = $user."savedfiles";
                   10252:     my @return_files;
                   10253:     my $path_part;
1.1359    raeburn  10254:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10255:     while (my $line = <IN>) {
1.572     banghart 10256:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10257:         my @paths_and_file = split(m|/|, $line);
                   10258:         my $file_part = pop(@paths_and_file);
                   10259:         chomp($file_part);
                   10260:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10261:         $path_part .= '/';
                   10262:         my $path_and_file = $path_part.$file_part;
                   10263:         if ($path_part ne $path) {
1.800     albertel 10264:             push(@return_files, ($path_and_file));
1.572     banghart 10265:         }
                   10266:     }
1.800     albertel 10267:     close(OUT);
1.574     banghart 10268:     return (@return_files);
1.572     banghart 10269: }
                   10270: 
1.1273    raeburn  10271: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10272:  
                   10273: sub portfiles_versioning {
                   10274:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10275:     my $portfolio_root = '/userfiles/portfolio';
                   10276:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10277:     foreach my $file (@{$portfiles}) {
                   10278:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10279:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10280:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10281:         my $getpropath = 1;
                   10282:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10283:                                              $stu_name,$getpropath);
                   10284:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10285:         my $new_answer = 
                   10286:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10287:         if ($new_answer ne 'problem getting file') {
                   10288:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10289:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10290:                               [$symb,$env{'request.course.id'},'graded']);
                   10291:         }
                   10292:     }
                   10293: }
                   10294: 
                   10295: sub get_next_version {
                   10296:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10297:     my $version;
                   10298:     if (ref($dir_list) eq 'ARRAY') {
                   10299:         foreach my $row (@{$dir_list}) {
                   10300:             my ($file) = split(/\&/,$row,2);
                   10301:             my ($file_name,$file_version,$file_ext) =
                   10302:                 &file_name_version_ext($file);
                   10303:             if (($file_name eq $answer_name) &&
                   10304:                 ($file_ext eq $answer_ext)) {
                   10305:                      # gets here if filename and extension match,
                   10306:                      # regardless of version
                   10307:                 if ($file_version ne '') {
                   10308:                     # a versioned file is found  so save it for later
                   10309:                     if ($file_version > $version) {
                   10310:                         $version = $file_version;
                   10311:                     }
                   10312:                 }
                   10313:             }
                   10314:         }
                   10315:     }
                   10316:     $version ++;
                   10317:     return($version);
                   10318: }
                   10319: 
                   10320: sub version_selected_portfile {
                   10321:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10322:     my ($answer_name,$answer_ver,$answer_ext) =
                   10323:         &file_name_version_ext($file_name);
                   10324:     my $new_answer;
                   10325:     $env{'form.copy'} =
                   10326:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10327:     if($env{'form.copy'} eq '-1') {
                   10328:         $new_answer = 'problem getting file';
                   10329:     } else {
                   10330:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10331:         my $copy_result = 
                   10332:             &finishuserfileupload($stu_name,$domain,'copy',
                   10333:                                   '/portfolio'.$directory.$new_answer);
                   10334:     }
                   10335:     undef($env{'form.copy'});
                   10336:     return ($new_answer);
                   10337: }
                   10338: 
                   10339: sub file_name_version_ext {
                   10340:     my ($file)=@_;
                   10341:     my @file_parts = split(/\./, $file);
                   10342:     my ($name,$version,$ext);
                   10343:     if (@file_parts > 1) {
                   10344:         $ext=pop(@file_parts);
                   10345:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10346:             $version=pop(@file_parts);
                   10347:         }
                   10348:         $name=join('.',@file_parts);
                   10349:     } else {
                   10350:         $name=join('.',@file_parts);
                   10351:     }
                   10352:     return($name,$version,$ext);
                   10353: }
                   10354: 
1.745     raeburn  10355: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10356: 
1.745     raeburn  10357: sub get_portfile_permissions {
                   10358:     my ($domain,$user) = @_;
1.613     albertel 10359:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10360:     my ($tmp)=keys(%current_permissions);
                   10361:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10362:     return \%current_permissions;
                   10363: }
                   10364: 
                   10365: #---------------------------------------------Get portfolio file access controls
                   10366: 
1.749     raeburn  10367: sub get_access_controls {
1.745     raeburn  10368:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10369:     my %access;
                   10370:     my $real_file = $file;
                   10371:     $file =~ s/\.meta$//;
1.745     raeburn  10372:     if (defined($file)) {
1.749     raeburn  10373:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10374:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10375:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10376:             }
                   10377:         }
1.745     raeburn  10378:     } else {
1.749     raeburn  10379:         foreach my $key (keys(%{$current_permissions})) {
                   10380:             if ($key =~ /\0accesscontrol$/) {
                   10381:                 if (defined($group)) {
                   10382:                     if ($key !~ m-^\Q$group\E/-) {
                   10383:                         next;
                   10384:                     }
                   10385:                 }
                   10386:                 my ($fullpath) = split(/\0/,$key);
                   10387:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10388:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10389:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10390:                     }
                   10391:                 }
                   10392:             }
                   10393:         }
                   10394:     }
                   10395:     return %access;
                   10396: }
                   10397: 
                   10398: sub modify_access_controls {
                   10399:     my ($file_name,$changes,$domain,$user)=@_;
                   10400:     my ($outcome,$deloutcome);
                   10401:     my %store_permissions;
                   10402:     my %new_values;
                   10403:     my %new_control;
                   10404:     my %translation;
                   10405:     my @deletions = ();
                   10406:     my $now = time;
                   10407:     if (exists($$changes{'activate'})) {
                   10408:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10409:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10410:             my $numnew = scalar(@newitems);
                   10411:             for (my $i=0; $i<$numnew; $i++) {
                   10412:                 my $newkey = $newitems[$i];
                   10413:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10414:                 if ($newkey =~ /^\d+:/) { 
                   10415:                     $newkey =~ s/^(\d+)/$newid/;
                   10416:                     $translation{$1} = $newid;
                   10417:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10418:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10419:                     $translation{$1} = $newid;
                   10420:                 }
1.749     raeburn  10421:                 $new_values{$file_name."\0".$newkey} = 
                   10422:                                           $$changes{'activate'}{$newitems[$i]};
                   10423:                 $new_control{$newkey} = $now;
                   10424:             }
                   10425:         }
                   10426:     }
                   10427:     my %todelete;
                   10428:     my %changed_items;
                   10429:     foreach my $action ('delete','update') {
                   10430:         if (exists($$changes{$action})) {
                   10431:             if (ref($$changes{$action}) eq 'HASH') {
                   10432:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10433:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10434:                     if ($action eq 'delete') { 
                   10435:                         $todelete{$itemnum} = 1;
                   10436:                     } else {
                   10437:                         $changed_items{$itemnum} = $key;
                   10438:                     }
                   10439:                 }
1.745     raeburn  10440:             }
                   10441:         }
1.749     raeburn  10442:     }
                   10443:     # get lock on access controls for file.
                   10444:     my $lockhash = {
                   10445:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10446:                                                        ':'.$env{'user.domain'},
                   10447:                    }; 
                   10448:     my $tries = 0;
                   10449:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10450:    
1.1288    damieng  10451:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10452:         $tries ++;
1.1289    damieng  10453:         sleep(0.1);
1.749     raeburn  10454:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10455:     }
                   10456:     if ($gotlock eq 'ok') {
                   10457:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10458:         my ($tmp)=keys(%curr_permissions);
                   10459:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10460:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10461:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10462:             if (ref($curr_controls) eq 'HASH') {
                   10463:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10464:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10465:                     if (defined($todelete{$itemnum})) {
                   10466:                         push(@deletions,$file_name."\0".$control_item);
                   10467:                     } else {
                   10468:                         if (defined($changed_items{$itemnum})) {
                   10469:                             $new_control{$changed_items{$itemnum}} = $now;
                   10470:                             push(@deletions,$file_name."\0".$control_item);
                   10471:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10472:                         } else {
                   10473:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10474:                         }
                   10475:                     }
1.745     raeburn  10476:                 }
                   10477:             }
                   10478:         }
1.970     raeburn  10479:         my ($group);
                   10480:         if (&is_course($domain,$user)) {
                   10481:             ($group,my $file) = split(/\//,$file_name,2);
                   10482:         }
1.749     raeburn  10483:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10484:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10485:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10486:         #  remove lock
                   10487:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10488:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10489:         my $sqlresult =
1.970     raeburn  10490:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10491:                                     $group);
1.749     raeburn  10492:     } else {
                   10493:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10494:     }
1.749     raeburn  10495:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10496: }
                   10497: 
1.827     raeburn  10498: sub make_public_indefinitely {
1.1271    raeburn  10499:     my (@requrl) = @_;
                   10500:     return &automated_portfile_access('public',\@requrl);
                   10501: }
                   10502: 
                   10503: sub automated_portfile_access {
                   10504:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10505:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10506:         return 'invalid';
                   10507:     }
1.1271    raeburn  10508:     my %urls;
                   10509:     if (ref($addsref) eq 'ARRAY') {
                   10510:         foreach my $requrl (@{$addsref}) {
                   10511:             if (&is_portfolio_url($requrl)) {
                   10512:                 unless (exists($urls{$requrl})) {
                   10513:                     $urls{$requrl} = 'add';
                   10514:                 }
                   10515:             }
                   10516:         }
                   10517:     }
                   10518:     if (ref($delsref) eq 'ARRAY') {
                   10519:         foreach my $requrl (@{$delsref}) { 
                   10520:             if (&is_portfolio_url($requrl)) {
                   10521:                 unless (exists($urls{$requrl})) {
                   10522:                     $urls{$requrl} = 'delete'; 
                   10523:                 }
                   10524:             }
                   10525:         }
                   10526:     }
                   10527:     unless (keys(%urls)) {
                   10528:         return 'invalid';
                   10529:     }
                   10530:     my $ip;
                   10531:     if ($accesstype eq 'ip') {
                   10532:         if (ref($info) eq 'HASH') {
                   10533:             if ($info->{'ip'} ne '') {
                   10534:                 $ip = $info->{'ip'};
                   10535:             }
                   10536:         }
                   10537:         if ($ip eq '') {
                   10538:             return 'invalid';
                   10539:         }
                   10540:     }
                   10541:     my $errors;
1.827     raeburn  10542:     my $now = time;
1.1271    raeburn  10543:     my %current_perms;
                   10544:     foreach my $requrl (sort(keys(%urls))) {
                   10545:         my $action;
                   10546:         if ($urls{$requrl} eq 'add') {
                   10547:             $action = 'activate';
                   10548:         } else {
                   10549:             $action = 'none';
                   10550:         }
                   10551:         my $aclnum = 0;
1.827     raeburn  10552:         my (undef,$udom,$unum,$file_name,$group) =
                   10553:             &parse_portfolio_url($requrl);
1.1271    raeburn  10554:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10555:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10556:         }
                   10557:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10558:                                                    $group,$file_name);
                   10559:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10560:             my ($num,$scope,$end,$start) = 
                   10561:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10562:             if ($scope eq $accesstype) {
                   10563:                 if (($start <= $now) && ($end == 0)) {
                   10564:                     if ($accesstype eq 'ip') {
                   10565:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10566:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10567:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10568:                                     if ($urls{$requrl} eq 'add') {
                   10569:                                         $action = 'none';
                   10570:                                         last;
                   10571:                                     } else {
                   10572:                                         $action = 'delete';
                   10573:                                         $aclnum = $num;
                   10574:                                         last;
                   10575:                                     }
                   10576:                                 }
                   10577:                             }
                   10578:                         }
                   10579:                     } elsif ($accesstype eq 'public') {
                   10580:                         if ($urls{$requrl} eq 'add') {
                   10581:                             $action = 'none';
                   10582:                             last;
                   10583:                         } else {
                   10584:                             $action = 'delete';
                   10585:                             $aclnum = $num;
                   10586:                             last;
                   10587:                         }
                   10588:                     }
                   10589:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10590:                     $action = 'update';
                   10591:                     $aclnum = $num;
1.1271    raeburn  10592:                     last;
1.827     raeburn  10593:                 }
                   10594:             }
                   10595:         }
                   10596:         if ($action eq 'none') {
1.1271    raeburn  10597:             next;
1.827     raeburn  10598:         } else {
                   10599:             my %changes;
                   10600:             my $newend = 0;
                   10601:             my $newstart = $now;
1.1271    raeburn  10602:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10603:             $changes{$action}{$newkey} = {
1.1271    raeburn  10604:                 type => $accesstype,
1.827     raeburn  10605:                 time => {
                   10606:                     start => $newstart,
                   10607:                     end   => $newend,
                   10608:                 },
                   10609:             };
1.1271    raeburn  10610:             if ($accesstype eq 'ip') {
                   10611:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10612:             }
1.827     raeburn  10613:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10614:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10615:             unless ($outcome eq 'ok') {
                   10616:                 $errors .= $outcome.' ';
                   10617:             }
1.827     raeburn  10618:         }
1.1271    raeburn  10619:     }
                   10620:     if ($errors) {
                   10621:         $errors =~ s/\s$//;
                   10622:         return $errors;
1.827     raeburn  10623:     } else {
1.1271    raeburn  10624:         return 'ok';
1.827     raeburn  10625:     }
                   10626: }
                   10627: 
1.745     raeburn  10628: #------------------------------------------------------Get Marked as Read Only
                   10629: 
                   10630: sub get_marked_as_readonly {
                   10631:     my ($domain,$user,$what,$group) = @_;
                   10632:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10633:     my @readonly_files;
1.629     banghart 10634:     my $cmp1=$what;
                   10635:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10636:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10637:         if (defined($group)) {
                   10638:             if ($file_name !~ m-^\Q$group\E/-) {
                   10639:                 next;
                   10640:             }
                   10641:         }
1.561     banghart 10642:         if (ref($value) eq "ARRAY"){
                   10643:             foreach my $stored_what (@{$value}) {
1.629     banghart 10644:                 my $cmp2=$stored_what;
1.759     albertel 10645:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10646:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10647:                 }
1.629     banghart 10648:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10649:                     push(@readonly_files, $file_name);
1.745     raeburn  10650:                     last;
1.563     banghart 10651:                 } elsif (!defined($what)) {
                   10652:                     push(@readonly_files, $file_name);
1.745     raeburn  10653:                     last;
1.561     banghart 10654:                 }
                   10655:             }
1.745     raeburn  10656:         }
1.561     banghart 10657:     }
                   10658:     return @readonly_files;
                   10659: }
1.577     banghart 10660: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10661: 
1.577     banghart 10662: sub get_marked_as_readonly_hash {
1.745     raeburn  10663:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10664:     my %readonly_files;
1.745     raeburn  10665:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10666:         if (defined($group)) {
                   10667:             if ($file_name !~ m-^\Q$group\E/-) {
                   10668:                 next;
                   10669:             }
                   10670:         }
1.577     banghart 10671:         if (ref($value) eq "ARRAY"){
                   10672:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10673:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10674:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10675:                         if ($lock_descriptor eq 'graded') {
                   10676:                             $readonly_files{$file_name} = 'graded';
                   10677:                         } elsif ($lock_descriptor eq 'handback') {
                   10678:                             $readonly_files{$file_name} = 'handback';
                   10679:                         } else {
                   10680:                             if (!exists($readonly_files{$file_name})) {
                   10681:                                 $readonly_files{$file_name} = 'locked';
                   10682:                             }
                   10683:                         }
1.745     raeburn  10684:                     }
1.750     banghart 10685:                 } 
1.577     banghart 10686:             }
                   10687:         } 
                   10688:     }
                   10689:     return %readonly_files;
                   10690: }
1.559     banghart 10691: # ------------------------------------------------------------ Unmark as Read Only
                   10692: 
                   10693: sub unmark_as_readonly {
1.629     banghart 10694:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10695:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10696:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10697:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10698:     my $symb_crs = $what;
                   10699:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10700:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10701:     my ($tmp)=keys(%current_permissions);
                   10702:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10703:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10704:     foreach my $file (@readonly_files) {
1.759     albertel 10705: 	my $clean_file = &declutter_portfile($file);
                   10706: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10707: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10708:         my @new_locks;
                   10709:         my @del_keys;
                   10710:         if (ref($current_locks) eq "ARRAY"){
                   10711:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10712:                 my $compare=$locker;
1.749     raeburn  10713:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10714:                     $compare=join('',@{$locker});
1.746     raeburn  10715:                     if ($compare ne $symb_crs) {
                   10716:                         push(@new_locks, $locker);
                   10717:                     }
1.563     banghart 10718:                 }
                   10719:             }
1.650     albertel 10720:             if (scalar(@new_locks) > 0) {
1.563     banghart 10721:                 $current_permissions{$file} = \@new_locks;
                   10722:             } else {
                   10723:                 push(@del_keys, $file);
1.613     albertel 10724:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10725:                 delete($current_permissions{$file});
1.563     banghart 10726:             }
                   10727:         }
1.561     banghart 10728:     }
1.613     albertel 10729:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10730:     return;
                   10731: }
1.512     banghart 10732: 
1.17      www      10733: # ------------------------------------------------------------ Directory lister
                   10734: 
                   10735: sub dirlist {
1.955     raeburn  10736:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10737:     $uri=~s/^\///;
                   10738:     $uri=~s/\/$//;
1.253     stredwic 10739:     my ($udom, $uname);
1.955     raeburn  10740:     if ($getuserdir) {
1.253     stredwic 10741:         $udom = $userdomain;
                   10742:         $uname = $username;
1.955     raeburn  10743:     } else {
                   10744:         (undef,$udom,$uname)=split(/\//,$uri);
                   10745:         if(defined($userdomain)) {
                   10746:             $udom = $userdomain;
                   10747:         }
                   10748:         if(defined($username)) {
                   10749:             $uname = $username;
                   10750:         }
1.253     stredwic 10751:     }
1.955     raeburn  10752:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10753: 
1.955     raeburn  10754:     $dirRoot = $perlvar{'lonDocRoot'};
                   10755:     if (defined($getpropath)) {
                   10756:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10757:         $dirRoot =~ s/\/$//;
1.955     raeburn  10758:     } elsif (defined($getuserdir)) {
                   10759:         my $subdir=$uname.'__';
                   10760:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10761:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10762:                    ."/$udom/$subdir/$uname";
                   10763:     } elsif (defined($alternateRoot)) {
                   10764:         $dirRoot = $alternateRoot;
1.751     banghart 10765:     }
1.253     stredwic 10766: 
                   10767:     if($udom) {
                   10768:         if($uname) {
1.1135    raeburn  10769:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10770:             if ($uhome eq 'no_host') {
                   10771:                 return ([],'no_host');
                   10772:             }
1.955     raeburn  10773:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10774:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10775:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10776:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10777:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10778:             } else {
                   10779:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10780:             }
1.605     matthew  10781:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10782:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10783:                 @listing_results = split(/:/,$listing);
                   10784:             } else {
                   10785:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10786:             }
1.1135    raeburn  10787:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10788:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10789:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10790:                 return ([],$listing);
                   10791:             } else {
                   10792:                 return (\@listing_results);
1.1135    raeburn  10793:             }
1.955     raeburn  10794:         } elsif(!$alternateRoot) {
1.1136    raeburn  10795:             my (%allusers,%listerror);
1.841     albertel 10796: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10797:  	    foreach my $tryserver (keys(%servers)) {
                   10798:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10799:                                   &escape($udom),$tryserver);
                   10800:                 if ($listing eq 'unknown_cmd') {
                   10801: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10802: 				      $udom, $tryserver);
                   10803:                 } else {
                   10804:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10805:                 }
1.841     albertel 10806: 		if ($listing eq 'unknown_cmd') {
                   10807: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10808: 				      $udom, $tryserver);
                   10809: 		    @listing_results = split(/:/,$listing);
                   10810: 		} else {
                   10811: 		    @listing_results =
                   10812: 			map { &unescape($_); } split(/:/,$listing);
                   10813: 		}
1.1136    raeburn  10814:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10815:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10816:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10817:                     $listerror{$tryserver} = $listing;
                   10818:                 } else {
1.841     albertel 10819: 		    foreach my $line (@listing_results) {
                   10820: 			my ($entry) = split(/&/,$line,2);
                   10821: 			$allusers{$entry} = 1;
                   10822: 		    }
                   10823: 		}
1.253     stredwic 10824:             }
1.1136    raeburn  10825:             my @alluserslist=();
1.800     albertel 10826:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10827:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10828:             }
1.1318    droeschl 10829: 
                   10830:             if (!%listerror) {
                   10831:                 # no errors
                   10832:                 return (\@alluserslist);
                   10833:             } elsif (scalar(keys(%servers)) == 1) {
                   10834:                 # one library server, one error 
                   10835:                 my ($key) = keys(%listerror);
                   10836:                 return (\@alluserslist, $listerror{$key});
                   10837:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10838:                 # con_lost indicates that we might miss data from at least one
                   10839:                 # library server
                   10840:                 return (\@alluserslist, 'con_lost');
                   10841:             } else {
                   10842:                 # multiple library servers and no con_lost -> data should be
                   10843:                 # complete. 
                   10844:                 return (\@alluserslist);
                   10845:             }
                   10846: 
1.253     stredwic 10847:         } else {
1.1136    raeburn  10848:             return ([],'missing username');
1.253     stredwic 10849:         }
1.955     raeburn  10850:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10851:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10852:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10853:         return (\@all_domains);
1.955     raeburn  10854:     } else {
1.1136    raeburn  10855:         return ([],'missing domain');
1.275     stredwic 10856:     }
                   10857: }
                   10858: 
                   10859: # --------------------------------------------- GetFileTimestamp
                   10860: # This function utilizes dirlist and returns the date stamp for
                   10861: # when it was last modified.  It will also return an error of -1
                   10862: # if an error occurs
                   10863: 
                   10864: sub GetFileTimestamp {
1.955     raeburn  10865:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10866:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10867:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10868:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10869:                                     undef,$getuserdir);
                   10870:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10871:         return -1;
                   10872:     }
                   10873:     if (ref($fileref) eq 'ARRAY') {
                   10874:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10875:         # @stats contains first the filename, then the stat output
                   10876:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10877:     } else {
                   10878:         return -1;
1.253     stredwic 10879:     }
1.26      www      10880: }
                   10881: 
1.712     albertel 10882: sub stat_file {
                   10883:     my ($uri) = @_;
1.787     albertel 10884:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10885: 
1.955     raeburn  10886:     my ($udom,$uname,$file);
1.712     albertel 10887:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10888: 	($udom,$uname,$file) =
1.811     albertel 10889: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10890: 	$file = 'userfiles/'.$file;
                   10891:     }
                   10892:     if ($uri =~ m-^/res/-) {
                   10893: 	($udom,$uname) = 
1.807     albertel 10894: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10895: 	$file = $uri;
                   10896:     }
                   10897: 
                   10898:     if (!$udom || !$uname || !$file) {
                   10899: 	# unable to handle the uri
                   10900: 	return ();
                   10901:     }
1.956     raeburn  10902:     my $getpropath;
                   10903:     if ($file =~ /^userfiles\//) {
                   10904:         $getpropath = 1;
                   10905:     }
1.1136    raeburn  10906:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10907:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10908:         return ();
                   10909:     } else {
                   10910:         if (ref($listref) eq 'ARRAY') {
                   10911:             my @stats = split('&',$listref->[0]);
                   10912: 	    shift(@stats); #filename is first
                   10913: 	    return @stats;
                   10914:         }
1.712     albertel 10915:     }
                   10916:     return ();
                   10917: }
                   10918: 
1.1313    raeburn  10919: # --------------------------------------------------------- recursedirs
                   10920: # Recursive function to traverse either a specific user's Authoring Space
                   10921: # or corresponding Published Resource Space, and populate the hash ref:
                   10922: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10923: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10924: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10925: # files in Authoring Space.
                   10926: #
                   10927: # Inputs:
                   10928: #
                   10929: # $is_home - true if current server is home server for user's space
                   10930: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10931: # $docroot - Document root (i.e., /home/httpd/html
                   10932: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10933: # $relpath - Current path (relative to top level).
                   10934: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10935: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10936: #
                   10937: # Returns: nothing
                   10938: #
                   10939: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10940: #
                   10941: # Currently used by interface/londocs.pm to create linked select boxes for
                   10942: # directory and filename to import a Course "Author" resource into a course, and
                   10943: # also to create linked select boxes for Authoring Space and Directory to choose
                   10944: # save location for creation of a new "standard" problem from the Course Editor.
                   10945: #
                   10946: 
                   10947: sub recursedirs {
                   10948:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10949:     return unless (ref($dirhashref) eq 'HASH');
                   10950:     my $currpath = $docroot.$toppath;
                   10951:     if ($relpath) {
                   10952:         $currpath .= "/$relpath";
                   10953:     }
                   10954:     my $savefile;
                   10955:     if (ref($filehashref)) {
                   10956:         $savefile = 1;
                   10957:     }
                   10958:     if ($is_home) {
                   10959:         if (opendir(my $dirh,$currpath)) {
                   10960:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10961:                 next if ($item eq '');
                   10962:                 if (-d "$currpath/$item") {
                   10963:                     my $newpath;
                   10964:                     if ($relpath) {
                   10965:                         $newpath = "$relpath/$item";
                   10966:                     } else {
                   10967:                         $newpath = $item;
                   10968:                     }
                   10969:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10970:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10971:                 } elsif ($savefile) {
                   10972:                     if ($context eq 'priv') {
                   10973:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10974:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10975:                         }
                   10976:                     } else {
                   10977:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10978:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10979:                         }
                   10980:                     }
                   10981:                 }
                   10982:             }
                   10983:             closedir($dirh);
                   10984:         }
                   10985:     } else {
                   10986:         my ($dirlistref,$listerror) =
                   10987:             &dirlist($toppath.$relpath);
                   10988:         my @dir_lines;
                   10989:         my $dirptr=16384;
                   10990:         if (ref($dirlistref) eq 'ARRAY') {
                   10991:             foreach my $dir_line (sort
                   10992:                               {
                   10993:                                   my ($afile)=split('&',$a,2);
                   10994:                                   my ($bfile)=split('&',$b,2);
                   10995:                                   return (lc($afile) cmp lc($bfile));
                   10996:                               } (@{$dirlistref})) {
                   10997:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10998:                     split(/\&/,$dir_line,16);
                   10999:                 $item =~ s/\s+$//;
                   11000:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11001:                 if ($dirptr&$testdir) {
                   11002:                     my $newpath;
                   11003:                     if ($relpath) {
                   11004:                         $newpath = "$relpath/$item";
                   11005:                     } else {
                   11006:                         $relpath = '/';
                   11007:                         $newpath = $item;
                   11008:                     }
                   11009:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11010:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11011:                 } elsif ($savefile) {
                   11012:                     if ($context eq 'priv') {
                   11013:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11014:                             $filehashref->{$relpath}{$item} = 1;
                   11015:                         }
                   11016:                     } else {
                   11017:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11018:                             $filehashref->{$relpath}{$item} = 1;
                   11019:                         }
                   11020:                     }
                   11021:                 }
                   11022:             }
                   11023:         }
                   11024:     }
                   11025:     return;
                   11026: }
                   11027: 
1.26      www      11028: # -------------------------------------------------------- Value of a Condition
                   11029: 
1.713     albertel 11030: # gets the value of a specific preevaluated condition
                   11031: #    stored in the string  $env{user.state.<cid>}
                   11032: # or looks up a condition reference in the bighash and if if hasn't
                   11033: # already been evaluated recurses into docondval to get the value of
                   11034: # the condition, then memoizing it to 
                   11035: #   $env{user.state.<cid>.<condition>}
1.40      www      11036: sub directcondval {
                   11037:     my $number=shift;
1.620     albertel 11038:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11039: 	&Apache::lonuserstate::evalstate();
                   11040:     }
1.713     albertel 11041:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11042: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11043:     } elsif ($number =~ /^_/) {
                   11044: 	my $sub_condition;
                   11045: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11046: 		&GDBM_READER(),0640)) {
                   11047: 	    $sub_condition=$bighash{'conditions'.$number};
                   11048: 	    untie(%bighash);
                   11049: 	}
                   11050: 	my $value = &docondval($sub_condition);
1.949     raeburn  11051: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11052: 	return $value;
                   11053:     }
1.620     albertel 11054:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11055:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11056:     } else {
                   11057:        return 2;
                   11058:     }
                   11059: }
                   11060: 
1.713     albertel 11061: # get the collection of conditions for this resource
1.26      www      11062: sub condval {
                   11063:     my $condidx=shift;
1.54      www      11064:     my $allpathcond='';
1.713     albertel 11065:     foreach my $cond (split(/\|/,$condidx)) {
                   11066: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11067: 	    $allpathcond.=
                   11068: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11069: 	}
1.191     harris41 11070:     }
1.54      www      11071:     $allpathcond=~s/\|$//;
1.713     albertel 11072:     return &docondval($allpathcond);
                   11073: }
                   11074: 
                   11075: #evaluates an expression of conditions
                   11076: sub docondval {
                   11077:     my ($allpathcond) = @_;
                   11078:     my $result=0;
                   11079:     if ($env{'request.course.id'}
                   11080: 	&& defined($allpathcond)) {
                   11081: 	my $operand='|';
                   11082: 	my @stack;
                   11083: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11084: 	    if ($chunk eq '(') {
                   11085: 		push @stack,($operand,$result);
                   11086: 	    } elsif ($chunk eq ')') {
                   11087: 		my $before=pop @stack;
                   11088: 		if (pop @stack eq '&') {
                   11089: 		    $result=$result>$before?$before:$result;
                   11090: 		} else {
                   11091: 		    $result=$result>$before?$result:$before;
                   11092: 		}
                   11093: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11094: 		$operand=$chunk;
                   11095: 	    } else {
                   11096: 		my $new=directcondval($chunk);
                   11097: 		if ($operand eq '&') {
                   11098: 		    $result=$result>$new?$new:$result;
                   11099: 		} else {
                   11100: 		    $result=$result>$new?$result:$new;
                   11101: 		}
                   11102: 	    }
                   11103: 	}
1.26      www      11104:     }
                   11105:     return $result;
1.421     albertel 11106: }
                   11107: 
                   11108: # ---------------------------------------------------- Devalidate courseresdata
                   11109: 
                   11110: sub devalidatecourseresdata {
                   11111:     my ($coursenum,$coursedomain)=@_;
                   11112:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11113:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11114: }
                   11115: 
1.763     www      11116: 
1.200     www      11117: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11118: #
                   11119: #  Parameters:
                   11120: #      $coursenum    - Number of the course.
                   11121: #      $coursedomain - Domain at which the course was created.
                   11122: #  Returns:
                   11123: #     A hash of the course parameters along (I think) with timestamps
                   11124: #     and version info.
1.877     foxr     11125: 
1.624     albertel 11126: sub get_courseresdata {
                   11127:     my ($coursenum,$coursedomain)=@_;
1.200     www      11128:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11129:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11130:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11131:     my %dumpreply;
1.417     albertel 11132:     unless (defined($cached)) {
1.624     albertel 11133: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11134: 	$result=\%dumpreply;
1.251     albertel 11135: 	my ($tmp) = keys(%dumpreply);
                   11136: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11137: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11138: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11139: 	    return $tmp;
1.416     albertel 11140: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11141: 	    $result=undef;
1.599     albertel 11142: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11143: 	}
                   11144:     }
1.624     albertel 11145:     return $result;
                   11146: }
                   11147: 
1.633     albertel 11148: sub devalidateuserresdata {
                   11149:     my ($uname,$udom)=@_;
                   11150:     my $hashid="$udom:$uname";
                   11151:     &devalidate_cache_new('userres',$hashid);
                   11152: }
                   11153: 
1.624     albertel 11154: sub get_userresdata {
                   11155:     my ($uname,$udom)=@_;
                   11156:     #most student don\'t have any data set, check if there is some data
                   11157:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11158: 
                   11159:     my $hashid="$udom:$uname";
                   11160:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11161:     if (!defined($cached)) {
                   11162: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11163: 	$result=\%resourcedata;
                   11164: 	&do_cache_new('userres',$hashid,$result,600);
                   11165:     }
                   11166:     my ($tmp)=keys(%$result);
                   11167:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11168: 	return $result;
                   11169:     }
                   11170:     #error 2 occurs when the .db doesn't exist
                   11171:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11172:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11173: 	    &logthis("<font color=\"blue\">WARNING:".
                   11174: 		     " Trying to get resource data for ".
                   11175: 		     $uname." at ".$udom.": ".
                   11176: 		     $tmp."</font>");
                   11177:         }
1.624     albertel 11178:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11179: 	#&EXT_cache_set($udom,$uname);
                   11180: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11181: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11182:     }
                   11183:     return $tmp;
                   11184: }
1.879     foxr     11185: #----------------------------------------------- resdata - return resource data
                   11186: #  Purpose:
                   11187: #    Return resource data for either users or for a course.
                   11188: #  Parameters:
                   11189: #     $name      - Course/user name.
                   11190: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11191: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11192: #     $mapp      - decluttered URL of enclosing map  
                   11193: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11194: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11195: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11196: #     $courseid  - CourseID (first part of param identifier).
                   11197: #     $modifier  - Middle part of param identifier.
                   11198: #     $what      - Last part of param identifier.
1.879     foxr     11199: #     @which     - Array of names of resources desired.
                   11200: #  Returns:
                   11201: #     The value of the first reasource in @which that is found in the
                   11202: #     resource hash.
                   11203: #  Exceptional Conditions:
                   11204: #     If the $type passed in is not valid (not the string 'course' or 
                   11205: #     'user', an undefined  reference is returned.
                   11206: #     If none of the resources are found, an undef is returned
1.624     albertel 11207: sub resdata {
1.1301    raeburn  11208:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11209:         $modifier,$what,@which)=@_;
1.624     albertel 11210:     my $result;
                   11211:     if ($type eq 'course') {
                   11212: 	$result=&get_courseresdata($name,$domain);
                   11213:     } elsif ($type eq 'user') {
                   11214: 	$result=&get_userresdata($name,$domain);
                   11215:     }
                   11216:     if (!ref($result)) { return $result; }    
1.251     albertel 11217:     foreach my $item (@which) {
1.1301    raeburn  11218:         if ($item->[1] eq 'course') {
                   11219:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11220:                 unless ($$recursed) {
1.1302    raeburn  11221:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11222:                     $$recursed = 1;
                   11223:                 }
                   11224:                 foreach my $item (@${recurseup}) {
                   11225:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11226:                     last if (defined($result->{$norecursechk}));
                   11227:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11228:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11229:                 }
                   11230:             }
                   11231:         }
                   11232:         if (defined($result->{$item->[0]})) {
1.927     albertel 11233: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11234: 	}
1.250     albertel 11235:     }
1.291     albertel 11236:     return undef;
1.200     www      11237: }
                   11238: 
1.1360    raeburn  11239: sub get_domain_lti {
                   11240:     my ($cdom,$context) = @_;
                   11241:     my ($name,%lti);
                   11242:     if ($context eq 'consumer') {
                   11243:         $name = 'ltitools';
                   11244:     } elsif ($context eq 'provider') {
                   11245:         $name = 'lti';
                   11246:     } else {
                   11247:         return %lti;
                   11248:     }
                   11249:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11250:     if (defined($cached)) {
                   11251:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11252:             %lti = %{$result};
1.1298    raeburn  11253:         }
                   11254:     } else {
1.1360    raeburn  11255:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11256:         if (ref($domconfig{$name}) eq 'HASH') {
                   11257:             %lti = %{$domconfig{$name}};
                   11258:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11259:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11260:                 foreach my $id (keys(%lti)) {
                   11261:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11262:                         foreach my $item ('key','secret') {
1.1360    raeburn  11263:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11264:                         }
                   11265:                     }
                   11266:                 }
                   11267:             }
1.1298    raeburn  11268:         }
                   11269:         my $cachetime = 24*60*60;
1.1360    raeburn  11270:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11271:     }
1.1360    raeburn  11272:     return %lti;
1.1298    raeburn  11273: }
                   11274: 
1.1236    raeburn  11275: sub get_numsuppfiles {
                   11276:     my ($cnum,$cdom,$ignorecache)=@_;
                   11277:     my $hashid=$cnum.':'.$cdom;
                   11278:     my ($suppcount,$cached);
                   11279:     unless ($ignorecache) {
                   11280:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11281:     }
                   11282:     unless (defined($cached)) {
                   11283:         my $chome=&homeserver($cnum,$cdom);
                   11284:         unless ($chome eq 'no_host') {
1.1366    raeburn  11285:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11286:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11287:             ($suppcount,$supptools,$errors) =
                   11288:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11289:                                                          $supptools,$errors);
1.1236    raeburn  11290:         }
                   11291:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11292:     }
                   11293:     return $suppcount;
                   11294: }
                   11295: 
1.379     matthew  11296: #
                   11297: # EXT resource caching routines
                   11298: #
                   11299: 
1.1302    raeburn  11300: {
                   11301: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11302: #
                   11303: # The course for which we cache
                   11304: my $cachedmapkey='';
                   11305: # The cached recursive maps for this course
                   11306: my %cachedmaps=();
                   11307: # When this was last done
                   11308: my $cachedmaptime='';
                   11309: 
1.379     matthew  11310: sub clear_EXT_cache_status {
1.383     albertel 11311:     &delenv('cache.EXT.');
1.379     matthew  11312: }
                   11313: 
                   11314: sub EXT_cache_status {
                   11315:     my ($target_domain,$target_user) = @_;
1.383     albertel 11316:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11317:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11318:         # We know already the user has no data
                   11319:         return 1;
                   11320:     } else {
                   11321:         return 0;
                   11322:     }
                   11323: }
                   11324: 
                   11325: sub EXT_cache_set {
                   11326:     my ($target_domain,$target_user) = @_;
1.383     albertel 11327:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11328:     #&appenv({$cachename => time});
1.379     matthew  11329: }
                   11330: 
1.28      www      11331: # --------------------------------------------------------- Value of a Variable
1.58      www      11332: sub EXT {
1.715     albertel 11333: 
1.1228    raeburn  11334:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11335:     unless ($varname) { return ''; }
1.218     albertel 11336:     #get real user name/domain, courseid and symb
                   11337:     my $courseid;
1.359     albertel 11338:     my $publicuser;
1.427     www      11339:     if ($symbparm) {
                   11340: 	$symbparm=&get_symb_from_alias($symbparm);
                   11341:     }
1.218     albertel 11342:     if (!($uname && $udom)) {
1.790     albertel 11343:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11344:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11345:     } else {
1.620     albertel 11346: 	$courseid=$env{'request.course.id'};
1.218     albertel 11347:     }
1.48      www      11348:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11349:     my $rest;
1.320     albertel 11350:     if (defined($therest[0])) {
1.48      www      11351:        $rest=join('.',@therest);
                   11352:     } else {
                   11353:        $rest='';
                   11354:     }
1.320     albertel 11355: 
1.57      www      11356:     my $qualifierrest=$qualifier;
                   11357:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11358:     my $spacequalifierrest=$space;
                   11359:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11360:     if ($realm eq 'user') {
1.48      www      11361: # --------------------------------------------------------------- user.resource
                   11362: 	if ($space eq 'resource') {
1.651     albertel 11363: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11364: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11365: 		 &&
1.744     albertel 11366: 		 ($symbparm eq &symbread()) ) {	
                   11367: 		# if we are in the middle of processing the resource the
                   11368: 		# get the value we are planning on committing
                   11369:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11370:                     return $Apache::lonhomework::results{$qualifierrest};
                   11371:                 } else {
                   11372:                     return $Apache::lonhomework::history{$qualifierrest};
                   11373:                 }
1.335     albertel 11374: 	    } else {
1.359     albertel 11375: 		my %restored;
1.620     albertel 11376: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11377: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11378: 		} else {
                   11379: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11380: 		}
1.335     albertel 11381: 		return $restored{$qualifierrest};
                   11382: 	    }
1.48      www      11383: # ----------------------------------------------------------------- user.access
                   11384:         } elsif ($space eq 'access') {
1.218     albertel 11385: 	    # FIXME - not supporting calls for a specific user
1.48      www      11386:             return &allowed($qualifier,$rest);
                   11387: # ------------------------------------------ user.preferences, user.environment
                   11388:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11389: 	    if (($uname eq $env{'user.name'}) &&
                   11390: 		($udom eq $env{'user.domain'})) {
                   11391: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11392: 	    } else {
1.359     albertel 11393: 		my %returnhash;
                   11394: 		if (!$publicuser) {
                   11395: 		    %returnhash=&userenvironment($udom,$uname,
                   11396: 						 $qualifierrest);
                   11397: 		}
1.218     albertel 11398: 		return $returnhash{$qualifierrest};
                   11399: 	    }
1.48      www      11400: # ----------------------------------------------------------------- user.course
                   11401:         } elsif ($space eq 'course') {
1.218     albertel 11402: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11403:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11404: # ------------------------------------------------------------------- user.role
                   11405:         } elsif ($space eq 'role') {
1.218     albertel 11406: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11407:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11408:             if ($qualifier eq 'value') {
                   11409: 		return $role;
                   11410:             } elsif ($qualifier eq 'extent') {
                   11411:                 return $where;
                   11412:             }
                   11413: # ----------------------------------------------------------------- user.domain
                   11414:         } elsif ($space eq 'domain') {
1.218     albertel 11415:             return $udom;
1.48      www      11416: # ------------------------------------------------------------------- user.name
                   11417:         } elsif ($space eq 'name') {
1.218     albertel 11418:             return $uname;
1.48      www      11419: # ---------------------------------------------------- Any other user namespace
1.29      www      11420:         } else {
1.359     albertel 11421: 	    my %reply;
                   11422: 	    if (!$publicuser) {
                   11423: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11424: 	    }
                   11425: 	    return $reply{$qualifierrest};
1.48      www      11426:         }
1.236     www      11427:     } elsif ($realm eq 'query') {
                   11428: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11429:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11430: 						[$spacequalifierrest]);
1.620     albertel 11431: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11432:    } elsif ($realm eq 'request') {
1.48      www      11433: # ------------------------------------------------------------- request.browser
                   11434:         if ($space eq 'browser') {
1.1145    bisitz   11435:             return $env{'browser.'.$qualifier};
1.57      www      11436: # ------------------------------------------------------------ request.filename
                   11437:         } else {
1.620     albertel 11438:             return $env{'request.'.$spacequalifierrest};
1.29      www      11439:         }
1.28      www      11440:     } elsif ($realm eq 'course') {
1.48      www      11441: # ---------------------------------------------------------- course.description
1.620     albertel 11442:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11443:     } elsif ($realm eq 'resource') {
1.165     www      11444: 
1.620     albertel 11445: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11446: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11447: 	}
1.693     albertel 11448: 
1.1232    raeburn  11449:         if ($qualifier eq '') {
                   11450: 	    if ($space eq 'title') {
                   11451: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11452: 	        return &gettitle($symbparm);
                   11453: 	    }
1.693     albertel 11454: 	
1.1232    raeburn  11455: 	    if ($space eq 'map') {
                   11456: 	        my ($map) = &decode_symb($symbparm);
                   11457: 	        return &symbread($map);
                   11458: 	    }
                   11459:             if ($space eq 'maptitle') {
                   11460:                 my ($map) = &decode_symb($symbparm);
                   11461:                 return &gettitle($map);
                   11462:             }
                   11463: 	    if ($space eq 'filename') {
                   11464: 	        if ($symbparm) {
                   11465: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11466: 	        }
                   11467: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11468: 	    }
1.1232    raeburn  11469: 
1.1233    raeburn  11470:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11471:                 if ($space eq 'visibleparts') {
                   11472:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11473:                     my $item;
                   11474:                     if (ref($navmap)) {
                   11475:                         my $res = $navmap->getBySymb($symbparm);
                   11476:                         my $parts = $res->parts();
                   11477:                         if (ref($parts) eq 'ARRAY') {
                   11478:                             $item = join(',',@{$parts});
                   11479:                         }
                   11480:                         undef($navmap);
1.1232    raeburn  11481:                     }
1.1233    raeburn  11482:                     return $item;
1.1232    raeburn  11483:                 }
                   11484:             }
                   11485:         }
1.693     albertel 11486: 
1.1301    raeburn  11487: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11488: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11489:         if (($courseid eq '') && ($cid)) {
                   11490:             $courseid = $cid;
                   11491:         }
                   11492: 	if (($symbparm && $courseid) && 
                   11493: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11494: 
1.218     albertel 11495: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11496: 
1.60      www      11497: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11498: 	    my $symbp=$symbparm;
1.1301    raeburn  11499: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11500: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11501:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11502: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11503: 	    if (($env{'user.name'} eq $uname) &&
                   11504: 		($env{'user.domain'} eq $udom)) {
                   11505: 		$section=$env{'request.course.sec'};
1.733     raeburn  11506:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11507:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11508: 	    } else {
1.539     albertel 11509: 		if (! defined($usection)) {
1.551     albertel 11510: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11511: 		} else {
                   11512: 		    $section = $usection;
                   11513: 		}
1.733     raeburn  11514:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11515: 	    }
                   11516: 
                   11517: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11518: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11519:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11520: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11521: 
1.593     albertel 11522: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11523: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11524:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11525: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11526: 
1.60      www      11527: # ----------------------------------------------------------- first, check user
1.624     albertel 11528: 
1.1301    raeburn  11529: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11530:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11531: 				       ([$courselevelr,'resource'],
                   11532: 					[$courselevelm,'map'     ],
1.1301    raeburn  11533:                                         [$courseleveli,'map'     ],
1.927     albertel 11534: 					[$courselevel, 'course'  ]));
1.931     albertel 11535: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11536: 
1.594     albertel 11537: # ------------------------------------------------ second, check some of course
1.684     raeburn  11538:             my $coursereply;
1.691     raeburn  11539:             if (@groups > 0) {
                   11540:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11541:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11542:                                        $mapp,\$recursed,\@recurseup);
                   11543:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11544:             }
1.96      www      11545: 
1.684     raeburn  11546: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11547: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11548: 				  'course',$mapp,\$recursed,\@recurseup,
                   11549:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11550: 				  ([$seclevelr,   'resource'],
                   11551: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11552:                                    [$secleveli,   'map'     ],
1.927     albertel 11553: 				   [$seclevel,    'course'  ],
                   11554: 				   [$courselevelr,'resource']));
                   11555: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11556: 
1.60      www      11557: # ------------------------------------------------------ third, check map parms
1.218     albertel 11558: 	    my %parmhash=();
                   11559: 	    my $thisparm='';
                   11560: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11561: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11562: 		    &GDBM_READER(),0640)) {
1.218     albertel 11563: 		$thisparm=$parmhash{$symbparm};
                   11564: 		untie(%parmhash);
                   11565: 	    }
1.927     albertel 11566: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11567: 	}
1.594     albertel 11568: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11569:  
                   11570:         my $what = $spacequalifierrest;
                   11571: 	$what=~s/\./\_/;
1.282     albertel 11572: 	my $filename;
                   11573: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11574: 	if ($symbparm) {
1.409     www      11575: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11576: 	} else {
1.620     albertel 11577: 	    $filename=$env{'request.filename'};
1.282     albertel 11578: 	}
1.1362    raeburn  11579:         my $toolsymb;
                   11580:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11581:             $toolsymb = $symbparm;
                   11582:         }
                   11583: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11584: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11585: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11586: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11587: 
1.1301    raeburn  11588: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11589: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11590: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11591: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11592: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11593: 				     'course',$mapp,\$recursed,\@recurseup,
                   11594:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11595: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11596:                                       [$courseleveli,'map'   ],
1.927     albertel 11597: 				      [$courselevel, 'course']));
                   11598: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11599: 	}
1.145     www      11600: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11601: 	unless ($space eq '0') {
1.336     albertel 11602: 	    my @parts=split(/_/,$space);
                   11603: 	    my $id=pop(@parts);
                   11604: 	    my $part=join('_',@parts);
                   11605: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11606: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11607: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11608: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11609: 	}
1.395     albertel 11610: 	if ($recurse) { return undef; }
1.1362    raeburn  11611: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11612: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11613: # ---------------------------------------------------- Any other user namespace
                   11614:     } elsif ($realm eq 'environment') {
                   11615: # ----------------------------------------------------------------- environment
1.620     albertel 11616: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11617: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11618: 	} else {
1.770     albertel 11619: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11620: 		return '';
                   11621: 	    }
1.219     albertel 11622: 	    my %returnhash=&userenvironment($udom,$uname,
                   11623: 					    $spacequalifierrest);
                   11624: 	    return $returnhash{$spacequalifierrest};
                   11625: 	}
1.28      www      11626:     } elsif ($realm eq 'system') {
1.48      www      11627: # ----------------------------------------------------------------- system.time
                   11628: 	if ($space eq 'time') {
                   11629: 	    return time;
                   11630:         }
1.696     albertel 11631:     } elsif ($realm eq 'server') {
                   11632: # ----------------------------------------------------------------- system.time
                   11633: 	if ($space eq 'name') {
                   11634: 	    return $ENV{'SERVER_NAME'};
                   11635:         }
1.28      www      11636:     }
1.48      www      11637:     return '';
1.61      www      11638: }
                   11639: 
1.927     albertel 11640: sub get_reply {
                   11641:     my ($reply_value) = @_;
1.940     raeburn  11642:     if (ref($reply_value) eq 'ARRAY') {
                   11643:         if (wantarray) {
                   11644: 	    return @$reply_value;
                   11645:         }
                   11646:         return $reply_value->[0];
                   11647:     } else {
                   11648:         return $reply_value;
1.927     albertel 11649:     }
                   11650: }
                   11651: 
1.691     raeburn  11652: sub check_group_parms {
1.1301    raeburn  11653:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11654:         $recursed,$recurseupref) = @_;
                   11655:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11656:                   [$what,'course']);
                   11657:     my $coursereply;
1.691     raeburn  11658:     foreach my $group (@{$groups}) {
1.1301    raeburn  11659:         my @groupitems = ();
1.691     raeburn  11660:         foreach my $level (@levels) {
1.927     albertel 11661:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11662:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11663:         }
1.1301    raeburn  11664:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11665:                                    $env{'course.'.$courseid.'.domain'},
                   11666:                                    'course',$mapp,$recursed,$recurseupref,
                   11667:                                    $courseid,'.['.$group.'].',$what,
                   11668:                                    @groupitems);
                   11669:         last if (defined($coursereply));
1.691     raeburn  11670:     }
                   11671:     return $coursereply;
                   11672: }
                   11673: 
1.1301    raeburn  11674: sub get_map_hierarchy {
1.1302    raeburn  11675:     my ($mapname,$courseid) = @_;
                   11676:     my @recurseup = ();
1.1301    raeburn  11677:     if ($mapname) {
1.1302    raeburn  11678:         if (($cachedmapkey eq $courseid) &&
                   11679:             (abs($cachedmaptime-time)<5)) {
                   11680:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11681:                 return @{$cachedmaps{$mapname}};
                   11682:             }
                   11683:         }
1.1301    raeburn  11684:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11685:         if (ref($navmap)) {
                   11686:             @recurseup = $navmap->recurseup_maps($mapname);
                   11687:             undef($navmap);
1.1302    raeburn  11688:             $cachedmaps{$mapname} = \@recurseup;
                   11689:             $cachedmaptime=time;
                   11690:             $cachedmapkey=$courseid;
1.1301    raeburn  11691:         }
                   11692:     }
                   11693:     return @recurseup;
                   11694: }
                   11695: 
1.1302    raeburn  11696: }
                   11697: 
1.691     raeburn  11698: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11699:     my ($courseid,@groups) = @_;
                   11700:     @groups = sort(@groups);
1.691     raeburn  11701:     return @groups;
                   11702: }
                   11703: 
1.395     albertel 11704: sub packages_tab_default {
1.1362    raeburn  11705:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11706:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11707: 
                   11708:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11709:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11710: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11711: 	if ($pack_type eq 'default') {
                   11712: 	    $do_default=1;
                   11713: 	} elsif ($pack_type eq 'extension') {
                   11714: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11715: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11716: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11717: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11718: 	}
                   11719:     }
                   11720:     # first look for a package that matches the requested part id
                   11721:     foreach my $package (@specifics) {
                   11722: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11723: 	next if ($pack_part ne $part);
                   11724: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11725: 	    return $packagetab{"$pack_type&$name&default"};
                   11726: 	}
                   11727:     }
                   11728:     # look for any possible matching non extension_ package
                   11729:     foreach my $package (@specifics) {
                   11730: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11731: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11732: 	    return $packagetab{"$pack_type&$name&default"};
                   11733: 	}
1.585     albertel 11734: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11735: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11736: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11737: 	}
                   11738:     }
1.738     albertel 11739:     # look for any posible extension_ match
                   11740:     foreach my $package (@extension) {
                   11741: 	my ($package,$pack_type)=@{$package};
                   11742: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11743: 	    return $packagetab{"$pack_type&$name&default"};
                   11744: 	}
                   11745: 	if (defined($packagetab{$package."&$name&default"})) {
                   11746: 	    return $packagetab{$package."&$name&default"};
                   11747: 	}
                   11748:     }
                   11749:     # look for a global default setting
                   11750:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11751: 	return $packagetab{"default&$name&default"};
                   11752:     }
1.395     albertel 11753:     return undef;
                   11754: }
                   11755: 
1.334     albertel 11756: sub add_prefix_and_part {
                   11757:     my ($prefix,$part)=@_;
                   11758:     my $keyroot;
                   11759:     if (defined($prefix) && $prefix !~ /^__/) {
                   11760: 	# prefix that has a part already
                   11761: 	$keyroot=$prefix;
                   11762:     } elsif (defined($prefix)) {
                   11763: 	# prefix that is missing a part
                   11764: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11765:     } else {
                   11766: 	# no prefix at all
                   11767: 	if (defined($part)) { $keyroot='_'.$part; }
                   11768:     }
                   11769:     return $keyroot;
                   11770: }
                   11771: 
1.71      www      11772: # ---------------------------------------------------------------- Get metadata
                   11773: 
1.599     albertel 11774: my %metaentry;
1.1070    www      11775: my %importedpartids;
1.1369    raeburn  11776: my %importedrespids;
1.71      www      11777: sub metadata {
1.1362    raeburn  11778:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11779:     $uri=&declutter($uri);
1.288     albertel 11780:     # if it is a non metadata possible uri return quickly
1.529     albertel 11781:     if (($uri eq '') || 
                   11782: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11783: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11784:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11785: 	return undef;
                   11786:     }
1.1261    raeburn  11787:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11788: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11789: 	return undef;
1.288     albertel 11790:     }
1.73      www      11791:     my $filename=$uri;
                   11792:     $uri=~s/\.meta$//;
1.172     www      11793: #
                   11794: # Is the metadata already cached?
1.177     www      11795: # Look at timestamp of caching
1.172     www      11796: # Everything is cached by the main uri, libraries are never directly cached
                   11797: #
1.428     albertel 11798:     if (!defined($liburi)) {
1.599     albertel 11799: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11800: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11801:     }
1.1362    raeburn  11802: 
                   11803: #
                   11804: # If the uri is for an external tool the file from
                   11805: # which metadata should be retrieved depends on whether
                   11806: # the tool had been configured to be gradable (set in the Course
                   11807: # Editor or Resource Editor).
                   11808: #
                   11809: # If a valid symb has been included as the third arg in the call
                   11810: # to &metadata() that can be used to retrieve the value of
                   11811: # parameter_0_gradable set for the resource, and included in the
                   11812: # uploaded map containing the tool. The value is retrieved via
                   11813: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11814: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11815: # is retrieved via &get().
                   11816: #
                   11817: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11818: # hiddenresource and encrypturl (during course initialization)
                   11819: # the map-level parameter for resource.0.gradable included in the 
                   11820: # uploaded map containing the tool will not yet have been stored
                   11821: # in the user_course_parms.db file for the user's session, so in 
                   11822: # this case fall back to retrieving gradable status from the
                   11823: # exttool_$marker.db file.
1.1362    raeburn  11824: #
                   11825: # In order to avoid an infinite loop, &metadata() will return
                   11826: # before a call to &EXT(), if the uri is for an external tool
                   11827: # and the $what for which metadata is being requested is
                   11828: # parameter_0_gradable or 0_gradable.
                   11829: #
                   11830: 
                   11831:     if ($uri =~ /ext\.tool$/) {
                   11832:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11833:             return;
                   11834:         } else {
                   11835:             my ($checked,$use_passback);
                   11836:             if ($toolsymb ne '') {
                   11837:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11838:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11839:                     $checked = 1;
                   11840:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11841:                         $use_passback = 1;
                   11842:                     }
                   11843:                 }
                   11844:             }
                   11845:             unless ($checked) {
                   11846:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11847:                 $marker=~s/\D//g;
1.1363    raeburn  11848:                 if ($marker) {
1.1362    raeburn  11849:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11850:                     $use_passback = $toolsettings{'gradable'};
                   11851:                 }
                   11852:             }
                   11853:             if ($use_passback) {
                   11854:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11855:             } else {
                   11856:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11857:             }
                   11858:         }
                   11859:     }
                   11860: 
1.428     albertel 11861:     {
1.1069    www      11862: # Imported parts would go here
1.1369    raeburn  11863:         my @origfiletagids=();
1.1069    www      11864:         my $importedparts=0;
1.1369    raeburn  11865: 
                   11866: # Imported responseids would go here
                   11867:         my $importedresponses=0;
1.172     www      11868: #
                   11869: # Is this a recursive call for a library?
                   11870: #
1.599     albertel 11871: #	if (! exists($metacache{$uri})) {
                   11872: #	    $metacache{$uri}={};
                   11873: #	}
1.924     albertel 11874: 	my $cachetime = 60*60;
1.171     www      11875:         if ($liburi) {
                   11876: 	    $liburi=&declutter($liburi);
                   11877:             $filename=$liburi;
1.401     bowersj2 11878:         } else {
1.599     albertel 11879: 	    &devalidate_cache_new('meta',$uri);
                   11880: 	    undef(%metaentry);
1.401     bowersj2 11881: 	}
1.140     www      11882:         my %metathesekeys=();
1.73      www      11883:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11884: 	my $metastring;
1.1140    www      11885: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11886: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11887: 	    $metastring = 
1.929     albertel 11888: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11889: 					  ('grade_target' => 'meta'));
                   11890: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11891: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11892:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11893: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11894: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11895: 	    $metastring=&getfile($file);
1.489     albertel 11896: 	}
1.208     albertel 11897:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11898:         my $token;
1.140     www      11899:         undef %metathesekeys;
1.71      www      11900:         while ($token=$parser->get_token) {
1.339     albertel 11901: 	    if ($token->[0] eq 'S') {
                   11902: 		if (defined($token->[2]->{'package'})) {
1.172     www      11903: #
                   11904: # This is a package - get package info
                   11905: #
1.339     albertel 11906: 		    my $package=$token->[2]->{'package'};
                   11907: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11908: 		    if (defined($token->[2]->{'id'})) { 
                   11909: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11910: 		    }
1.599     albertel 11911: 		    if ($metaentry{':packages'}) {
                   11912: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11913: 		    } else {
1.599     albertel 11914: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11915: 		    }
1.736     albertel 11916: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11917: 			my $part=$keyroot;
                   11918: 			$part=~s/^\_//;
1.736     albertel 11919: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11920: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11921: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11922: 			    # ignore package.tab specified default values
                   11923:                             # here &package_tab_default() will fetch those
                   11924: 			    if ($subp eq 'default') { next; }
1.736     albertel 11925: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11926: 			    my $unikey;
                   11927: 			    if ($pack =~ /_0$/) {
                   11928: 				$unikey='parameter_0_'.$name;
                   11929: 				$part=0;
                   11930: 			    } else {
                   11931: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11932: 			    }
1.339     albertel 11933: 			    if ($subp eq 'display') {
                   11934: 				$value.=' [Part: '.$part.']';
                   11935: 			    }
1.599     albertel 11936: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11937: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11938: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11939: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11940: 			    }
1.599     albertel 11941: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11942: 				$metaentry{':'.$unikey}=
                   11943: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11944: 			    }
1.339     albertel 11945: 			}
                   11946: 		    }
                   11947: 		} else {
1.172     www      11948: #
                   11949: # This is not a package - some other kind of start tag
1.339     albertel 11950: #
                   11951: 		    my $entry=$token->[1];
1.1068    www      11952: 		    my $unikey='';
1.175     www      11953: 
1.339     albertel 11954: 		    if ($entry eq 'import') {
1.175     www      11955: #
                   11956: # Importing a library here
1.339     albertel 11957: #
1.1067    www      11958:                         my $location=$parser->get_text('/import');
                   11959:                         my $dir=$filename;
                   11960:                         $dir=~s|[^/]*$||;
                   11961:                         $location=&filelocation($dir,$location);
1.1369    raeburn  11962: 
                   11963:                         my $importid=$token->[2]->{'id'};
1.1068    www      11964:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  11965: #
                   11966: # Check metadata for imported file to
                   11967: # see if it contained response items
                   11968: #
1.1372    raeburn  11969:                         my ($origfile,@libfilekeys);
1.1370    raeburn  11970:                         my %currmetaentry = %metaentry;
1.1372    raeburn  11971:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   11972:                                                            $depthcount+1));
                   11973:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   11974:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   11975:                                                              undef,$depthcount+1);
                   11976:                             if ($libresponseorder ne '') {
                   11977:                                 if ($#origfiletagids<0) {
                   11978:                                     undef(%importedrespids);
                   11979:                                     undef(%importedpartids);
                   11980:                                 }
1.1373    raeburn  11981:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   11982:                                 if (@respids) {
                   11983:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   11984:                                 }
                   11985:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  11986:                                     $importedresponses = 1;
1.1369    raeburn  11987: # We need to get the original file and the imported file to get the response order correct
                   11988: # Load and inspect original file
1.1372    raeburn  11989:                                     if ($#origfiletagids<0) {
                   11990:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11991:                                         $origfile=&getfile($origfilelocation);
                   11992:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11993:                                     }
1.1369    raeburn  11994:                                 }
                   11995:                             }
                   11996:                         }
1.1370    raeburn  11997: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11998: # hash populated for imported library file
                   11999:                         %metaentry = %currmetaentry;
                   12000:                         undef(%currmetaentry);
1.1374    raeburn  12001:                         if ($importmode eq 'part') {
1.1068    www      12002: # Import as part(s)
1.1069    www      12003:                            $importedparts=1;
                   12004: # We need to get the original file and the imported file to get the part order correct
                   12005: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12006: # Load and inspect original file if we didn't do that already
                   12007:                            if ($#origfiletagids<0) {
                   12008:                                undef(%importedrespids);
                   12009:                                undef(%importedpartids);
                   12010:                                if ($origfile eq '') {
                   12011:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12012:                                    $origfile=&getfile($origfilelocation);
                   12013:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12014:                                }
1.1070    www      12015:                            }
1.1372    raeburn  12016:                            my @impfilepartids;
                   12017: # If <partorder> tag is included in metadata for the imported file
                   12018: # get the parts in the imported file from that.
                   12019:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12020:                                %currmetaentry = %metaentry;
                   12021:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12022:                                                             $depthcount+1);
                   12023:                                %metaentry = %currmetaentry;
                   12024:                                undef(%currmetaentry);
                   12025:                                if ($libpartorder ne '') {
                   12026:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12027:                                }
                   12028:                            } else {
                   12029: # If no <partorder> tag available, load and inspect imported file
                   12030:                                my $impfile=&getfile($location);
                   12031:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12032:                            }
1.1069    www      12033:                            if ($#impfilepartids>=0) {
                   12034: # This problem had parts
1.1070    www      12035:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12036:                            } else {
                   12037: # Importing by turning a single problem into a problem part
                   12038: # It gets the import-tags ID as part-ID
                   12039:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12040:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12041:                            }
1.1068    www      12042:                         } else {
1.1374    raeburn  12043: # Import as problem or as normal import
                   12044:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12045:                             unless ($importmode eq 'problem') {
1.1068    www      12046: # Normal import
1.1374    raeburn  12047:                                 if (defined($token->[2]->{'id'})) {
                   12048:                                     $unikey.='_'.$token->[2]->{'id'};
                   12049:                                 }
                   12050:                             }
                   12051: # Check metadata for imported file to
                   12052: # see if it contained parts
                   12053:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12054:                                 %currmetaentry = %metaentry;
                   12055:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12056:                                                              $depthcount+1);
                   12057:                                 %metaentry = %currmetaentry;
                   12058:                                 undef(%currmetaentry);
                   12059:                                 if ($libpartorder ne '') {
                   12060:                                     $importedparts = 1;
                   12061:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12062:                                 }
                   12063:                             }
1.1067    www      12064:                         }
1.339     albertel 12065: 			if ($depthcount<20) {
1.736     albertel 12066: 			    my $metadata = 
1.1362    raeburn  12067: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12068: 					  $depthcount+1);
                   12069: 			    foreach my $meta (split(',',$metadata)) {
                   12070: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12071: 				$metathesekeys{$meta}=1;
1.339     albertel 12072: 			    }
1.1068    www      12073:                         }
1.1067    www      12074: 		    } else {
                   12075: #
                   12076: # Not importing, some other kind of non-package, non-library start tag
                   12077: # 
                   12078:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12079:                         if (defined($token->[2]->{'id'})) {
                   12080:                             $unikey.='_'.$token->[2]->{'id'};
                   12081:                         }
1.339     albertel 12082: 			if (defined($token->[2]->{'name'})) { 
                   12083: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12084: 			}
                   12085: 			$metathesekeys{$unikey}=1;
1.736     albertel 12086: 			foreach my $param (@{$token->[3]}) {
                   12087: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12088: 				$token->[2]->{$param};
1.339     albertel 12089: 			}
                   12090: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12091: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12092: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12093: 		 # only ws inside the tag, and not in default, so use default
                   12094: 		 # as value
1.599     albertel 12095: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12096: 			} elsif ( $internaltext =~ /\S/ ) {
                   12097: 		  # something interesting inside the tag
                   12098: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12099: 			} else {
1.908     albertel 12100: 		  # no interesting values, don't set a default
1.339     albertel 12101: 			}
1.172     www      12102: # end of not-a-package not-a-library import
1.339     albertel 12103: 		    }
1.172     www      12104: # end of not-a-package start tag
1.339     albertel 12105: 		}
1.172     www      12106: # the next is the end of "start tag"
1.339     albertel 12107: 	    }
                   12108: 	}
1.483     albertel 12109: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12110: 	$extension = lc($extension);
                   12111: 	if ($extension eq 'htm') { $extension='html'; }
                   12112: 
1.737     albertel 12113: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12114: 	    #no specific packages #how's our extension
                   12115: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12116: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12117: 					 \%metathesekeys);
                   12118: 	}
1.883     albertel 12119: 
                   12120: 	if (!exists($metaentry{':packages'})
                   12121: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12122: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12123: 		#no specific packages well let's get default then
                   12124: 		if ($key!~/^default&/) { next; }
1.488     albertel 12125: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12126: 					     \%metathesekeys);
                   12127: 	    }
                   12128: 	}
1.338     www      12129: # are there custom rights to evaluate
1.599     albertel 12130: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12131: 
1.338     www      12132:     #
                   12133:     # Importing a rights file here
1.339     albertel 12134:     #
                   12135: 	    unless ($depthcount) {
1.599     albertel 12136: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12137: 		my $dir=$filename;
                   12138: 		$dir=~s|[^/]*$||;
                   12139: 		$location=&filelocation($dir,$location);
1.736     albertel 12140: 		my $rights_metadata =
1.1362    raeburn  12141: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12142: 			      $depthcount+1);
                   12143: 		foreach my $rights (split(',',$rights_metadata)) {
                   12144: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12145: 		    $metathesekeys{$rights}=1;
1.339     albertel 12146: 		}
                   12147: 	    }
                   12148: 	}
1.737     albertel 12149: 	# uniqifiy package listing
                   12150: 	my %seen;
                   12151: 	my @uniq_packages =
                   12152: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12153: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12154: 
1.1369    raeburn  12155:         if (($importedresponses) || ($importedparts)) {
                   12156:             if ($importedparts) {
1.1070    www      12157: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12158:                 $metaentry{':partorder'}='';
                   12159:                 $metathesekeys{'partorder'}=1;
                   12160:             }
                   12161:             if ($importedresponses) {
                   12162: # We had imported responses and need to rebuil responseorder
                   12163:                 $metaentry{':responseorder'}='';
                   12164:                 $metathesekeys{'responseorder'}=1;
                   12165:             }
                   12166:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12167:                 my $origid = $origfiletagids[$index+1];
                   12168:                 if ($origfiletagids[$index] eq 'part') {
                   12169: # Original part, part of the problem
                   12170:                     if ($importedparts) {
                   12171:                         $metaentry{':partorder'}.=','.$origid;
                   12172:                     }
                   12173:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12174:                     if ($importedparts) {
                   12175: # We have imported parts at this position
1.1373    raeburn  12176:                         if ($importedpartids{$origid} ne '') {
                   12177:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12178:                         }
1.1369    raeburn  12179:                     }
                   12180:                     if ($importedresponses) {
                   12181: # We have imported responses at this position
1.1373    raeburn  12182:                         if ($importedrespids{$origid} ne '') {
                   12183:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12184:                         }
                   12185:                     }
                   12186:                 } else {
                   12187: # Original response item, part of the problem
                   12188:                     if ($importedresponses) {
                   12189:                         $metaentry{':responseorder'}.=','.$origid;
                   12190:                     }
                   12191:                 }
                   12192:             }
                   12193:             if ($importedparts) {
                   12194:                 $metaentry{':partorder'}=~s/^\,//;
                   12195:             }
                   12196:             if ($importedresponses) {
                   12197:                 $metaentry{':responseorder'}=~s/^\,//;
                   12198:             }
1.1070    www      12199:         }
1.737     albertel 12200: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12201: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12202: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12203:         unless ($liburi) {
                   12204: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12205:         }
1.177     www      12206: # this is the end of "was not already recently cached
1.71      www      12207:     }
1.599     albertel 12208:     return $metaentry{':'.$what};
1.261     albertel 12209: }
                   12210: 
1.488     albertel 12211: sub metadata_create_package_def {
1.483     albertel 12212:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12213:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12214:     if ($subp eq 'default') { next; }
                   12215:     
1.599     albertel 12216:     if (defined($metaentry{':packages'})) {
                   12217: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12218:     } else {
1.599     albertel 12219: 	$metaentry{':packages'}=$package;
1.483     albertel 12220:     }
                   12221:     my $value=$packagetab{$key};
                   12222:     my $unikey;
                   12223:     $unikey='parameter_0_'.$name;
1.599     albertel 12224:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12225:     $$metathesekeys{$unikey}=1;
1.599     albertel 12226:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12227: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12228:     }
1.599     albertel 12229:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12230: 	$metaentry{':'.$unikey}=
                   12231: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12232:     }
                   12233: }
                   12234: 
1.261     albertel 12235: sub metadata_generate_part0 {
                   12236:     my ($metadata,$metacache,$uri) = @_;
                   12237:     my %allnames;
1.737     albertel 12238:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12239: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12240: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12241: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12242: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12243: 	    $allnames{$name}=$part;
                   12244: 	  }
                   12245: 	}
                   12246:     }
                   12247:     foreach my $name (keys(%allnames)) {
                   12248:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12249:       my $key=":parameter_0_$name";
1.261     albertel 12250:       $$metacache{"$key.part"}='0';
                   12251:       $$metacache{"$key.name"}=$name;
1.428     albertel 12252:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12253: 					   $allnames{$name}.'_'.$name.
                   12254: 					   '.type'};
1.428     albertel 12255:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12256: 			     '.display'};
1.644     www      12257:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12258:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12259:       $$metacache{"$key.display"}=$olddis;
                   12260:     }
1.71      www      12261: }
                   12262: 
1.764     albertel 12263: # ------------------------------------------------------ Devalidate title cache
                   12264: 
                   12265: sub devalidate_title_cache {
                   12266:     my ($url)=@_;
                   12267:     if (!$env{'request.course.id'}) { return; }
                   12268:     my $symb=&symbread($url);
                   12269:     if (!$symb) { return; }
                   12270:     my $key=$env{'request.course.id'}."\0".$symb;
                   12271:     &devalidate_cache_new('title',$key);
                   12272: }
                   12273: 
1.1014    droeschl 12274: # ------------------------------------------------- Get the title of a course
                   12275: 
                   12276: sub current_course_title {
                   12277:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12278: }
1.301     www      12279: # ------------------------------------------------- Get the title of a resource
                   12280: 
                   12281: sub gettitle {
                   12282:     my $urlsymb=shift;
                   12283:     my $symb=&symbread($urlsymb);
1.534     albertel 12284:     if ($symb) {
1.620     albertel 12285: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12286: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12287: 	if (defined($cached)) { 
                   12288: 	    return $result;
                   12289: 	}
1.534     albertel 12290: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12291: 	my $title='';
1.907     albertel 12292: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12293: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12294: 	} else {
                   12295: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12296: 		    &GDBM_READER(),0640)) {
                   12297: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12298: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12299: 		untie(%bighash);
                   12300: 	    }
1.534     albertel 12301: 	}
                   12302: 	$title=~s/\&colon\;/\:/gs;
                   12303: 	if ($title) {
1.1159    www      12304: # Remember both $symb and $title for dynamic metadata
                   12305:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12306:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12307: # Cache this title and then return it
1.599     albertel 12308: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12309: 	}
                   12310: 	$urlsymb=$url;
                   12311:     }
                   12312:     my $title=&metadata($urlsymb,'title');
                   12313:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12314:     return $title;
1.301     www      12315: }
1.613     albertel 12316: 
1.614     albertel 12317: sub get_slot {
                   12318:     my ($which,$cnum,$cdom)=@_;
                   12319:     if (!$cnum || !$cdom) {
1.790     albertel 12320: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12321: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12322: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12323:     }
1.703     albertel 12324:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12325:     my %slotinfo;
                   12326:     if (exists($remembered{$key})) {
                   12327: 	$slotinfo{$which} = $remembered{$key};
                   12328:     } else {
                   12329: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12330: 	&Apache::lonhomework::showhash(%slotinfo);
                   12331: 	my ($tmp)=keys(%slotinfo);
                   12332: 	if ($tmp=~/^error:/) { return (); }
                   12333: 	$remembered{$key} = $slotinfo{$which};
                   12334:     }
1.616     albertel 12335:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12336: 	return %{$slotinfo{$which}};
                   12337:     }
                   12338:     return $slotinfo{$which};
1.614     albertel 12339: }
1.1150    raeburn  12340: 
                   12341: sub get_reservable_slots {
                   12342:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12343:     my $now = time;
                   12344:     my $reservable_info;
                   12345:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12346:     if (exists($remembered{$key})) {
                   12347:         $reservable_info = $remembered{$key};
                   12348:     } else {
                   12349:         my %resv;
                   12350:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12351:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12352:         $reservable_info = \%resv;
                   12353:         $remembered{$key} = $reservable_info;
                   12354:     }
                   12355:     return $reservable_info;
                   12356: }
                   12357: 
                   12358: sub get_course_slots {
                   12359:     my ($cnum,$cdom) = @_;
                   12360:     my $hashid=$cnum.':'.$cdom;
                   12361:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12362:     if (defined($cached)) {
                   12363:         if (ref($result) eq 'HASH') {
                   12364:             return %{$result};
                   12365:         }
                   12366:     } else {
                   12367:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12368:         my ($tmp) = keys(%slots);
                   12369:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12370:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12371:             return %slots;
                   12372:         }
                   12373:     }
                   12374:     return;
                   12375: }
                   12376: 
                   12377: sub devalidate_slots_cache {
                   12378:     my ($cnum,$cdom)=@_;
                   12379:     my $hashid=$cnum.':'.$cdom;
                   12380:     &devalidate_cache_new('allslots',$hashid);
                   12381: }
                   12382: 
1.1181    raeburn  12383: sub get_coursechange {
                   12384:     my ($cdom,$cnum) = @_;
                   12385:     if ($cdom eq '' || $cnum eq '') {
                   12386:         return unless ($env{'request.course.id'});
                   12387:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12388:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12389:     }
                   12390:     my $hashid=$cdom.'_'.$cnum;
                   12391:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12392:     if ((defined($cached)) && ($change ne '')) {
                   12393:         return $change;
                   12394:     } else {
                   12395:         my %crshash;
                   12396:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12397:         if ($crshash{'internal.contentchange'} eq '') {
                   12398:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12399:             if ($change eq '') {
                   12400:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12401:                 $change = $crshash{'internal.created'};
                   12402:             }
                   12403:         } else {
                   12404:             $change = $crshash{'internal.contentchange'};
                   12405:         }
                   12406:         my $cachetime = 600;
                   12407:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12408:     }
                   12409:     return $change;
                   12410: }
                   12411: 
                   12412: sub devalidate_coursechange_cache {
                   12413:     my ($cnum,$cdom)=@_;
                   12414:     my $hashid=$cnum.':'.$cdom;
                   12415:     &devalidate_cache_new('crschange',$hashid);
                   12416: }
                   12417: 
1.31      www      12418: # ------------------------------------------------- Update symbolic store links
                   12419: 
                   12420: sub symblist {
                   12421:     my ($mapname,%newhash)=@_;
1.438     www      12422:     $mapname=&deversion(&declutter($mapname));
1.31      www      12423:     my %hash;
1.620     albertel 12424:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12425:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12426:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12427: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12428: 		next if ($url eq 'last_known'
                   12429: 			 && $env{'form.no_update_last_known'});
                   12430: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12431: 						    $newhash{$url}->[1],
                   12432: 						    $newhash{$url}->[0]);
1.191     harris41 12433:             }
1.31      www      12434:             if (untie(%hash)) {
                   12435: 		return 'ok';
                   12436:             }
                   12437:         }
                   12438:     }
                   12439:     return 'error';
1.212     www      12440: }
                   12441: 
                   12442: # --------------------------------------------------------------- Verify a symb
                   12443: 
                   12444: sub symbverify {
1.1190    raeburn  12445:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12446:     my $thisfn=$thisurl;
1.439     www      12447:     $thisfn=&declutter($thisfn);
1.215     www      12448: # direct jump to resource in page or to a sequence - will construct own symbs
                   12449:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12450: # check URL part
1.409     www      12451:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12452: 
1.431     www      12453:     unless ($url eq $thisfn) { return 0; }
1.213     www      12454: 
1.216     www      12455:     $symb=&symbclean($symb);
1.510     www      12456:     $thisurl=&deversion($thisurl);
1.439     www      12457:     $thisfn=&deversion($thisfn);
1.213     www      12458: 
                   12459:     my %bighash;
                   12460:     my $okay=0;
1.431     www      12461: 
1.620     albertel 12462:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12463:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12464:         my $noclutter;
1.1032    raeburn  12465:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12466:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12467:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12468:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12469:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12470:                 $noclutter = 1;
                   12471:             }
                   12472:         }
                   12473:         my $ids;
                   12474:         if ($noclutter) {
                   12475:             $ids=$bighash{'ids_'.$thisurl};
                   12476:         } else {
                   12477:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12478:         }
1.1102    raeburn  12479:         unless ($ids) {
                   12480:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12481:             $ids=$bighash{$idkey};
1.216     www      12482:         }
                   12483:         if ($ids) {
                   12484: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12485:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12486:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12487:             }
1.800     albertel 12488: 	    foreach my $id (split(/\,/,$ids)) {
                   12489: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12490:                if (
                   12491:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12492:    eq $symb) {
                   12493:                    if (ref($encstate)) {
                   12494:                        $$encstate = $bighash{'encrypted_'.$id};
                   12495:                    }
1.620     albertel 12496: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12497: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12498:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12499: 		       $okay=1;
1.1202    raeburn  12500:                        last;
1.582     albertel 12501: 		   }
                   12502: 	       }
1.216     www      12503: 	   }
                   12504:         }
1.213     www      12505: 	untie(%bighash);
                   12506:     }
                   12507:     return $okay;
1.31      www      12508: }
                   12509: 
1.210     www      12510: # --------------------------------------------------------------- Clean-up symb
                   12511: 
                   12512: sub symbclean {
                   12513:     my $symb=shift;
1.568     albertel 12514:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12515: # remove version from map
                   12516:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12517: 
1.210     www      12518: # remove version from URL
                   12519:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12520: 
1.507     www      12521: # remove wrapper
                   12522: 
1.510     www      12523:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12524:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12525:     return $symb;
1.409     www      12526: }
                   12527: 
                   12528: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12529: 
                   12530: sub encode_symb {
                   12531:     my ($map,$resid,$url)=@_;
                   12532:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12533: }
1.409     www      12534: 
                   12535: sub decode_symb {
1.568     albertel 12536:     my $symb=shift;
                   12537:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12538:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12539:     return (&fixversion($map),$resid,&fixversion($url));
                   12540: }
                   12541: 
                   12542: sub fixversion {
                   12543:     my $fn=shift;
1.609     banghart 12544:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12545:     my %bighash;
                   12546:     my $uri=&clutter($fn);
1.620     albertel 12547:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12548: # is this cached?
1.599     albertel 12549:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12550:     if (defined($cached)) { return $result; }
                   12551: # unfortunately not cached, or expired
1.620     albertel 12552:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12553: 	    &GDBM_READER(),0640)) {
                   12554:  	if ($bighash{'version_'.$uri}) {
                   12555:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12556:  	    unless (($version eq 'mostrecent') || 
                   12557: 		    ($version==&getversion($uri))) {
1.440     www      12558:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12559:  	    }
                   12560:  	}
                   12561:  	untie %bighash;
1.413     www      12562:     }
1.599     albertel 12563:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12564: }
                   12565: 
                   12566: sub deversion {
                   12567:     my $url=shift;
                   12568:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12569:     return $url;
1.210     www      12570: }
                   12571: 
1.31      www      12572: # ------------------------------------------------------ Return symb list entry
                   12573: 
                   12574: sub symbread {
1.1282    raeburn  12575:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12576:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12577:     if (defined($env{$cache_str})) {
                   12578:         if ($ignorecachednull) {
                   12579:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12580:         } else {
                   12581:             return $env{$cache_str};
                   12582:         }
                   12583:     }
1.242     www      12584: # no filename provided? try from environment
1.1265    raeburn  12585:     unless ($thisfn) {
1.620     albertel 12586:         if ($env{'request.symb'}) {
                   12587: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12588: 	}
1.620     albertel 12589: 	$thisfn=$env{'request.filename'};
1.44      www      12590:     }
1.569     albertel 12591:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12592: # is that filename actually a symb? Verify, clean, and return
                   12593:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12594: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12595: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12596: 	}
1.242     www      12597:     }
1.44      www      12598:     $thisfn=declutter($thisfn);
1.31      www      12599:     my %hash;
1.37      www      12600:     my %bighash;
                   12601:     my $syval='';
1.620     albertel 12602:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12603:         my $targetfn = $thisfn;
1.609     banghart 12604:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12605:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12606:         }
1.687     albertel 12607: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12608: 	    $targetfn=$1;
                   12609: 	}
1.620     albertel 12610:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12611:                       &GDBM_READER(),0640)) {
1.481     raeburn  12612: 	    $syval=$hash{$targetfn};
1.37      www      12613:             untie(%hash);
                   12614:         }
                   12615: # ---------------------------------------------------------- There was an entry
                   12616:         if ($syval) {
1.601     albertel 12617: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12618: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12619: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12620: 		    #return $env{$cache_str}='';
1.601     albertel 12621: 		#}    
                   12622: 		#$syval.=$1;
                   12623: 	    #}
1.37      www      12624:         } else {
                   12625: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12626:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12627:                             &GDBM_READER(),0640)) {
1.37      www      12628: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12629:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12630:               unless ($ids) { 
                   12631:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12632:               }
                   12633:               unless ($ids) {
                   12634: # alias?
                   12635: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12636:               }
1.37      www      12637:               if ($ids) {
                   12638: # ------------------------------------------------------------------- Has ID(s)
                   12639:                  my @possibilities=split(/\,/,$ids);
1.39      www      12640:                  if ($#possibilities==0) {
                   12641: # ----------------------------------------------- There is only one possibility
1.37      www      12642: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12643: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12644: 						    $resid,$thisfn);
1.1282    raeburn  12645:                      if (ref($possibles) eq 'HASH') {
                   12646:                          $possibles->{$syval} = 1;    
                   12647:                      }
                   12648:                      if ($checkforblock) {
                   12649:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12650:                          if (@blockers) {
                   12651:                              $syval = '';
                   12652:                              return;
                   12653:                          }
                   12654:                      }
                   12655:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12656: # ------------------------------------------ There is more than one possibility
                   12657:                      my $realpossible=0;
1.800     albertel 12658:                      foreach my $id (@possibilities) {
                   12659: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12660:                          my $canaccess;
                   12661:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12662:                              $canaccess = 1;
                   12663:                          } else { 
                   12664:                              $canaccess = &allowed('bre',$file);
                   12665:                          }
                   12666:                          if ($canaccess) {
                   12667:          		     my ($mapid,$resid)=split(/\./,$id);
                   12668:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12669:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12670: 						             $resid,$thisfn);
                   12671:                                  if (ref($possibles) eq 'HASH') {
                   12672:                                      $possibles->{$syval} = 1;
                   12673:                                  }
                   12674:                                  if ($checkforblock) {
                   12675:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12676:                                      unless (@blockers > 0) {
                   12677:                                          $syval = $poss_syval;
                   12678:                                          $realpossible++;
                   12679:                                      }
                   12680:                                  } else {
                   12681:                                      $syval = $poss_syval;
                   12682:                                      $realpossible++;
                   12683:                                  }
                   12684:                              }
1.39      www      12685: 			 }
1.191     harris41 12686:                      }
1.39      www      12687: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12688:                  } else {
                   12689:                      $syval='';
1.37      www      12690:                  }
                   12691: 	      }
1.1282    raeburn  12692:               untie(%bighash);
1.481     raeburn  12693:            }
1.31      www      12694:         }
1.62      www      12695:         if ($syval) {
1.620     albertel 12696: 	    return $env{$cache_str}=$syval;
1.62      www      12697:         }
1.31      www      12698:     }
1.949     raeburn  12699:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12700:     return $env{$cache_str}='';
1.31      www      12701: }
                   12702: 
                   12703: # ---------------------------------------------------------- Return random seed
                   12704: 
1.32      www      12705: sub numval {
                   12706:     my $txt=shift;
                   12707:     $txt=~tr/A-J/0-9/;
                   12708:     $txt=~tr/a-j/0-9/;
                   12709:     $txt=~tr/K-T/0-9/;
                   12710:     $txt=~tr/k-t/0-9/;
                   12711:     $txt=~tr/U-Z/0-5/;
                   12712:     $txt=~tr/u-z/0-5/;
                   12713:     $txt=~s/\D//g;
1.564     albertel 12714:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12715:     return int($txt);
1.368     albertel 12716: }
                   12717: 
1.484     albertel 12718: sub numval2 {
                   12719:     my $txt=shift;
                   12720:     $txt=~tr/A-J/0-9/;
                   12721:     $txt=~tr/a-j/0-9/;
                   12722:     $txt=~tr/K-T/0-9/;
                   12723:     $txt=~tr/k-t/0-9/;
                   12724:     $txt=~tr/U-Z/0-5/;
                   12725:     $txt=~tr/u-z/0-5/;
                   12726:     $txt=~s/\D//g;
                   12727:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12728:     my $total;
                   12729:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12730:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12731:     return int($total);
                   12732: }
                   12733: 
1.575     albertel 12734: sub numval3 {
                   12735:     use integer;
                   12736:     my $txt=shift;
                   12737:     $txt=~tr/A-J/0-9/;
                   12738:     $txt=~tr/a-j/0-9/;
                   12739:     $txt=~tr/K-T/0-9/;
                   12740:     $txt=~tr/k-t/0-9/;
                   12741:     $txt=~tr/U-Z/0-5/;
                   12742:     $txt=~tr/u-z/0-5/;
                   12743:     $txt=~s/\D//g;
                   12744:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12745:     my $total;
                   12746:     foreach my $val (@txts) { $total+=$val; }
                   12747:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12748:     return $total;
                   12749: }
                   12750: 
1.675     albertel 12751: sub digest {
                   12752:     my ($data)=@_;
                   12753:     my $digest=&Digest::MD5::md5($data);
                   12754:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12755:     my ($e,$f);
                   12756:     {
                   12757:         use integer;
                   12758:         $e=($a+$b);
                   12759:         $f=($c+$d);
                   12760:         if ($_64bit) {
                   12761:             $e=(($e<<32)>>32);
                   12762:             $f=(($f<<32)>>32);
                   12763:         }
                   12764:     }
                   12765:     if (wantarray) {
                   12766: 	return ($e,$f);
                   12767:     } else {
                   12768: 	my $g;
                   12769: 	{
                   12770: 	    use integer;
                   12771: 	    $g=($e+$f);
                   12772: 	    if ($_64bit) {
                   12773: 		$g=(($g<<32)>>32);
                   12774: 	    }
                   12775: 	}
                   12776: 	return $g;
                   12777:     }
                   12778: }
                   12779: 
1.368     albertel 12780: sub latest_rnd_algorithm_id {
1.675     albertel 12781:     return '64bit5';
1.366     albertel 12782: }
1.32      www      12783: 
1.503     albertel 12784: sub get_rand_alg {
                   12785:     my ($courseid)=@_;
1.790     albertel 12786:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12787:     if ($courseid) {
1.620     albertel 12788: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12789:     }
                   12790:     return &latest_rnd_algorithm_id();
                   12791: }
                   12792: 
1.562     albertel 12793: sub validCODE {
                   12794:     my ($CODE)=@_;
                   12795:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12796:     return 0;
                   12797: }
                   12798: 
1.491     albertel 12799: sub getCODE {
1.620     albertel 12800:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12801:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12802: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12803: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12804: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12805:     }
                   12806:     return undef;
                   12807: }
1.1133    foxr     12808: #
                   12809: #  Determines the random seed for a specific context:
                   12810: #
                   12811: # parameters:
                   12812: #   symb      - in course context the symb for the seed.
                   12813: #   course_id - The course id of the form domain_coursenum.
                   12814: #   domain    - Domain for the user.
                   12815: #   course    - Course for the user.
                   12816: #   cenv      - environment of the course.
                   12817: #
                   12818: # NOTE:
                   12819: #   All parameters are picked out of the environment if missing
                   12820: #   or not defined.
                   12821: #   If a symb cannot be determined the current time is used instead.
                   12822: #
                   12823: #  For a given well defined symb, courside, domain, username,
                   12824: #  and course environment, the seed is reproducible.
                   12825: #
1.31      www      12826: sub rndseed {
1.1133    foxr     12827:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12828:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12829:     if (!defined($symb)) {
1.366     albertel 12830: 	unless ($symb=$wsymb) { return time; }
                   12831:     }
1.1146    foxr     12832:     if (!defined $courseid) { 
                   12833: 	$courseid=$wcourseid; 
                   12834:     }
                   12835:     if (!defined $domain) { $domain=$wdomain; }
                   12836:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12837: 
                   12838:     my $which;
                   12839:     if (defined($cenv->{'rndseed'})) {
                   12840: 	$which = $cenv->{'rndseed'};
                   12841:     } else {
                   12842: 	$which =&get_rand_alg($courseid);
                   12843:     }
1.491     albertel 12844:     if (defined(&getCODE())) {
1.1133    foxr     12845: 
1.675     albertel 12846: 	if ($which eq '64bit5') {
                   12847: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12848: 	} elsif ($which eq '64bit4') {
1.575     albertel 12849: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12850: 	} else {
                   12851: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12852: 	}
1.675     albertel 12853:     } elsif ($which eq '64bit5') {
                   12854: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12855:     } elsif ($which eq '64bit4') {
                   12856: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12857:     } elsif ($which eq '64bit3') {
                   12858: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12859:     } elsif ($which eq '64bit2') {
                   12860: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12861:     } elsif ($which eq '64bit') {
                   12862: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12863:     }
                   12864:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12865: }
                   12866: 
                   12867: sub rndseed_32bit {
                   12868:     my ($symb,$courseid,$domain,$username)=@_;
                   12869:     {
                   12870: 	use integer;
                   12871: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12872: 	my $symbseed=numval($symb) << 22;
                   12873: 	my $namechck=unpack("%32C*",$username) << 17;
                   12874: 	my $nameseed=numval($username) << 12;
                   12875: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12876: 	my $courseseed=unpack("%32C*",$courseid);
                   12877: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12878: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12879: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12880: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12881: 	return $num;
                   12882:     }
                   12883: }
                   12884: 
                   12885: sub rndseed_64bit {
                   12886:     my ($symb,$courseid,$domain,$username)=@_;
                   12887:     {
                   12888: 	use integer;
                   12889: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12890: 	my $symbseed=numval($symb) << 10;
                   12891: 	my $namechck=unpack("%32S*",$username);
                   12892: 	
                   12893: 	my $nameseed=numval($username) << 21;
                   12894: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12895: 	my $courseseed=unpack("%32S*",$courseid);
                   12896: 	
                   12897: 	my $num1=$symbchck+$symbseed+$namechck;
                   12898: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12899: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12900: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12901: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12902: 	return "$num1,$num2";
1.155     albertel 12903:     }
1.366     albertel 12904: }
                   12905: 
1.443     albertel 12906: sub rndseed_64bit2 {
                   12907:     my ($symb,$courseid,$domain,$username)=@_;
                   12908:     {
                   12909: 	use integer;
                   12910: 	# strings need to be an even # of cahracters long, it it is odd the
                   12911:         # last characters gets thrown away
                   12912: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12913: 	my $symbseed=numval($symb) << 10;
                   12914: 	my $namechck=unpack("%32S*",$username.' ');
                   12915: 	
                   12916: 	my $nameseed=numval($username) << 21;
1.501     albertel 12917: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12918: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12919: 	
                   12920: 	my $num1=$symbchck+$symbseed+$namechck;
                   12921: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12922: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12923: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12924: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12925: 	return "$num1,$num2";
                   12926:     }
                   12927: }
                   12928: 
                   12929: sub rndseed_64bit3 {
                   12930:     my ($symb,$courseid,$domain,$username)=@_;
                   12931:     {
                   12932: 	use integer;
                   12933: 	# strings need to be an even # of cahracters long, it it is odd the
                   12934:         # last characters gets thrown away
                   12935: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12936: 	my $symbseed=numval2($symb) << 10;
                   12937: 	my $namechck=unpack("%32S*",$username.' ');
                   12938: 	
                   12939: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12940: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12941: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12942: 	
                   12943: 	my $num1=$symbchck+$symbseed+$namechck;
                   12944: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12945: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12946: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12947: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12948: 	
1.503     albertel 12949: 	return "$num1:$num2";
1.443     albertel 12950:     }
                   12951: }
                   12952: 
1.575     albertel 12953: sub rndseed_64bit4 {
                   12954:     my ($symb,$courseid,$domain,$username)=@_;
                   12955:     {
                   12956: 	use integer;
                   12957: 	# strings need to be an even # of cahracters long, it it is odd the
                   12958:         # last characters gets thrown away
                   12959: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12960: 	my $symbseed=numval3($symb) << 10;
                   12961: 	my $namechck=unpack("%32S*",$username.' ');
                   12962: 	
                   12963: 	my $nameseed=numval3($username) << 21;
                   12964: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12965: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12966: 	
                   12967: 	my $num1=$symbchck+$symbseed+$namechck;
                   12968: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12969: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12970: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12971: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12972: 	
1.575     albertel 12973: 	return "$num1:$num2";
                   12974:     }
                   12975: }
                   12976: 
1.675     albertel 12977: sub rndseed_64bit5 {
                   12978:     my ($symb,$courseid,$domain,$username)=@_;
                   12979:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12980:     return "$num1:$num2";
                   12981: }
                   12982: 
1.366     albertel 12983: sub rndseed_CODE_64bit {
                   12984:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12985:     {
1.366     albertel 12986: 	use integer;
1.443     albertel 12987: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12988: 	my $symbseed=numval2($symb);
1.491     albertel 12989: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12990: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12991: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12992: 	my $num1=$symbseed+$CODEchck;
                   12993: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12994: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12995: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12996: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12997: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12998: 	return "$num1:$num2";
1.366     albertel 12999:     }
                   13000: }
                   13001: 
1.575     albertel 13002: sub rndseed_CODE_64bit4 {
                   13003:     my ($symb,$courseid,$domain,$username)=@_;
                   13004:     {
                   13005: 	use integer;
                   13006: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13007: 	my $symbseed=numval3($symb);
                   13008: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13009: 	my $CODEseed=numval3(&getCODE());
                   13010: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13011: 	my $num1=$symbseed+$CODEchck;
                   13012: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13013: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13014: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13015: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13016: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13017: 	return "$num1:$num2";
                   13018:     }
                   13019: }
                   13020: 
1.675     albertel 13021: sub rndseed_CODE_64bit5 {
                   13022:     my ($symb,$courseid,$domain,$username)=@_;
                   13023:     my $code = &getCODE();
                   13024:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13025:     return "$num1:$num2";
                   13026: }
                   13027: 
1.366     albertel 13028: sub setup_random_from_rndseed {
                   13029:     my ($rndseed)=@_;
1.503     albertel 13030:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13031:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13032:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13033:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13034:         } else {
                   13035:             &Math::Random::random_set_seed($num1,$num2);
                   13036:         }
1.366     albertel 13037:     } else {
                   13038: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13039:     }
1.36      albertel 13040: }
                   13041: 
1.474     albertel 13042: sub latest_receipt_algorithm_id {
1.835     albertel 13043:     return 'receipt3';
1.474     albertel 13044: }
                   13045: 
1.480     www      13046: sub recunique {
                   13047:     my $fucourseid=shift;
                   13048:     my $unique;
1.835     albertel 13049:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13050: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13051: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13052:     } else {
                   13053: 	$unique=$perlvar{'lonReceipt'};
                   13054:     }
                   13055:     return unpack("%32C*",$unique);
                   13056: }
                   13057: 
                   13058: sub recprefix {
                   13059:     my $fucourseid=shift;
                   13060:     my $prefix;
1.835     albertel 13061:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13062: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13063: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13064:     } else {
                   13065: 	$prefix=$perlvar{'lonHostID'};
                   13066:     }
                   13067:     return unpack("%32C*",$prefix);
                   13068: }
                   13069: 
1.76      www      13070: sub ireceipt {
1.474     albertel 13071:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13072: 
                   13073:     my $return =&recprefix($fucourseid).'-';
                   13074: 
                   13075:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13076: 	$env{'request.state'} eq 'construct') {
                   13077: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13078: 	return $return;
                   13079:     }
                   13080: 
1.76      www      13081:     my $cuname=unpack("%32C*",$funame);
                   13082:     my $cudom=unpack("%32C*",$fudom);
                   13083:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13084:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13085:     my $cunique=&recunique($fucourseid);
1.474     albertel 13086:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13087:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13088: 
1.790     albertel 13089: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13090: 			       
                   13091: 	$return.= ($cunique%$cuname+
                   13092: 		   $cunique%$cudom+
                   13093: 		   $cusymb%$cuname+
                   13094: 		   $cusymb%$cudom+
                   13095: 		   $cucourseid%$cuname+
                   13096: 		   $cucourseid%$cudom+
                   13097: 		   $cpart%$cuname+
                   13098: 		   $cpart%$cudom);
                   13099:     } else {
                   13100: 	$return.= ($cunique%$cuname+
                   13101: 		   $cunique%$cudom+
                   13102: 		   $cusymb%$cuname+
                   13103: 		   $cusymb%$cudom+
                   13104: 		   $cucourseid%$cuname+
                   13105: 		   $cucourseid%$cudom);
                   13106:     }
                   13107:     return $return;
1.76      www      13108: }
                   13109: 
                   13110: sub receipt {
1.474     albertel 13111:     my ($part)=@_;
1.790     albertel 13112:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13113:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13114: }
1.260     ng       13115: 
1.790     albertel 13116: sub whichuser {
                   13117:     my ($passedsymb)=@_;
                   13118:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13119:     if (defined($env{'form.grade_symb'})) {
                   13120: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13121: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13122: 	if (!$allowed &&
                   13123: 	    exists($env{'request.course.sec'}) &&
                   13124: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13125: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13126: 			      '/'.$env{'request.course.sec'});
                   13127: 	}
                   13128: 	if ($allowed) {
                   13129: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13130: 	    $courseid=$tmp_courseid;
                   13131: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13132: 	    ($name)=&get_env_multiple('form.grade_username');
                   13133: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13134: 	}
                   13135:     }
                   13136:     if (!$passedsymb) {
                   13137: 	$symb=&symbread();
                   13138:     } else {
                   13139: 	$symb=$passedsymb;
                   13140:     }
                   13141:     $courseid=$env{'request.course.id'};
                   13142:     $domain=$env{'user.domain'};
                   13143:     $name=$env{'user.name'};
                   13144:     if ($name eq 'public' && $domain eq 'public') {
                   13145: 	if (!defined($env{'form.username'})) {
                   13146: 	    $env{'form.username'}.=time.rand(10000000);
                   13147: 	}
                   13148: 	$name.=$env{'form.username'};
                   13149:     }
                   13150:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13151: 
                   13152: }
                   13153: 
1.36      albertel 13154: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13155: # returns either the contents of the file or 
                   13156: # -1 if the file doesn't exist
1.481     raeburn  13157: #
                   13158: # if the target is a file that was uploaded via DOCS, 
                   13159: # a check will be made to see if a current copy exists on the local server,
                   13160: # if it does this will be served, otherwise a copy will be retrieved from
                   13161: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13162: # the local server.   
1.472     albertel 13163: 
1.36      albertel 13164: sub getfile {
1.538     albertel 13165:     my ($file) = @_;
1.609     banghart 13166:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13167:     &repcopy($file);
                   13168:     return &readfile($file);
                   13169: }
                   13170: 
                   13171: sub repcopy_userfile {
                   13172:     my ($file)=@_;
1.1142    raeburn  13173:     my $londocroot = $perlvar{'lonDocRoot'};
                   13174:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13175:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13176:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13177: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13178:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13179:     if (-e "$file") {
1.828     www      13180: # we already have a local copy, check it out
1.538     albertel 13181: 	my @fileinfo = stat($file);
1.828     www      13182: 	my $rtncode;
                   13183: 	my $info;
1.538     albertel 13184: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13185: 	if ($lwpresp ne 'ok') {
1.828     www      13186: # there is no such file anymore, even though we had a local copy
1.482     albertel 13187: 	    if ($rtncode eq '404') {
1.538     albertel 13188: 		unlink($file);
1.482     albertel 13189: 	    }
                   13190: 	    return -1;
                   13191: 	}
                   13192: 	if ($info < $fileinfo[9]) {
1.828     www      13193: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13194: 	    return 'ok';
1.828     www      13195: 	} else {
                   13196: # the file is outdated, get rid of it
                   13197: 	    unlink($file);
1.482     albertel 13198: 	}
1.828     www      13199:     }
                   13200: # one way or the other, at this point, we don't have the file
                   13201: # construct the correct path for the file
                   13202:     my @parts = ($cdom,$cnum); 
                   13203:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13204: 	push @parts, split(/\//,$1);
                   13205:     }
                   13206:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13207:     foreach my $part (@parts) {
                   13208: 	$path .= '/'.$part;
                   13209: 	if (!-e $path) {
                   13210: 	    mkdir($path,0770);
1.482     albertel 13211: 	}
                   13212:     }
1.828     www      13213: # now the path exists for sure
                   13214: # get a user agent
                   13215:     my $transferfile=$file.'.in.transfer';
                   13216: # FIXME: this should flock
                   13217:     if (-e $transferfile) { return 'ok'; }
                   13218:     my $request;
                   13219:     $uri=~s/^\///;
1.980     raeburn  13220:     my $homeserver = &homeserver($cnum,$cdom);
                   13221:     my $protocol = $protocol{$homeserver};
                   13222:     $protocol = 'http' if ($protocol ne 'https');
                   13223:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13224:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13225: # did it work?
                   13226:     if ($response->is_error()) {
                   13227: 	unlink($transferfile);
                   13228: 	&logthis("Userfile repcopy failed for $uri");
                   13229: 	return -1;
                   13230:     }
                   13231: # worked, rename the transfer file
                   13232:     rename($transferfile,$file);
1.607     raeburn  13233:     return 'ok';
1.481     raeburn  13234: }
                   13235: 
1.517     albertel 13236: sub tokenwrapper {
                   13237:     my $uri=shift;
1.980     raeburn  13238:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13239:     $uri=~s|^/||;
1.620     albertel 13240:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13241:     my $token=$1;
1.552     albertel 13242:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13243:     if ($udom && $uname && $file) {
                   13244: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13245:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13246:         my $homeserver = &homeserver($uname,$udom);
                   13247:         my $protocol = $protocol{$homeserver};
                   13248:         $protocol = 'http' if ($protocol ne 'https');
                   13249:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13250:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13251:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13252:     } else {
                   13253:         return '/adm/notfound.html';
                   13254:     }
                   13255: }
                   13256: 
1.828     www      13257: # call with reqtype HEAD: get last modification time
                   13258: # call with reqtype GET: get the file contents
                   13259: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13260: #
1.481     raeburn  13261: sub getuploaded {
                   13262:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13263:     $uri=~s/^\///;
1.980     raeburn  13264:     my $homeserver = &homeserver($cnum,$cdom);
                   13265:     my $protocol = $protocol{$homeserver};
                   13266:     $protocol = 'http' if ($protocol ne 'https');
                   13267:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13268:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13269:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13270:     $$rtncode = $response->code;
1.482     albertel 13271:     if (! $response->is_success()) {
                   13272: 	return 'failed';
                   13273:     }      
                   13274:     if ($reqtype eq 'HEAD') {
1.486     www      13275: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13276:     } elsif ($reqtype eq 'GET') {
                   13277: 	$$info = $response->content;
1.472     albertel 13278:     }
1.482     albertel 13279:     return 'ok';
1.36      albertel 13280: }
                   13281: 
1.481     raeburn  13282: sub readfile {
                   13283:     my $file = shift;
                   13284:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13285:     my $fh;
1.1359    raeburn  13286:     open($fh,"<",$file);
1.481     raeburn  13287:     my $a='';
1.800     albertel 13288:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13289:     return $a;
                   13290: }
                   13291: 
1.36      albertel 13292: sub filelocation {
1.590     banghart 13293:     my ($dir,$file) = @_;
                   13294:     my $location;
                   13295:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13296: 
                   13297:     if ($file =~ m-^/adm/-) {
                   13298: 	$file=~s-^/adm/wrapper/-/-;
                   13299: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13300:     }
1.882     albertel 13301: 
1.1139    www      13302:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13303:         $location = $file;
1.609     banghart 13304:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13305:         my ($udom,$uname,$filename)=
1.811     albertel 13306:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13307:         my $home=&homeserver($uname,$udom);
                   13308:         my $is_me=0;
                   13309:         my @ids=&current_machine_ids();
                   13310:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13311:         if ($is_me) {
1.1117    foxr     13312:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13313:         } else {
                   13314:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13315:   	      $udom.'/'.$uname.'/'.$filename;
                   13316:         }
1.882     albertel 13317:     } elsif ($file =~ m-^/adm/-) {
                   13318: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13319:     } else {
                   13320:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13321:         $file=~s:^/(res|priv)/:/:;
                   13322:         my $space=$1;
1.590     banghart 13323:         if ( !( $file =~ m:^/:) ) {
                   13324:             $location = $dir. '/'.$file;
                   13325:         } else {
1.1142    raeburn  13326:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13327:         }
1.59      albertel 13328:     }
1.590     banghart 13329:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13330:     while ($location=~m{/\.\./}) {
                   13331: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13332: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13333: 	} else {
                   13334: 	    $location=~ s{/\.\./}{/}g;
                   13335: 	}
                   13336:     } #remove dir/..
1.590     banghart 13337:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13338:     return $location;
1.46      www      13339: }
1.36      albertel 13340: 
1.46      www      13341: sub hreflocation {
                   13342:     my ($dir,$file)=@_;
1.980     raeburn  13343:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13344: 	$file=filelocation($dir,$file);
1.700     albertel 13345:     } elsif ($file=~m-^/adm/-) {
                   13346: 	$file=~s-^/adm/wrapper/-/-;
                   13347: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13348:     }
                   13349:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13350: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13351:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13352: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13353: 	        {/uploaded/$1/$2/}x;
1.46      www      13354:     }
1.913     albertel 13355:     if ($file=~ m{^/userfiles/}) {
                   13356: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13357:     }
1.462     albertel 13358:     return $file;
1.465     albertel 13359: }
                   13360: 
1.1139    www      13361: 
                   13362: 
                   13363: 
                   13364: 
1.465     albertel 13365: sub current_machine_domains {
1.853     albertel 13366:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13367: }
                   13368: 
                   13369: sub machine_domains {
                   13370:     my ($hostname) = @_;
1.465     albertel 13371:     my @domains;
1.838     albertel 13372:     my %hostname = &all_hostnames();
1.465     albertel 13373:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13374: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13375: 	if ($hostname eq $name) {
1.844     albertel 13376: 	    push(@domains,&host_domain($id));
1.465     albertel 13377: 	}
                   13378:     }
                   13379:     return @domains;
                   13380: }
                   13381: 
                   13382: sub current_machine_ids {
1.853     albertel 13383:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13384: }
                   13385: 
                   13386: sub machine_ids {
                   13387:     my ($hostname) = @_;
                   13388:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13389:     my @ids;
1.888     albertel 13390:     my %name_to_host = &all_names();
1.889     albertel 13391:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13392: 	return @{ $name_to_host{$hostname} };
                   13393:     }
                   13394:     return;
1.31      www      13395: }
                   13396: 
1.824     raeburn  13397: sub additional_machine_domains {
                   13398:     my @domains;
1.1359    raeburn  13399:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13400:     while( my $line = <$fh>) {
                   13401:         $line =~ s/\s//g;
                   13402:         push(@domains,$line);
                   13403:     }
                   13404:     return @domains;
                   13405: }
                   13406: 
                   13407: sub default_login_domain {
                   13408:     my $domain = $perlvar{'lonDefDomain'};
                   13409:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13410:     foreach my $posdom (&current_machine_domains(),
                   13411:                         &additional_machine_domains()) {
                   13412:         if (lc($posdom) eq lc($testdomain)) {
                   13413:             $domain=$posdom;
                   13414:             last;
                   13415:         }
                   13416:     }
                   13417:     return $domain;
                   13418: }
                   13419: 
1.31      www      13420: # ------------------------------------------------------------- Declutters URLs
                   13421: 
                   13422: sub declutter {
                   13423:     my $thisfn=shift;
1.569     albertel 13424:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13425:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13426:         $thisfn=~s{^/home/httpd/html}{};
                   13427:     }
1.31      www      13428:     $thisfn=~s/^\///;
1.697     albertel 13429:     $thisfn=~s|^adm/wrapper/||;
                   13430:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13431:     $thisfn=~s/^res\///;
1.1172    bisitz   13432:     $thisfn=~s/^priv\///;
1.1032    raeburn  13433:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13434:         $thisfn=~s/\?.+$//;
                   13435:     }
1.268     www      13436:     return $thisfn;
                   13437: }
                   13438: 
                   13439: # ------------------------------------------------------------- Clutter up URLs
                   13440: 
                   13441: sub clutter {
                   13442:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13443:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13444: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13445:        $thisfn='/res'.$thisfn; 
                   13446:     }
1.1031    raeburn  13447:     if ($thisfn !~m|^/adm|) {
                   13448: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13449: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13450: 	} else {
                   13451: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13452: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13453: 	    if ($embstyle eq 'ssi'
                   13454: 		|| ($embstyle eq 'hdn')
                   13455: 		|| ($embstyle eq 'rat')
                   13456: 		|| ($embstyle eq 'prv')
                   13457: 		|| ($embstyle eq 'ign')) {
                   13458: 		#do nothing with these
                   13459: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13460: 		|| ($embstyle eq 'emb')
                   13461: 		|| ($embstyle eq 'wrp')) {
                   13462: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13463: 	    } elsif ($embstyle eq 'unk'
                   13464: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13465: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13466: 	    } else {
1.718     www      13467: #		&logthis("Got a blank emb style");
1.695     albertel 13468: 	    }
1.694     albertel 13469: 	}
1.1343    raeburn  13470:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13471:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13472:     }
1.31      www      13473:     return $thisfn;
1.12      www      13474: }
                   13475: 
1.787     albertel 13476: sub clutter_with_no_wrapper {
                   13477:     my $uri = &clutter(shift);
                   13478:     if ($uri =~ m-^/adm/-) {
                   13479: 	$uri =~ s-^/adm/wrapper/-/-;
                   13480: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13481:     }
                   13482:     return $uri;
                   13483: }
                   13484: 
1.557     albertel 13485: sub freeze_escape {
                   13486:     my ($value)=@_;
                   13487:     if (ref($value)) {
                   13488: 	$value=&nfreeze($value);
                   13489: 	return '__FROZEN__'.&escape($value);
                   13490:     }
                   13491:     return &escape($value);
                   13492: }
                   13493: 
1.11      www      13494: 
1.557     albertel 13495: sub thaw_unescape {
                   13496:     my ($value)=@_;
                   13497:     if ($value =~ /^__FROZEN__/) {
                   13498: 	substr($value,0,10,undef);
                   13499: 	$value=&unescape($value);
                   13500: 	return &thaw($value);
                   13501:     }
                   13502:     return &unescape($value);
                   13503: }
                   13504: 
1.436     albertel 13505: sub correct_line_ends {
                   13506:     my ($result)=@_;
                   13507:     $$result =~s/\r\n/\n/mg;
                   13508:     $$result =~s/\r/\n/mg;
1.415     albertel 13509: }
1.1       albertel 13510: # ================================================================ Main Program
                   13511: 
1.184     www      13512: sub goodbye {
1.204     albertel 13513:    &logthis("Starting Shut down");
1.443     albertel 13514: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13515:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13516: #converted
1.599     albertel 13517: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13518:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13519: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13520: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13521: #1.1 only
1.870     albertel 13522: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13523: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13524: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13525: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13526:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13527:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13528:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13529:    &flushcourselogs();
                   13530:    &logthis("Shutting down");
                   13531: }
                   13532: 
1.852     albertel 13533: sub get_dns {
1.1210    raeburn  13534:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13535:     if (!$ignore_cache) {
                   13536: 	my ($content,$cached)=
                   13537: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13538: 	if ($cached) {
1.1210    raeburn  13539: 	    &$func($content,$hashref);
1.869     albertel 13540: 	    return;
                   13541: 	}
                   13542:     }
                   13543: 
                   13544:     my %alldns;
1.1379    raeburn  13545:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13546:         foreach my $dns (<$config>) {
                   13547: 	    next if ($dns !~ /^\^(\S*)/x);
                   13548:             my $line = $1;
                   13549:             my ($host,$protocol) = split(/:/,$line);
                   13550:             if ($protocol ne 'https') {
                   13551:                 $protocol = 'http';
                   13552:             }
                   13553: 	    $alldns{$host} = $protocol;
1.979     raeburn  13554:         }
1.1379    raeburn  13555:         close($config);
1.869     albertel 13556:     }
                   13557:     while (%alldns) {
1.1263    raeburn  13558: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13559: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13560:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13561:         delete($alldns{$dns});
1.852     albertel 13562: 	next if ($response->is_error());
1.1379    raeburn  13563:         if ($url eq '/adm/dns/loncapaCRL') {
                   13564:             return &$func($response);
                   13565:         } else {
                   13566: 	    my @content = split("\n",$response->content);
                   13567: 	    unless ($nocache) {
                   13568: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   13569: 	    }
                   13570: 	    &$func(\@content,$hashref);
                   13571:             return;
                   13572:         }
                   13573:     }
                   13574:     my $which = (split('/',$url,4))[3];
                   13575:     if ($which eq 'loncapaCRL') {
                   13576:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   13577:         if (-e $diskfile) {
                   13578:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   13579:         } else {
                   13580:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   13581:         }
                   13582:     } else {
                   13583:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13584:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13585:             my @content = <$config>;
                   13586:             close($config);
                   13587:             &$func(\@content,$hashref);
                   13588:         }
1.852     albertel 13589:     }
1.1210    raeburn  13590:     return;
                   13591: }
                   13592: 
                   13593: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13594: sub parse_dns_checksums_tab {
1.1210    raeburn  13595:     my ($lines,$hashref) = @_;
1.1264    raeburn  13596:     my $lonhost = $perlvar{'lonHostID'};
                   13597:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13598:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13599:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13600:     my $webconfdir = '/etc/httpd/conf';
                   13601:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13602:         $webconfdir = '/etc/apache2';
                   13603:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13604:         if ($1 >= 10) {
                   13605:             $webconfdir = '/etc/apache2';
                   13606:         }
                   13607:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13608:         if ($1 >= 10.0) {
                   13609:             $webconfdir = '/etc/apache2';
                   13610:         }
                   13611:     }
1.1210    raeburn  13612:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13613:     my (%chksum,%revnum);
                   13614:     if (ref($lines) eq 'ARRAY') {
                   13615:         chomp(@{$lines});
1.1238    raeburn  13616:         my $version = shift(@{$lines});
                   13617:         if ($version eq $release) {  
1.1210    raeburn  13618:             foreach my $line (@{$lines}) {
1.1238    raeburn  13619:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13620:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13621:                     if ($webconfdir eq '/etc/apache2') {
                   13622:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13623:                     }
                   13624:                 }
1.1238    raeburn  13625:                 $chksum{$file} = $shasum;
                   13626:                 $revnum{$file} = $version;
1.1210    raeburn  13627:             }
                   13628:             if (ref($hashref) eq 'HASH') {
                   13629:                 %{$hashref} = (
                   13630:                                 sums     => \%chksum,
                   13631:                                 versions => \%revnum,
                   13632:                               );
                   13633:             }
                   13634:         }
                   13635:     }
1.869     albertel 13636:     return;
1.852     albertel 13637: }
1.1210    raeburn  13638: 
                   13639: sub fetch_dns_checksums {
1.1238    raeburn  13640:     my %checksums;
                   13641:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13642:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13643:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13644:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13645:              \%checksums);
1.1210    raeburn  13646:     return \%checksums;
                   13647: }
                   13648: 
1.1379    raeburn  13649: sub fetch_crl_pemfile {
                   13650:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   13651: }
                   13652: 
                   13653: sub save_crl_pem {
                   13654:     my ($response) = @_;
1.1380    raeburn  13655:     my ($msg,$hadchanges);
1.1379    raeburn  13656:     if (ref($response)) {
                   13657:         my $now = time;
                   13658:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   13659:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   13660:         if (open(my $fh,'>',"$tmpcrl")) {
                   13661:             print $fh $response->content;
                   13662:             close($fh);
                   13663:             if (-e $lonca) {
                   13664:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   13665:                     my $check = <PIPE>;
                   13666:                     close(PIPE);
                   13667:                     chomp($check);
                   13668:                     if ($check eq 'verify OK') {
                   13669:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  13670:                         my $backup;
1.1379    raeburn  13671:                         if (-e $dest) {
1.1380    raeburn  13672:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   13673:                                 $backup = 'ok';
                   13674:                             }
1.1379    raeburn  13675:                         }
                   13676:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   13677:                             $msg = 'ok';
1.1380    raeburn  13678:                             if ($backup) {
                   13679:                                 my (%oldnums,%newnums);
                   13680:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   13681:                                     while (<PIPE>) {
                   13682:                                         $oldnums{(split(/:/))[1]} = 1;
                   13683:                                     }
                   13684:                                     close(PIPE);
                   13685:                                 }
                   13686:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   13687:                                     while(<PIPE>) {
                   13688:                                         $newnums{(split(/:/))[1]} = 1;
                   13689:                                     }
                   13690:                                     close(PIPE);
                   13691:                                 }
                   13692:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   13693:                                     unless (exists($oldnums{$key})) {
                   13694:                                         $hadchanges = 1;
                   13695:                                         last;
                   13696:                                     }
                   13697:                                 }
                   13698:                                 unless ($hadchanges) {
                   13699:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   13700:                                         unless (exists($newnums{$key})) {
                   13701:                                             $hadchanges = 1;
                   13702:                                             last;
                   13703:                                         }
                   13704:                                     }
                   13705:                                 }
                   13706:                             }
1.1379    raeburn  13707:                         }
                   13708:                     } else {
                   13709:                         unlink($tmpcrl);
                   13710:                     }
                   13711:                 } else {
                   13712:                     unlink($tmpcrl);
                   13713:                 }
                   13714:             } else {
                   13715:                 unlink($tmpcrl);
                   13716:             }
                   13717:         }
                   13718:     }
1.1380    raeburn  13719:     return ($msg,$hadchanges);
1.1379    raeburn  13720: }
                   13721: 
1.327     albertel 13722: # ------------------------------------------------------------ Read domain file
                   13723: {
1.852     albertel 13724:     my $loaded;
1.846     albertel 13725:     my %domain;
                   13726: 
1.852     albertel 13727:     sub parse_domain_tab {
                   13728: 	my ($lines) = @_;
                   13729: 	foreach my $line (@$lines) {
                   13730: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13731: 
1.846     albertel 13732: 	    chomp($line);
1.852     albertel 13733: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13734: 	    my %this_domain;
                   13735: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13736: 			       'lang_def', 'city', 'longi', 'lati',
                   13737: 			       'primary') {
                   13738: 		$this_domain{$field} = shift(@elements);
                   13739: 	    }
                   13740: 	    $domain{$name} = \%this_domain;
1.852     albertel 13741: 	}
                   13742:     }
1.864     albertel 13743: 
                   13744:     sub reset_domain_info {
                   13745: 	undef($loaded);
                   13746: 	undef(%domain);
                   13747:     }
                   13748: 
1.852     albertel 13749:     sub load_domain_tab {
1.1293    raeburn  13750: 	my ($ignore_cache,$nocache) = @_;
                   13751: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13752: 	my $fh;
1.1359    raeburn  13753: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13754: 	    my @lines = <$fh>;
                   13755: 	    &parse_domain_tab(\@lines);
1.448     albertel 13756: 	}
1.852     albertel 13757: 	close($fh);
                   13758: 	$loaded = 1;
1.327     albertel 13759:     }
1.846     albertel 13760: 
                   13761:     sub domain {
1.852     albertel 13762: 	&load_domain_tab() if (!$loaded);
                   13763: 
1.846     albertel 13764: 	my ($name,$what) = @_;
                   13765: 	return if ( !exists($domain{$name}) );
                   13766: 
                   13767: 	if (!$what) {
                   13768: 	    return $domain{$name}{'description'};
                   13769: 	}
                   13770: 	return $domain{$name}{$what};
                   13771:     }
1.974     raeburn  13772: 
                   13773:     sub domain_info {
                   13774:         &load_domain_tab() if (!$loaded);
                   13775:         return %domain;
                   13776:     }
                   13777: 
1.327     albertel 13778: }
                   13779: 
                   13780: 
1.1       albertel 13781: # ------------------------------------------------------------- Read hosts file
                   13782: {
1.838     albertel 13783:     my %hostname;
1.844     albertel 13784:     my %hostdom;
1.845     albertel 13785:     my %libserv;
1.852     albertel 13786:     my $loaded;
1.888     albertel 13787:     my %name_to_host;
1.1074    raeburn  13788:     my %internetdom;
1.1107    raeburn  13789:     my %LC_dns_serv;
1.852     albertel 13790: 
                   13791:     sub parse_hosts_tab {
                   13792: 	my ($file) = @_;
                   13793: 	foreach my $configline (@$file) {
                   13794: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13795:             chomp($configline);
                   13796: 	    if ($configline =~ /^\^/) {
                   13797:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13798:                     $LC_dns_serv{$1} = 1;
                   13799:                 }
                   13800:                 next;
                   13801:             }
1.1074    raeburn  13802: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13803: 	    $name=~s/\s//g;
                   13804: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13805:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13806:                     my $curr = $hostname{$id};
                   13807:                     my $skip;
                   13808:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13809:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13810:                             $skip = 1;
                   13811:                         } else {
                   13812:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13813:                         }
                   13814:                     }
                   13815:                     unless ($skip) {
                   13816:                         push(@{$name_to_host{$name}},$id);
                   13817:                     }
                   13818:                 } else {
                   13819:                     push(@{$name_to_host{$name}},$id);
                   13820:                 }
1.852     albertel 13821: 		$hostname{$id}=$name;
                   13822: 		$hostdom{$id}=$domain;
                   13823: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13824:                 if (defined($protocol)) {
                   13825:                     if ($protocol eq 'https') {
                   13826:                         $protocol{$id} = $protocol;
                   13827:                     } else {
                   13828:                         $protocol{$id} = 'http'; 
                   13829:                     }
1.968     raeburn  13830:                 } else {
1.969     raeburn  13831:                     $protocol{$id} = 'http';
1.968     raeburn  13832:                 }
1.1074    raeburn  13833:                 if (defined($intdom)) {
                   13834:                     $internetdom{$id} = $intdom;
                   13835:                 }
1.852     albertel 13836: 	    }
                   13837: 	}
                   13838:     }
1.864     albertel 13839:     
                   13840:     sub reset_hosts_info {
1.897     albertel 13841: 	&purge_remembered();
1.864     albertel 13842: 	&reset_domain_info();
                   13843: 	&reset_hosts_ip_info();
1.1339    raeburn  13844:         undef(%internetdom);
1.892     albertel 13845: 	undef(%name_to_host);
1.864     albertel 13846: 	undef(%hostname);
                   13847: 	undef(%hostdom);
                   13848: 	undef(%libserv);
                   13849: 	undef($loaded);
                   13850:     }
1.1       albertel 13851: 
1.852     albertel 13852:     sub load_hosts_tab {
1.1293    raeburn  13853: 	my ($ignore_cache,$nocache) = @_;
                   13854: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13855: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13856: 	my @config = <$config>;
                   13857: 	&parse_hosts_tab(\@config);
                   13858: 	close($config);
                   13859: 	$loaded=1;
1.1       albertel 13860:     }
1.852     albertel 13861: 
1.838     albertel 13862:     sub hostname {
1.852     albertel 13863: 	&load_hosts_tab() if (!$loaded);
                   13864: 
1.838     albertel 13865: 	my ($lonid) = @_;
                   13866: 	return $hostname{$lonid};
                   13867:     }
1.845     albertel 13868: 
1.838     albertel 13869:     sub all_hostnames {
1.852     albertel 13870: 	&load_hosts_tab() if (!$loaded);
                   13871: 
1.838     albertel 13872: 	return %hostname;
                   13873:     }
1.845     albertel 13874: 
1.888     albertel 13875:     sub all_names {
1.1293    raeburn  13876:         my ($ignore_cache,$nocache) = @_;
                   13877: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13878: 
                   13879: 	return %name_to_host;
                   13880:     }
                   13881: 
1.974     raeburn  13882:     sub all_host_domain {
                   13883:         &load_hosts_tab() if (!$loaded);
                   13884:         return %hostdom;
                   13885:     }
                   13886: 
1.1339    raeburn  13887:     sub all_host_intdom {
                   13888:         &load_hosts_tab() if (!$loaded);
                   13889:         return %internetdom;
                   13890:     }
                   13891: 
1.845     albertel 13892:     sub is_library {
1.852     albertel 13893: 	&load_hosts_tab() if (!$loaded);
                   13894: 
1.845     albertel 13895: 	return exists($libserv{$_[0]});
                   13896:     }
                   13897: 
                   13898:     sub all_library {
1.852     albertel 13899: 	&load_hosts_tab() if (!$loaded);
                   13900: 
1.845     albertel 13901: 	return %libserv;
                   13902:     }
                   13903: 
1.1062    droeschl 13904:     sub unique_library {
                   13905: 	#2x reverse removes all hostnames that appear more than once
                   13906:         my %unique = reverse &all_library();
                   13907:         return reverse %unique;
                   13908:     }
                   13909: 
1.841     albertel 13910:     sub get_servers {
1.852     albertel 13911: 	&load_hosts_tab() if (!$loaded);
                   13912: 
1.841     albertel 13913: 	my ($domain,$type) = @_;
                   13914: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13915: 	                                          : %hostname;
                   13916: 	my %result;
1.842     albertel 13917: 	if (ref($domain) eq 'ARRAY') {
                   13918: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13919: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13920: 		    $result{$host} = $hostname;
                   13921: 		}
                   13922: 	    }
                   13923: 	} else {
                   13924: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13925: 		if ($hostdom{$host} eq $domain) {
                   13926: 		    $result{$host} = $hostname;
                   13927: 		}
1.841     albertel 13928: 	    }
                   13929: 	}
                   13930: 	return %result;
                   13931:     }
1.845     albertel 13932: 
1.1062    droeschl 13933:     sub get_unique_servers {
                   13934:         my %unique = reverse &get_servers(@_);
                   13935: 	return reverse %unique;
                   13936:     }
                   13937: 
1.844     albertel 13938:     sub host_domain {
1.852     albertel 13939: 	&load_hosts_tab() if (!$loaded);
                   13940: 
1.844     albertel 13941: 	my ($lonid) = @_;
                   13942: 	return $hostdom{$lonid};
                   13943:     }
                   13944: 
1.841     albertel 13945:     sub all_domains {
1.852     albertel 13946: 	&load_hosts_tab() if (!$loaded);
                   13947: 
1.841     albertel 13948: 	my %seen;
                   13949: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13950: 	return @uniq;
                   13951:     }
1.1074    raeburn  13952: 
                   13953:     sub internet_dom {
                   13954:         &load_hosts_tab() if (!$loaded);
                   13955: 
                   13956:         my ($lonid) = @_;
                   13957:         return $internetdom{$lonid};
                   13958:     }
1.1107    raeburn  13959: 
                   13960:     sub is_LC_dns {
                   13961:         &load_hosts_tab() if (!$loaded);
                   13962: 
                   13963:         my ($hostname) = @_;
                   13964:         return exists($LC_dns_serv{$hostname});
                   13965:     }
                   13966: 
1.1       albertel 13967: }
                   13968: 
1.847     albertel 13969: { 
                   13970:     my %iphost;
1.856     albertel 13971:     my %name_to_ip;
                   13972:     my %lonid_to_ip;
1.869     albertel 13973: 
1.847     albertel 13974:     sub get_hosts_from_ip {
                   13975: 	my ($ip) = @_;
                   13976: 	my %iphosts = &get_iphost();
                   13977: 	if (ref($iphosts{$ip})) {
                   13978: 	    return @{$iphosts{$ip}};
                   13979: 	}
                   13980: 	return;
1.839     albertel 13981:     }
1.864     albertel 13982:     
                   13983:     sub reset_hosts_ip_info {
                   13984: 	undef(%iphost);
                   13985: 	undef(%name_to_ip);
                   13986: 	undef(%lonid_to_ip);
                   13987:     }
1.856     albertel 13988: 
                   13989:     sub get_host_ip {
                   13990: 	my ($lonid) = @_;
                   13991: 	if (exists($lonid_to_ip{$lonid})) {
                   13992: 	    return $lonid_to_ip{$lonid};
                   13993: 	}
                   13994: 	my $name=&hostname($lonid);
                   13995:    	my $ip = gethostbyname($name);
                   13996: 	return if (!$ip || length($ip) ne 4);
                   13997: 	$ip=inet_ntoa($ip);
                   13998: 	$name_to_ip{$name}   = $ip;
                   13999: 	$lonid_to_ip{$lonid} = $ip;
                   14000: 	return $ip;
                   14001:     }
1.847     albertel 14002:     
                   14003:     sub get_iphost {
1.1293    raeburn  14004: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14005: 
1.869     albertel 14006: 	if (!$ignore_cache) {
                   14007: 	    if (%iphost) {
                   14008: 		return %iphost;
                   14009: 	    }
                   14010: 	    my ($ip_info,$cached)=
                   14011: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14012: 	    if ($cached) {
                   14013: 		%iphost      = %{$ip_info->[0]};
                   14014: 		%name_to_ip  = %{$ip_info->[1]};
                   14015: 		%lonid_to_ip = %{$ip_info->[2]};
                   14016: 		return %iphost;
                   14017: 	    }
                   14018: 	}
1.894     albertel 14019: 
                   14020: 	# get yesterday's info for fallback
                   14021: 	my %old_name_to_ip;
                   14022: 	my ($ip_info,$cached)=
                   14023: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14024: 	if ($cached) {
                   14025: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14026: 	}
                   14027: 
1.1293    raeburn  14028: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14029: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14030: 	    my $ip;
                   14031: 	    if (!exists($name_to_ip{$name})) {
                   14032: 		$ip = gethostbyname($name);
                   14033: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14034: 		    if (defined($old_name_to_ip{$name})) {
                   14035: 			$ip = $old_name_to_ip{$name};
                   14036: 			&logthis("Can't find $name defaulting to old $ip");
                   14037: 		    } else {
                   14038: 			&logthis("Name $name no IP found");
                   14039: 			next;
                   14040: 		    }
                   14041: 		} else {
                   14042: 		    $ip=inet_ntoa($ip);
1.847     albertel 14043: 		}
                   14044: 		$name_to_ip{$name} = $ip;
                   14045: 	    } else {
                   14046: 		$ip = $name_to_ip{$name};
1.653     albertel 14047: 	    }
1.888     albertel 14048: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14049: 		$lonid_to_ip{$id} = $ip;
                   14050: 	    }
                   14051: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14052: 	}
1.1293    raeburn  14053:         unless ($nocache) {
                   14054: 	    &do_cache_new('iphost','iphost',
                   14055: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14056: 		          48*60*60);
                   14057:         }
1.869     albertel 14058: 
1.847     albertel 14059: 	return %iphost;
1.598     albertel 14060:     }
                   14061: 
1.992     raeburn  14062:     #
                   14063:     #  Given a DNS returns the loncapa host name for that DNS 
                   14064:     # 
                   14065:     sub host_from_dns {
                   14066:         my ($dns) = @_;
                   14067:         my @hosts;
                   14068:         my $ip;
                   14069: 
1.993     raeburn  14070:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14071:             $ip = $name_to_ip{$dns};
                   14072:         }
                   14073:         if (!$ip) {
                   14074:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14075:             if (length($ip) == 4) { 
                   14076: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14077:             }
                   14078:         }
                   14079:         if ($ip) {
                   14080: 	    @hosts = get_hosts_from_ip($ip);
                   14081: 	    return $hosts[0];
                   14082:         }
                   14083:         return undef;
1.986     foxr     14084:     }
1.992     raeburn  14085: 
1.1074    raeburn  14086:     sub get_internet_names {
                   14087:         my ($lonid) = @_;
                   14088:         return if ($lonid eq '');
                   14089:         my ($idnref,$cached)=
                   14090:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14091:         if ($cached) {
                   14092:             return $idnref;
                   14093:         }
                   14094:         my $ip = &get_host_ip($lonid);
                   14095:         my @hosts = &get_hosts_from_ip($ip);
                   14096:         my %iphost = &get_iphost();
                   14097:         my (@idns,%seen);
                   14098:         foreach my $id (@hosts) {
                   14099:             my $dom = &host_domain($id);
                   14100:             my $prim_id = &domain($dom,'primary');
                   14101:             my $prim_ip = &get_host_ip($prim_id);
                   14102:             next if ($seen{$prim_ip});
                   14103:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14104:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14105:                     my $intdom = &internet_dom($id);
                   14106:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14107:                         push(@idns,$intdom);
                   14108:                     }
                   14109:                 }
                   14110:             }
                   14111:             $seen{$prim_ip} = 1;
                   14112:         }
1.1219    raeburn  14113:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14114:     }
                   14115: 
1.986     foxr     14116: }
                   14117: 
1.1079    raeburn  14118: sub all_loncaparevs {
1.1249    raeburn  14119:     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  14120: }
                   14121: 
1.1227    raeburn  14122: # ---------------------------------------------------------- Read loncaparev table
                   14123: {
                   14124:     sub load_loncaparevs { 
                   14125:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14126:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14127:                 while (my $configline=<$config>) {
                   14128:                     chomp($configline);
                   14129:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14130:                     $loncaparevs{$hostid}=$loncaparev;
                   14131:                 }
                   14132:                 close($config);
                   14133:             }
                   14134:         }
                   14135:     }
                   14136: }
                   14137: 
                   14138: # ---------------------------------------------------------- Read serverhostID table
                   14139: {
                   14140:     sub load_serverhomeIDs {
                   14141:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14142:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14143:                 while (my $configline=<$config>) {
                   14144:                     chomp($configline);
                   14145:                     my ($name,$id)=split(/:/,$configline);
                   14146:                     $serverhomeIDs{$name}=$id;
                   14147:                 }
                   14148:                 close($config);
                   14149:             }
                   14150:         }
                   14151:     }
                   14152: }
                   14153: 
                   14154: 
1.862     albertel 14155: BEGIN {
                   14156: 
                   14157: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14158:     unless ($readit) {
                   14159: {
                   14160:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14161:     %perlvar = (%perlvar,%{$configvars});
                   14162: }
                   14163: 
                   14164: 
1.1       albertel 14165: # ------------------------------------------------------ Read spare server file
                   14166: {
1.1359    raeburn  14167:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14168: 
                   14169:     while (my $configline=<$config>) {
                   14170:        chomp($configline);
1.284     matthew  14171:        if ($configline) {
1.784     albertel 14172: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14173: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14174: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14175:        }
                   14176:     }
1.448     albertel 14177:     close($config);
1.1       albertel 14178: }
1.11      www      14179: # ------------------------------------------------------------ Read permissions
                   14180: {
1.1359    raeburn  14181:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14182: 
                   14183:     while (my $configline=<$config>) {
1.448     albertel 14184: 	chomp($configline);
                   14185: 	if ($configline) {
                   14186: 	    my ($role,$perm)=split(/ /,$configline);
                   14187: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14188: 	}
1.11      www      14189:     }
1.448     albertel 14190:     close($config);
1.11      www      14191: }
                   14192: 
                   14193: # -------------------------------------------- Read plain texts for permissions
                   14194: {
1.1359    raeburn  14195:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14196: 
                   14197:     while (my $configline=<$config>) {
1.448     albertel 14198: 	chomp($configline);
                   14199: 	if ($configline) {
1.742     raeburn  14200: 	    my ($short,@plain)=split(/:/,$configline);
                   14201:             %{$prp{$short}} = ();
                   14202: 	    if (@plain > 0) {
                   14203:                 $prp{$short}{'std'} = $plain[0];
                   14204:                 for (my $i=1; $i<@plain; $i++) {
                   14205:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14206:                 }
                   14207:             }
1.448     albertel 14208: 	}
1.135     www      14209:     }
1.448     albertel 14210:     close($config);
1.135     www      14211: }
                   14212: 
                   14213: # ---------------------------------------------------------- Read package table
                   14214: {
1.1359    raeburn  14215:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14216: 
                   14217:     while (my $configline=<$config>) {
1.483     albertel 14218: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14219: 	chomp($configline);
                   14220: 	my ($short,$plain)=split(/:/,$configline);
                   14221: 	my ($pack,$name)=split(/\&/,$short);
                   14222: 	if ($plain ne '') {
                   14223: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14224: 	    $packagetab{$short}=$plain; 
                   14225: 	}
1.11      www      14226:     }
1.448     albertel 14227:     close($config);
1.329     matthew  14228: }
                   14229: 
1.1073    raeburn  14230: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14231: 
                   14232: &load_loncaparevs();
1.1073    raeburn  14233: 
1.1074    raeburn  14234: # ---------------------------------------------------------- Read serverhostID table
                   14235: 
1.1227    raeburn  14236: &load_serverhomeIDs();
                   14237: 
                   14238: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14239: {
                   14240:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14241:     if (-e $file) {
                   14242:         my $parser = HTML::LCParser->new($file);
                   14243:         while (my $token = $parser->get_token()) {
                   14244:             if ($token->[0] eq 'S') {
                   14245:                 my $item = $token->[1];
                   14246:                 my $name = $token->[2]{'name'};
                   14247:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14248:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14249:                 my $namematch = $token->[2]{'namematch'};
                   14250:                 if ($item eq 'parameter') {
                   14251:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14252:                         my $release = $parser->get_text();
                   14253:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14254:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14255:                     }
                   14256:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14257:                     my $release = $parser->get_text();
                   14258:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14259:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14260:                 }
                   14261:             }
                   14262:         }
                   14263:     }
1.1073    raeburn  14264: }
                   14265: 
1.1138    raeburn  14266: # ---------------------------------------------------------- Read managers table
                   14267: {
                   14268:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14269:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14270:             while (my $configline=<$config>) {
                   14271:                 chomp($configline);
                   14272:                 next if ($configline =~ /^\#/);
                   14273:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14274:                     $managerstab{$configline} = 1;
                   14275:                 }
                   14276:             }
                   14277:             close($config);
                   14278:         }
                   14279:     }
                   14280: }
                   14281: 
1.329     matthew  14282: # ------------- set up temporary directory
                   14283: {
1.1117    foxr     14284:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14285: 
1.11      www      14286: }
                   14287: 
1.794     albertel 14288: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14289: 				'compress_threshold'=> 20_000,
                   14290:  			        });
1.185     www      14291: 
1.281     www      14292: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14293: $dumpcount=0;
1.958     www      14294: $locknum=0;
1.22      www      14295: 
1.163     harris41 14296: &logtouch();
1.672     albertel 14297: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14298: $readit=1;
1.564     albertel 14299:     {
                   14300: 	use integer;
                   14301: 	my $test=(2**32)+1;
1.568     albertel 14302: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14303: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14304:     }
1.195     www      14305: }
1.1       albertel 14306: }
1.179     www      14307: 
1.1       albertel 14308: 1;
1.191     harris41 14309: __END__
                   14310: 
1.243     albertel 14311: =pod
                   14312: 
1.191     harris41 14313: =head1 NAME
                   14314: 
1.243     albertel 14315: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14316: 
                   14317: =head1 SYNOPSIS
                   14318: 
1.243     albertel 14319: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14320: 
                   14321:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14322: 
1.243     albertel 14323: Common parameters:
                   14324: 
                   14325: =over 4
                   14326: 
                   14327: =item *
                   14328: 
                   14329: $uname : an internal username (if $cname expecting a course Id specifically)
                   14330: 
                   14331: =item *
                   14332: 
                   14333: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14334: 
                   14335: =item *
                   14336: 
                   14337: $symb : a resource instance identifier
                   14338: 
                   14339: =item *
                   14340: 
                   14341: $namespace : the name of a .db file that contains the data needed or
                   14342: being set.
                   14343: 
                   14344: =back
                   14345: 
1.394     bowersj2 14346: =head1 OVERVIEW
1.191     harris41 14347: 
1.394     bowersj2 14348: lonnet provides subroutines which interact with the
                   14349: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14350: about classes, users, and resources.
1.243     albertel 14351: 
                   14352: For many of these objects you can also use this to store data about
                   14353: them or modify them in various ways.
1.191     harris41 14354: 
1.394     bowersj2 14355: =head2 Symbs
1.191     harris41 14356: 
1.394     bowersj2 14357: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14358: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14359: map, the resource number of the resource in the map, and the URL of
                   14360: the resource itself. The latter is somewhat redundant, but might help
                   14361: if maps change.
                   14362: 
                   14363: An example is
                   14364: 
                   14365:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14366: 
                   14367: The respective map entry is
                   14368: 
                   14369:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14370:   title="Problem 2">
                   14371:  </resource>
                   14372: 
                   14373: Symbs are used by the random number generator, as well as to store and
                   14374: restore data specific to a certain instance of for example a problem.
                   14375: 
                   14376: =head2 Storing And Retrieving Data
                   14377: 
                   14378: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14379: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14380: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14381: is is the non-critical message twin of cstore. These functions are for
                   14382: handlers to store a perl hash to a user's permanent data space in an
                   14383: easy manner, and to retrieve it again on another call. It is expected
                   14384: that a handler would use this once at the beginning to retrieve data,
                   14385: and then again once at the end to send only the new data back.
                   14386: 
                   14387: The data is stored in the user's data directory on the user's
                   14388: homeserver under the ID of the course.
                   14389: 
                   14390: The hash that is returned by restore will have all of the previous
                   14391: value for all of the elements of the hash.
                   14392: 
                   14393: Example:
                   14394: 
                   14395:  #creating a hash
                   14396:  my %hash;
                   14397:  $hash{'foo'}='bar';
                   14398: 
                   14399:  #storing it
                   14400:  &Apache::lonnet::cstore(\%hash);
                   14401: 
                   14402:  #changing a value
                   14403:  $hash{'foo'}='notbar';
                   14404: 
                   14405:  #adding a new value
                   14406:  $hash{'bar'}='foo';
                   14407:  &Apache::lonnet::cstore(\%hash);
                   14408: 
                   14409:  #retrieving the hash
                   14410:  my %history=&Apache::lonnet::restore();
                   14411: 
                   14412:  #print the hash
                   14413:  foreach my $key (sort(keys(%history))) {
                   14414:    print("\%history{$key} = $history{$key}");
                   14415:  }
                   14416: 
                   14417: Will print out:
1.191     harris41 14418: 
1.394     bowersj2 14419:  %history{1:foo} = bar
                   14420:  %history{1:keys} = foo:timestamp
                   14421:  %history{1:timestamp} = 990455579
                   14422:  %history{2:bar} = foo
                   14423:  %history{2:foo} = notbar
                   14424:  %history{2:keys} = foo:bar:timestamp
                   14425:  %history{2:timestamp} = 990455580
                   14426:  %history{bar} = foo
                   14427:  %history{foo} = notbar
                   14428:  %history{timestamp} = 990455580
                   14429:  %history{version} = 2
                   14430: 
                   14431: Note that the special hash entries C<keys>, C<version> and
                   14432: C<timestamp> were added to the hash. C<version> will be equal to the
                   14433: total number of versions of the data that have been stored. The
                   14434: C<timestamp> attribute will be the UNIX time the hash was
                   14435: stored. C<keys> is available in every historical section to list which
                   14436: keys were added or changed at a specific historical revision of a
                   14437: hash.
                   14438: 
                   14439: B<Warning>: do not store the hash that restore returns directly. This
                   14440: will cause a mess since it will restore the historical keys as if the
                   14441: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14442: 
1.394     bowersj2 14443: Calling convention:
1.191     harris41 14444: 
1.1225    raeburn  14445:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14446:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14447: 
1.394     bowersj2 14448: For more detailed information, see lonnet specific documentation.
1.191     harris41 14449: 
1.394     bowersj2 14450: =head1 RETURN MESSAGES
1.191     harris41 14451: 
1.394     bowersj2 14452: =over 4
1.191     harris41 14453: 
1.394     bowersj2 14454: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14455: 
1.394     bowersj2 14456: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14457: when the connection is brought back up
1.191     harris41 14458: 
1.394     bowersj2 14459: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14460: for later delivery
1.191     harris41 14461: 
1.967     bisitz   14462: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14463: 
1.394     bowersj2 14464: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14465: that was requested
1.191     harris41 14466: 
1.243     albertel 14467: =back
1.191     harris41 14468: 
1.243     albertel 14469: =head1 PUBLIC SUBROUTINES
1.191     harris41 14470: 
1.243     albertel 14471: =head2 Session Environment Functions
1.191     harris41 14472: 
1.243     albertel 14473: =over 4
1.191     harris41 14474: 
1.394     bowersj2 14475: =item * 
                   14476: X<appenv()>
1.949     raeburn  14477: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14478: the user envirnoment file, and will be restored for each access this
1.620     albertel 14479: user makes during this session, also modifies the %env for the current
1.949     raeburn  14480: process. Optional rolesarrayref - if defined contains a reference to an array
                   14481: of roles which are exempt from the restriction on modifying user.role entries 
                   14482: in the user's environment.db and in %env.    
1.191     harris41 14483: 
                   14484: =item *
1.394     bowersj2 14485: X<delenv()>
1.987     raeburn  14486: B<delenv($delthis,$regexp)>: removes all items from the session
                   14487: environment file that begin with $delthis. If the 
                   14488: optional second arg - $regexp - is true, $delthis is treated as a 
                   14489: regular expression, otherwise \Q$delthis\E is used. 
                   14490: The values are also deleted from the current processes %env.
1.191     harris41 14491: 
1.795     albertel 14492: =item * get_env_multiple($name) 
                   14493: 
                   14494: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14495: values may be defined and end up as an array ref.
                   14496: 
                   14497: returns an array of values
                   14498: 
1.243     albertel 14499: =back
                   14500: 
                   14501: =head2 User Information
1.191     harris41 14502: 
1.243     albertel 14503: =over 4
1.191     harris41 14504: 
                   14505: =item *
1.394     bowersj2 14506: X<queryauthenticate()>
                   14507: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14508: authentication scheme
                   14509: 
                   14510: =item *
1.394     bowersj2 14511: X<authenticate()>
1.1073    raeburn  14512: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14513: authenticate user from domain's lib servers (first use the current
                   14514: one). C<$upass> should be the users password.
1.1073    raeburn  14515: $checkdefauth is optional (value is 1 if a check should be made to
                   14516:    authenticate user using default authentication method, and allow
                   14517:    account creation if username does not have account in the domain).
                   14518: $clientcancheckhost is optional (value is 1 if checking whether the
                   14519:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14520: 
                   14521: =item *
1.394     bowersj2 14522: X<homeserver()>
                   14523: B<homeserver($uname,$udom)>: find the server which has
                   14524: the user's directory and files (there must be only one), this caches
                   14525: the answer, and also caches if there is a borken connection.
1.191     harris41 14526: 
                   14527: =item *
1.394     bowersj2 14528: X<idget()>
1.1300    raeburn  14529: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14530: a list of student/employee IDs or clicker IDs
                   14531: (student/employee IDs are a unique resource in a domain, there must be 
                   14532: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14533: clickerIDs are not necessarily unique, as students might share clickers.
                   14534: (returns hash: id=>name,id=>name)
1.191     harris41 14535: 
                   14536: =item *
1.394     bowersj2 14537: X<idrget()>
                   14538: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14539: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14540: 
                   14541: =item *
1.394     bowersj2 14542: X<idput()>
1.1300    raeburn  14543: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14544: names and associated student/employee IDs or clicker IDs.
                   14545: 
                   14546: =item *
                   14547: X<iddel()>
                   14548: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14549: student/employee ID or clicker ID username look-ups from domain.
                   14550: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14551: If no $uhome is provided, it will be determined usig &homeserver()
                   14552: for each user.  If no $namespace is provided, the default is ids.
                   14553: 
                   14554: =item *
                   14555: X<updateclickers()>
                   14556: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14557: clicker ID-to-username look-ups in clickers.db on library server.
                   14558: Permitted actions are add or del (i.e., add or delete). The 
                   14559: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14560: value is an escaped comma-separated list of usernames (for whom the
                   14561: library server is the homeserver), who registered that particular ID.
                   14562: If $critical is true, the update will be sent via &critical, otherwise
                   14563: &reply() will be used.
1.191     harris41 14564: 
                   14565: =item *
1.394     bowersj2 14566: X<rolesinit()>
1.1169    droeschl 14567: B<rolesinit($udom,$username)>: get user privileges.
                   14568: returns user role, first access and timer interval hashes
1.243     albertel 14569: 
                   14570: =item *
1.1171    droeschl 14571: X<privileged()>
                   14572: B<privileged($username,$domain)>: returns a true if user has a
                   14573: privileged and active role (i.e. su or dc), false otherwise.
                   14574: 
                   14575: =item *
1.551     albertel 14576: X<getsection()>
                   14577: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14578: course $cname, return section name/number or '' for "not in course"
                   14579: and '-1' for "no section"
                   14580: 
                   14581: =item *
1.394     bowersj2 14582: X<userenvironment()>
                   14583: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14584: passed in @what from the requested user's environment, returns a hash
                   14585: 
1.858     raeburn  14586: =item * 
                   14587: X<userlog_query()>
1.859     albertel 14588: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14589: activity.log file. %filters defines filters applied when parsing the
                   14590: log file. These can be start or end timestamps, or the type of action
                   14591: - log to look for Login or Logout events, check for Checkin or
                   14592: Checkout, role for role selection. The response is in the form
                   14593: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14594: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14595: 
1.243     albertel 14596: =back
                   14597: 
                   14598: =head2 User Roles
                   14599: 
                   14600: =over 4
                   14601: 
                   14602: =item *
                   14603: 
1.1284    raeburn  14604: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14605: returns codes for allowed actions.
                   14606: 
                   14607: The first argument is required, all others are optional.
                   14608: 
                   14609: $priv is the privilege being checked.
                   14610: $uri contains additional information about what is being checked for access (e.g.,
                   14611: URL, course ID etc.). 
                   14612: $symb is the unique resource instance identifier in a course; if needed,
                   14613: but not provided, it will be retrieved via a call to &symbread(). 
                   14614: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14615: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14616: files).
                   14617: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14618: prevents recursive calls to &allowed.
                   14619: 
1.243     albertel 14620:  F: full access
                   14621:  U,I,K: authentication modes (cxx only)
                   14622:  '': forbidden
                   14623:  1: user needs to choose course
                   14624:  2: browse allowed
1.766     albertel 14625:  A: passphrase authentication needed
1.1284    raeburn  14626:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14627: 
                   14628: =item *
                   14629: 
1.1192    raeburn  14630: constructaccess($url,$setpriv) : check for access to construction space URL
                   14631: 
                   14632: See if the owner domain and name in the URL match those in the
                   14633: expected environment.  If so, return three element list
                   14634: ($ownername,$ownerdomain,$ownerhome).
                   14635: 
                   14636: Otherwise return the null string.
                   14637: 
                   14638: If second argument 'setpriv' is true, it assigns the privileges,
                   14639: and returns the same three element list, unless the owner has
                   14640: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14641: in which case the null string is returned.
                   14642: 
                   14643: =item *
                   14644: 
1.1326    raeburn  14645: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14646: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14647: for system, domain, and course level. $uname and $udom are optional (current
                   14648: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14649: 
                   14650: =item *
                   14651: 
1.988     raeburn  14652: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14653: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14654: $type is Course (default) or Community.
1.988     raeburn  14655: If $forcedefault evaluates to true, text returned will be default 
                   14656: text for $type. Otherwise, if this is a course, the text returned 
                   14657: will be a custom name for the role (if defined in the course's 
                   14658: environment).  If no custom name is defined the default is returned.
                   14659:    
1.832     raeburn  14660: =item *
                   14661: 
1.1219    raeburn  14662: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14663: All arguments are optional. Returns a hash of a roles, either for
                   14664: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14665: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14666: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14667: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14668: For each key, value is set to colon-separated start and end times for
                   14669: the role.  If no username and domain are specified, will default to
1.934     raeburn  14670: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14671: of role statuses (active, future or previous), roles 
                   14672: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14673: to restrict the list of roles reported. If no array ref is 
                   14674: provided for types, will default to return only active roles.
1.834     albertel 14675: 
1.1195    raeburn  14676: =item *
                   14677: 
                   14678: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14679: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14680: 
                   14681: Additional optional arguments are: $type (if role checking is to be restricted 
                   14682: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14683: available roles) or future (roles available in the future), and
                   14684: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14685: have active Domain Coordinator role in course's domain or in additional
                   14686: domains (specified in 'Domains to check for privileged users' in course
                   14687: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14688: 
                   14689: =item *
                   14690: 
                   14691: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14692: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14693: $possdomains and $possroles are optional array refs -- to domains to check and
                   14694: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14695: users' roles.db to check for a dc or su role in any domain. This can be
                   14696: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14697: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14698: this then allows &privileged_by_domain() to be used, which caches the identity
                   14699: of privileged users, eliminating the need for repeated calls to &dump().
                   14700: 
                   14701: =item *
                   14702: 
                   14703: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14704: where the outer hash keys are domains specified in the $possdomains array ref,
                   14705: next inner hash keys are privileged roles specified in the $roles array ref,
                   14706: and the innermost hash contains key = value pairs for username:domain = end:start
                   14707: for active or future "privileged" users with that role in that domain. To avoid
                   14708: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14709: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14710: 
1.243     albertel 14711: =back
                   14712: 
                   14713: =head2 User Modification
                   14714: 
                   14715: =over 4
                   14716: 
                   14717: =item *
                   14718: 
1.957     raeburn  14719: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14720: user for the level given by URL.  Optional start and end dates (leave empty
                   14721: string or zero for "no date")
1.191     harris41 14722: 
                   14723: =item *
                   14724: 
1.243     albertel 14725: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14726: change a users, password, possible return values are: ok,
                   14727: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14728: refused
1.191     harris41 14729: 
                   14730: =item *
                   14731: 
1.243     albertel 14732: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14733: 
                   14734: =item *
                   14735: 
1.1058    raeburn  14736: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14737:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14738: 
                   14739: will update user information (firstname,middlename,lastname,generation,
                   14740: permanentemail), and if forceid is true, student/employee ID also.
                   14741: A user's institutional affiliation(s) can also be updated.
                   14742: User information fields will not be overwritten with empty entries 
                   14743: unless the field is included in the $candelete array reference.
                   14744: This array is included when a single user is modified via "Manage Users",
                   14745: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14746: 
                   14747: =item *
                   14748: 
1.286     matthew  14749: modifystudent
                   14750: 
1.957     raeburn  14751: modify a student's enrollment and identification information.
1.1235    raeburn  14752: The course id is resolved based on the current user's environment.  
                   14753: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14754: associated with a course.
                   14755: 
1.297     matthew  14756: This call is essentially a wrapper for lonnet::modifyuser and
                   14757: lonnet::modify_student_enrollment
1.286     matthew  14758: 
                   14759: Inputs: 
                   14760: 
                   14761: =over 4
                   14762: 
1.957     raeburn  14763: =item B<$udom> Student's loncapa domain
1.286     matthew  14764: 
1.957     raeburn  14765: =item B<$uname> Student's loncapa login name
1.286     matthew  14766: 
1.964     bisitz   14767: =item B<$uid> Student/Employee ID
1.286     matthew  14768: 
1.957     raeburn  14769: =item B<$umode> Student's authentication mode
1.286     matthew  14770: 
1.957     raeburn  14771: =item B<$upass> Student's password
1.286     matthew  14772: 
1.957     raeburn  14773: =item B<$first> Student's first name
1.286     matthew  14774: 
1.957     raeburn  14775: =item B<$middle> Student's middle name
1.286     matthew  14776: 
1.957     raeburn  14777: =item B<$last> Student's last name
1.286     matthew  14778: 
1.957     raeburn  14779: =item B<$gene> Student's generation
1.286     matthew  14780: 
1.957     raeburn  14781: =item B<$usec> Student's section in course
1.286     matthew  14782: 
                   14783: =item B<$end> Unix time of the roles expiration
                   14784: 
                   14785: =item B<$start> Unix time of the roles start date
                   14786: 
                   14787: =item B<$forceid> If defined, allow $uid to be changed
                   14788: 
                   14789: =item B<$desiredhome> server to use as home server for student
                   14790: 
1.957     raeburn  14791: =item B<$email> Student's permanent e-mail address
                   14792: 
                   14793: =item B<$type> Type of enrollment (auto or manual)
                   14794: 
1.963     raeburn  14795: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14796: 
                   14797: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14798: 
1.963     raeburn  14799: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14800: 
1.963     raeburn  14801: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14802: 
1.1216    raeburn  14803: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14804: 
                   14805: =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  14806: 
1.286     matthew  14807: =back
1.297     matthew  14808: 
                   14809: =item *
                   14810: 
                   14811: modify_student_enrollment
                   14812: 
1.1235    raeburn  14813: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14814: 'role.request.course' must be defined for this function to proceed.
                   14815: 
                   14816: Inputs:
                   14817: 
                   14818: =over 4
                   14819: 
1.1235    raeburn  14820: =item $udom, student's domain
1.297     matthew  14821: 
1.1235    raeburn  14822: =item $uname, student's name
1.297     matthew  14823: 
1.1235    raeburn  14824: =item $uid, student's user id
1.297     matthew  14825: 
1.1235    raeburn  14826: =item $first, student's first name
1.297     matthew  14827: 
                   14828: =item $middle
                   14829: 
                   14830: =item $last
                   14831: 
                   14832: =item $gene
                   14833: 
                   14834: =item $usec
                   14835: 
                   14836: =item $end
                   14837: 
                   14838: =item $start
                   14839: 
1.957     raeburn  14840: =item $type
                   14841: 
                   14842: =item $locktype
                   14843: 
                   14844: =item $cid
                   14845: 
                   14846: =item $selfenroll
                   14847: 
                   14848: =item $context
                   14849: 
1.1216    raeburn  14850: =item $credits, number of credits student will earn from this class
                   14851: 
1.1314    raeburn  14852: =item $instsec, institutional course section code for student
                   14853: 
1.297     matthew  14854: =back
                   14855: 
1.191     harris41 14856: 
                   14857: =item *
                   14858: 
1.243     albertel 14859: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14860: custom role; give a custom role to a user for the level given by URL.  Specify
                   14861: name and domain of role author, and role name
1.191     harris41 14862: 
                   14863: =item *
                   14864: 
1.243     albertel 14865: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14866: 
                   14867: =item *
                   14868: 
1.243     albertel 14869: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14870: 
                   14871: =back
                   14872: 
                   14873: =head2 Course Infomation
                   14874: 
                   14875: =over 4
1.191     harris41 14876: 
                   14877: =item *
                   14878: 
1.1118    foxr     14879: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14880: specified course id, including all environment settings for the
                   14881: course, the description of the course will be in the hash under the
                   14882: key 'description'
1.191     harris41 14883: 
1.1118    foxr     14884: $options is an optional parameter that if supplied is a hash reference that controls
                   14885: what how this function works.  It has the following key/values:
                   14886: 
                   14887: =over 4
                   14888: 
                   14889: =item freshen_cache
                   14890: 
                   14891: If defined, and the environment cache for the course is valid, it is 
                   14892: returned in the returned hash.
                   14893: 
                   14894: =item one_time
                   14895: 
                   14896: If defined, the last cache time is set to _now_
                   14897: 
                   14898: =item user
                   14899: 
                   14900: If defined, the supplied username is used instead of the current user.
                   14901: 
                   14902: 
                   14903: =back
                   14904: 
1.191     harris41 14905: =item *
                   14906: 
1.624     albertel 14907: resdata($name,$domain,$type,@which) : request for current parameter
                   14908: setting for a specific $type, where $type is either 'course' or 'user',
                   14909: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14910: answers for 10 minutes.
1.243     albertel 14911: 
1.877     foxr     14912: =item *
                   14913: 
                   14914: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14915: data base, returning a hash that is keyed by the resource name and has
                   14916: values that are the resource value.  I believe that the timestamps and
                   14917: versions are also returned.
                   14918: 
1.1236    raeburn  14919: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14920: supplemental content area. This routine caches the number of files for 
                   14921: 10 minutes.
                   14922: 
1.243     albertel 14923: =back
                   14924: 
                   14925: =head2 Course Modification
                   14926: 
                   14927: =over 4
1.191     harris41 14928: 
                   14929: =item *
                   14930: 
1.243     albertel 14931: writecoursepref($courseid,%prefs) : write preferences (environment
                   14932: database) for a course
1.191     harris41 14933: 
                   14934: =item *
                   14935: 
1.1011    raeburn  14936: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14937: 
                   14938: =item *
                   14939: 
1.1038    raeburn  14940: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14941: 
1.1167    droeschl 14942: =item *
                   14943: 
                   14944: is_course($courseid), is_course($cdom, $cnum)
                   14945: 
                   14946: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14947: two component version $cdom, $cnum. It checks if the specified course exists.
                   14948: 
                   14949: Returns:
                   14950:     undef if the course doesn't exist, otherwise
                   14951:     in scalar context the combined courseid.
                   14952:     in list context the two components of the course identifier, domain and 
                   14953:     courseid.    
                   14954: 
1.243     albertel 14955: =back
                   14956: 
                   14957: =head2 Resource Subroutines
                   14958: 
                   14959: =over 4
1.191     harris41 14960: 
                   14961: =item *
                   14962: 
1.243     albertel 14963: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14964: 
                   14965: =item *
                   14966: 
1.243     albertel 14967: repcopy($filename) : subscribes to the requested file, and attempts to
                   14968: replicate from the owning library server, Might return
1.607     raeburn  14969: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14970: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14971: resource. Expects the local filesystem pathname
                   14972: (/home/httpd/html/res/....)
                   14973: 
                   14974: =back
                   14975: 
                   14976: =head2 Resource Information
                   14977: 
                   14978: =over 4
1.191     harris41 14979: 
                   14980: =item *
                   14981: 
1.1228    raeburn  14982: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14983: and returns the value of a variety of different possible values,
                   14984: $varname should be a request string, and the other parameters can be
                   14985: used to specify who and what one is asking about. Ordinarily, $cid 
                   14986: does not need to be specified, as it is retrived from 
                   14987: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14988: within lonuserstate::loadmap() when initializing a course, before
                   14989: $env{'request.course.id'} has been set, so it needs to be provided
                   14990: in that one case.
1.243     albertel 14991: 
                   14992: Possible values for $varname are environment.lastname (or other item
                   14993: from the envirnment hash), user.name (or someother aspect about the
                   14994: user), resource.0.maxtries (or some other part and parameter of a
                   14995: resource)
1.204     albertel 14996: 
                   14997: =item *
                   14998: 
1.243     albertel 14999: directcondval($number) : get current value of a condition; reads from a state
                   15000: string
1.204     albertel 15001: 
                   15002: =item *
                   15003: 
1.243     albertel 15004: condval($condidx) : value of condition index based on state
1.204     albertel 15005: 
                   15006: =item *
                   15007: 
1.1362    raeburn  15008: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15009: resource's metadata, $what should be either a specific key, or either
                   15010: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15011: packages that this resource currently uses, the last 3 arguments are 
                   15012: only used internally for recursive metadata.
                   15013: 
                   15014: the toolsymb is only used where the uri is for an external tool (for which
                   15015: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15016: 
1.1371    raeburn  15017: this function automatically caches all requests except any made recursively
                   15018: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15019: defined).
1.191     harris41 15020: 
                   15021: =item *
                   15022: 
1.243     albertel 15023: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15024: network of library servers; returns file handle of where SQL and regex results
                   15025: will be stored for query
1.191     harris41 15026: 
                   15027: =item *
                   15028: 
1.1282    raeburn  15029: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15030: return symbolic list entry (all arguments optional). 
                   15031: 
                   15032: Args: filename is the filename (including path) for the file for which a symb 
                   15033: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15034: to check access status if more than one resource was found in the bighash 
                   15035: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15036: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15037: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15038: cause possible symbs to be checked to determine if they are subject to content
                   15039: blocking, if so they will not be included as possible symbs; possibles is a
                   15040: ref to a hash, which, as a side effect, will be populated with all possible 
                   15041: symbs (content blocking not tested).
                   15042:  
1.243     albertel 15043: returns the data handle
1.191     harris41 15044: 
                   15045: =item *
                   15046: 
1.1190    raeburn  15047: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15048: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15049: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15050: on failure, user must be in a course, as it assumes the existence of
                   15051: the course initial hash, and uses $env('request.course.id'}.  The third
                   15052: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15053: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15054: encrypted; otherwise it will be null.  
1.191     harris41 15055: 
                   15056: =item *
                   15057: 
1.243     albertel 15058: symbclean($symb) : removes versions numbers from a symb, returns the
                   15059: cleaned symb
1.191     harris41 15060: 
                   15061: =item *
                   15062: 
1.243     albertel 15063: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15064: course map, user must be in a course for it to work.
1.191     harris41 15065: 
                   15066: =item *
                   15067: 
1.243     albertel 15068: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15069: 
                   15070: =item *
                   15071: 
1.243     albertel 15072: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15073: a random seed, all arguments are optional, if they aren't sent it uses the
                   15074: environment to derive them. Note: if symb isn't sent and it can't get one
                   15075: from &symbread it will use the current time as its return value
1.191     harris41 15076: 
                   15077: =item *
                   15078: 
1.243     albertel 15079: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15080: unfakeable, receipt
1.191     harris41 15081: 
                   15082: =item *
                   15083: 
1.620     albertel 15084: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15085: 
                   15086: =item *
                   15087: 
1.243     albertel 15088: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15089: 
                   15090: =item *
                   15091: 
1.243     albertel 15092: 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 15093: 
                   15094: =item *
                   15095: 
1.243     albertel 15096: 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 15097: 
                   15098: =item *
                   15099: 
1.243     albertel 15100: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15101: 
                   15102: =item *
                   15103: 
1.243     albertel 15104: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15105: forcing spreadsheet to reevaluate the resource scores next time.
                   15106: 
1.1195    raeburn  15107: =item * 
                   15108: 
1.1196    raeburn  15109: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15110: when viewing in course context.
1.1195    raeburn  15111: 
1.1196    raeburn  15112:  input: six args -- filename (decluttered), course number, course domain,
                   15113:                     url, symb (if registered) and group (if this is a 
                   15114:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15115: 
1.1196    raeburn  15116:  output: array of five scalars --
1.1195    raeburn  15117:          $cfile -- url for file editing if editable on current server
                   15118:          $home -- homeserver of resource (i.e., for author if published,
                   15119:                                           or course if uploaded.).
                   15120:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15121:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15122:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15123: 
                   15124: =item *
                   15125: 
                   15126: is_course_upload($file,$cnum,$cdom)
                   15127: 
                   15128: Used in course context to determine if current file was uploaded to 
                   15129: the course (i.e., would be found in /userfiles/docs on the course's 
                   15130: homeserver.
                   15131: 
                   15132:   input: 3 args -- filename (decluttered), course number and course domain.
                   15133:   output: boolean -- 1 if file was uploaded.
                   15134: 
1.243     albertel 15135: =back
                   15136: 
                   15137: =head2 Storing/Retreiving Data
                   15138: 
                   15139: =over 4
1.191     harris41 15140: 
                   15141: =item *
                   15142: 
1.1269    raeburn  15143: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15144: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15145: the remaining args aren't required and if they aren't passed or are '' they will
                   15146: be derived from the env (with the exception of $laststore, which is an 
                   15147: optional arg used when a user's submission is stored in grading).
                   15148: $laststore is $version=$timestamp, where $version is the most recent version
                   15149: number retrieved for the corresponding $symb in the $namespace db file, and
                   15150: $timestamp is the timestamp for that transaction (UNIX time).
                   15151: $laststore is currently only passed when cstore() is called by 
                   15152: structuretags::finalize_storage().
1.191     harris41 15153: 
                   15154: =item *
                   15155: 
1.1269    raeburn  15156: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15157: but uses critical subroutine
1.191     harris41 15158: 
                   15159: =item *
                   15160: 
1.243     albertel 15161: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15162: all args are optional
1.191     harris41 15163: 
                   15164: =item *
                   15165: 
1.717     albertel 15166: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15167: dumps the complete (or key matching regexp) namespace into a hash
                   15168: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15169: normally &store()ed into
                   15170: 
                   15171: $range should be either an integer '100' (give me the first 100
                   15172:                                            matching records)
                   15173:               or be  two integers sperated by a - with no spaces
                   15174:                  '30-50' (give me the 30th through the 50th matching
                   15175:                           records)
                   15176: 
                   15177: 
                   15178: =item *
                   15179: 
1.1269    raeburn  15180: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15181: replaces a &store() version of data with a replacement set of data
                   15182: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15183: reference. If $tolog is true, the transaction is logged in the courselog
                   15184: with an action=PUTSTORE.
1.717     albertel 15185: 
                   15186: =item *
                   15187: 
1.243     albertel 15188: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15189: works very similar to store/cstore, but all data is stored in a
                   15190: temporary location and can be reset using tmpreset, $storehash should
                   15191: be a hash reference, returns nothing on success
1.191     harris41 15192: 
                   15193: =item *
                   15194: 
1.243     albertel 15195: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15196: similar to restore, but all data is stored in a temporary location and
                   15197: can be reset using tmpreset. Returns a hash of values on success,
                   15198: error string otherwise.
1.191     harris41 15199: 
                   15200: =item *
                   15201: 
1.243     albertel 15202: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15203: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15204: 
                   15205: =item *
                   15206: 
1.243     albertel 15207: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15208: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15209: 
                   15210: =item *
                   15211: 
1.243     albertel 15212: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15213: namesp ($udom and $uname are optional)
1.191     harris41 15214: 
                   15215: =item *
                   15216: 
1.702     albertel 15217: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15218: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15219: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15220: 
1.702     albertel 15221: $range should be either an integer '100' (give me the first 100
                   15222:                                            matching records)
                   15223:               or be  two integers sperated by a - with no spaces
                   15224:                  '30-50' (give me the 30th through the 50th matching
                   15225:                           records)
1.449     matthew  15226: =item *
                   15227: 
                   15228: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15229: $store can be a scalar, an array reference, or if the amount to be 
                   15230: incremented is > 1, a hash reference.
                   15231: 
                   15232: ($udom and $uname are optional)
1.191     harris41 15233: 
                   15234: =item *
                   15235: 
1.243     albertel 15236: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15237: ($udom and $uname are optional)
1.191     harris41 15238: 
                   15239: =item *
                   15240: 
1.243     albertel 15241: cput($namespace,$storehash,$udom,$uname) : critical put
                   15242: ($udom and $uname are optional)
1.191     harris41 15243: 
                   15244: =item *
                   15245: 
1.748     albertel 15246: newput($namespace,$storehash,$udom,$uname) :
                   15247: 
                   15248: Attempts to store the items in the $storehash, but only if they don't
                   15249: currently exist, if this succeeds you can be certain that you have 
                   15250: successfully created a new key value pair in the $namespace db.
                   15251: 
                   15252: 
                   15253: Args:
                   15254:  $namespace: name of database to store values to
                   15255:  $storehash: hashref to store to the db
                   15256:  $udom: (optional) domain of user containing the db
                   15257:  $uname: (optional) name of user caontaining the db
                   15258: 
                   15259: Returns:
                   15260:  'ok' -> succeeded in storing all keys of $storehash
                   15261:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15262:                         least <key> already existed in the db (other
                   15263:                         requested keys may also already exist)
1.967     bisitz   15264:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15265:  'con_lost' -> unable to contact request server
                   15266:  'refused' -> action was not allowed by remote machine
                   15267: 
                   15268: 
                   15269: =item *
                   15270: 
1.243     albertel 15271: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15272: reference filled in from namesp (encrypts the return communication)
                   15273: ($udom and $uname are optional)
1.191     harris41 15274: 
                   15275: =item *
                   15276: 
1.243     albertel 15277: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15278: critical subroutine
                   15279: 
1.806     raeburn  15280: =item *
                   15281: 
1.860     raeburn  15282: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15283: array reference filled in from namespace found in domain level on either
                   15284: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15285: 
                   15286: =item *
                   15287: 
1.860     raeburn  15288: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15289: domain level either on specified domain server ($uhome) or primary domain 
                   15290: server ($udom and $uhome are optional)
1.806     raeburn  15291: 
1.943     raeburn  15292: =item * 
                   15293: 
1.1240    raeburn  15294: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15295: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15296: the target domain.
                   15297: 
                   15298: May also include additional key => value pairs for the following groups:
                   15299: 
                   15300: =over
                   15301: 
                   15302: =item
                   15303: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15304: 
                   15305: =over
                   15306: 
                   15307: =item defaultquota, authorquota
                   15308: 
                   15309: =back
                   15310: 
                   15311: =item
                   15312: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15313: portfolio for users).
                   15314: 
                   15315: =over
                   15316: 
                   15317: =item
                   15318: aboutme, blog, webdav, portfolio
                   15319: 
                   15320: =back
                   15321: 
                   15322: =item
                   15323: requestcourses: ability to request courses, and how requests are processed.
                   15324: 
                   15325: =over
                   15326: 
                   15327: =item
1.1305    raeburn  15328: official, unofficial, community, textbook, placement
1.1240    raeburn  15329: 
                   15330: =back
                   15331: 
                   15332: =item
                   15333: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15334: 
                   15335: =over
                   15336: 
                   15337: =item
1.1256    raeburn  15338: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15339: 
                   15340: =back
                   15341: 
                   15342: =item
                   15343: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15344: for course's uploaded content.
                   15345: 
                   15346: =over
                   15347: 
                   15348: =item
1.1246    raeburn  15349: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15350: communityquota, textbookquota, placementquota
1.1240    raeburn  15351: 
                   15352: =back
                   15353: 
                   15354: =item
                   15355: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15356: on your servers.
                   15357: 
                   15358: =over
                   15359: 
                   15360: =item 
                   15361: remotesessions, hostedsessions
                   15362: 
                   15363: =back
                   15364: 
                   15365: =back
                   15366: 
                   15367: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15368: utility to create a configuration.db file on a domain's primary library server 
                   15369: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15370: -- corresponding values are authentication type (internal, krb4, krb5,
                   15371: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15372: will be available. Values are retrieved from cache (if current), unless the
                   15373: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15374: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15375: 
                   15376: Typical usage:
1.943     raeburn  15377: 
1.1240    raeburn  15378: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15379: 
1.243     albertel 15380: =back
                   15381: 
                   15382: =head2 Network Status Functions
                   15383: 
                   15384: =over 4
1.191     harris41 15385: 
                   15386: =item *
                   15387: 
1.1137    raeburn  15388: dirlist() : return directory list based on URI (first arg).
                   15389: 
                   15390: Inputs: 1 required, 5 optional.
                   15391: 
                   15392: =over
                   15393: 
                   15394: =item 
                   15395: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15396: 
                   15397: =item
                   15398: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15399: 
                   15400: =item
                   15401: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15402: 
                   15403: =item
                   15404: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15405: 
                   15406: =item
                   15407: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15408: 
                   15409: =item 
                   15410: $alternateRoot - path to prepend in place of path from $uri.
                   15411: 
                   15412: =back
                   15413: 
                   15414: Returns: Array of up to two items.
                   15415: 
                   15416: =over
                   15417: 
                   15418: a reference to an array of files/subdirectories
                   15419: 
                   15420: =over
                   15421: 
                   15422: Each element in the array of files/subdirectories is a & separated list of
                   15423: item name and the result of running stat on the item.  If dirlist was requested
                   15424: for a file instead of a directory, the item name will be ''. For a directory 
                   15425: listing, if the item is a metadata file, the element will end &N&M 
                   15426: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15427: default copyright set (1).  
                   15428: 
                   15429: =back
                   15430: 
                   15431: a scalar containing error condition (if encountered).
                   15432: 
                   15433: =over
                   15434: 
                   15435: =item 
                   15436: no_host (no homeserver identified for $username:$domain).
                   15437: 
                   15438: =item 
                   15439: no_such_host (server contacted for listing not identified as valid host).
                   15440: 
                   15441: =item 
                   15442: con_lost (connection to remote server failed).
                   15443: 
                   15444: =item 
                   15445: refused (invalid $username:$domain received on lond side).
                   15446: 
                   15447: =item 
                   15448: no_such_dir (directory at specified path on lond side does not exist). 
                   15449: 
                   15450: =item 
                   15451: empty (directory at specified path on lond side is empty).
                   15452: 
                   15453: =over
                   15454: 
                   15455: This is currently not encountered because the &ls3, &ls2, 
                   15456: &ls (_handler) routines on the lond side do not filter out
                   15457: . and .. from a directory listing. 
                   15458: 
                   15459: =back
                   15460: 
                   15461: =back
                   15462: 
                   15463: =back
1.191     harris41 15464: 
                   15465: =item *
                   15466: 
1.243     albertel 15467: spareserver() : find server with least workload from spare.tab
                   15468: 
1.986     foxr     15469: 
                   15470: =item *
                   15471: 
                   15472: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15473: if there is no corresponding loncapa host.
                   15474: 
1.243     albertel 15475: =back
                   15476: 
1.986     foxr     15477: 
1.243     albertel 15478: =head2 Apache Request
                   15479: 
                   15480: =over 4
1.191     harris41 15481: 
                   15482: =item *
                   15483: 
1.243     albertel 15484: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15485: localhost, posts hash
                   15486: 
                   15487: =back
                   15488: 
                   15489: =head2 Data to String to Data
                   15490: 
                   15491: =over 4
1.191     harris41 15492: 
                   15493: =item *
                   15494: 
1.243     albertel 15495: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15496: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15497: 
                   15498: =item *
                   15499: 
1.243     albertel 15500: hashref2str($hashref) : convert a hashref into a string complete with
                   15501: escaping and '=' and '&' separators, supports elements that are
                   15502: arrayrefs and hashrefs
1.191     harris41 15503: 
                   15504: =item *
                   15505: 
1.243     albertel 15506: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15507: with escaping and '&' separators, supports elements that are arrayrefs
                   15508: and hashrefs
1.191     harris41 15509: 
                   15510: =item *
                   15511: 
1.243     albertel 15512: str2hash($string) : convert string to hash using unescaping and
                   15513: splitting on '=' and '&', supports elements that are arrayrefs and
                   15514: hashrefs
1.191     harris41 15515: 
                   15516: =item *
                   15517: 
1.243     albertel 15518: str2array($string) : convert string to hash using unescaping and
                   15519: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15520: 
                   15521: =back
                   15522: 
                   15523: =head2 Logging Routines
                   15524: 
                   15525: 
                   15526: These routines allow one to make log messages in the lonnet.log and
                   15527: lonnet.perm logfiles.
1.191     harris41 15528: 
1.1119    foxr     15529: =over 4
                   15530: 
1.191     harris41 15531: =item *
                   15532: 
1.243     albertel 15533: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15534: 
                   15535: =item *
                   15536: 
1.243     albertel 15537: logthis() : append message to the normal lonnet.log file, it gets
                   15538: preiodically rolled over and deleted.
1.191     harris41 15539: 
                   15540: =item *
                   15541: 
1.243     albertel 15542: logperm() : append a permanent message to lonnet.perm.log, this log
                   15543: file never gets deleted by any automated portion of the system, only
                   15544: messages of critical importance should go in here.
                   15545: 
1.1119    foxr     15546: 
1.243     albertel 15547: =back
                   15548: 
                   15549: =head2 General File Helper Routines
                   15550: 
                   15551: =over 4
1.191     harris41 15552: 
                   15553: =item *
                   15554: 
1.481     raeburn  15555: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15556: (a) files in /uploaded
                   15557:   (i) If a local copy of the file exists - 
                   15558:       compares modification date of local copy with last-modified date for 
                   15559:       definitive version stored on home server for course. If local copy is 
                   15560:       stale, requests a new version from the home server and stores it. 
                   15561:       If the original has been removed from the home server, then local copy 
                   15562:       is unlinked.
                   15563:   (ii) If local copy does not exist -
                   15564:       requests the file from the home server and stores it. 
                   15565:   
                   15566:   If $caller is 'uploadrep':  
                   15567:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15568:     for request for files originally uploaded via DOCS. 
                   15569:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15570:   
                   15571:   Otherwise:
                   15572:      This indicates a call from the content generation phase of the request.
                   15573:      -  returns the entire contents of the file or -1.
                   15574:      
                   15575: (b) files in /res
                   15576:    - returns the entire contents of a file or -1; 
                   15577:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15578: 
1.712     albertel 15579: 
                   15580: =item *
                   15581: 
                   15582: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15583:                   reference
                   15584: 
                   15585: returns either a stat() list of data about the file or an empty list
                   15586: if the file doesn't exist or couldn't find out about it (connection
                   15587: problems or user unknown)
                   15588: 
1.191     harris41 15589: =item *
                   15590: 
1.243     albertel 15591: filelocation($dir,$file) : returns file system location of a file
                   15592: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15593: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15594: and a file of ../bob will become /a/bob)
1.191     harris41 15595: 
                   15596: =item *
                   15597: 
                   15598: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15599: filelocation except for hrefs
                   15600: 
                   15601: =item *
                   15602: 
1.1261    raeburn  15603: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15604: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15605: 
1.243     albertel 15606: =back
                   15607: 
1.608     albertel 15608: =head2 Usererfile file routines (/uploaded*)
                   15609: 
                   15610: =over 4
                   15611: 
                   15612: =item *
                   15613: 
                   15614: userfileupload(): main rotine for putting a file in a user or course's
                   15615:                   filespace, arguments are,
                   15616: 
1.620     albertel 15617:  formname - required - this is the name of the element in $env where the
1.608     albertel 15618:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15619:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15620:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15621:  context - if coursedoc, store the file in the course of the active role
                   15622:              of the current user; 
                   15623:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15624:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15625:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15626:          if undefined, it will be placed in "unknown"
                   15627: 
                   15628:  (This routine calls clean_filename() to remove any dangerous
                   15629:  characters from the filename, and then calls finuserfileupload() to
                   15630:  complete the transaction)
                   15631: 
                   15632:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15633:  and /adm/notfound.html if unsuccessful
                   15634: 
                   15635: =item *
                   15636: 
                   15637: clean_filename(): routine for cleaing a filename up for storage in
                   15638:                  userfile space, argument is:
                   15639: 
                   15640:  filename - proposed filename
                   15641: 
                   15642: returns: the new clean filename
                   15643: 
                   15644: =item *
                   15645: 
1.1090    raeburn  15646: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15647: userspace, probably shouldn't be called directly
                   15648: 
                   15649:   docuname: username or courseid of destination for the file
                   15650:   docudom: domain of user/course of destination for the file
                   15651:   formname: same as for userfileupload()
1.1090    raeburn  15652:   fname: filename (including subdirectories) for the file
                   15653:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15654:   allfiles: reference to hash used to store objects found by parser
                   15655:   codebase: reference to hash used for codebases of java objects found by parser
                   15656:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15657:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15658:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15659:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15660:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15661:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15662:   mimetype: reference to scalar to accommodate mime type determined
                   15663:             from File::MMagic if $parser = parse.
1.608     albertel 15664: 
                   15665:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15666:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15667:  was 'overwrite').
                   15668:  
1.608     albertel 15669: 
                   15670: =item *
                   15671: 
                   15672: renameuserfile(): renames an existing userfile to a new name
                   15673: 
                   15674:   Args:
                   15675:    docuname: username or courseid of destination for the file
                   15676:    docudom: domain of user/course of destination for the file
                   15677:    old: current file name (including any subdirs under userfiles)
                   15678:    new: desired file name (including any subdirs under userfiles)
                   15679: 
                   15680: =item *
                   15681: 
                   15682: mkdiruserfile(): creates a directory is a userfiles dir
                   15683: 
                   15684:   Args:
                   15685:    docuname: username or courseid of destination for the file
                   15686:    docudom: domain of user/course of destination for the file
                   15687:    dir: dir to create (including any subdirs under userfiles)
                   15688: 
                   15689: =item *
                   15690: 
                   15691: removeuserfile(): removes a file that exists in userfiles
                   15692: 
                   15693:   Args:
                   15694:    docuname: username or courseid of destination for the file
                   15695:    docudom: domain of user/course of destination for the file
                   15696:    fname: filname to delete (including any subdirs under userfiles)
                   15697: 
                   15698: =item *
                   15699: 
                   15700: removeuploadedurl(): convience function for removeuserfile()
                   15701: 
                   15702:   Args:
                   15703:    url:  a full /uploaded/... url to delete
                   15704: 
1.747     albertel 15705: =item * 
                   15706: 
                   15707: get_portfile_permissions():
                   15708:   Args:
                   15709:     domain: domain of user or course contain the portfolio files
                   15710:     user: name of user or num of course contain the portfolio files
                   15711:   Returns:
                   15712:     hashref of a dump of the proper file_permissions.db
                   15713:    
                   15714: 
                   15715: =item * 
                   15716: 
                   15717: get_access_controls():
                   15718: 
                   15719: Args:
                   15720:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15721:   group: (optional) the group you want the files associated with
                   15722:   file: (optional) the file you want access info on
                   15723: 
                   15724: Returns:
1.749     raeburn  15725:     a hash (keys are file names) of hashes containing
                   15726:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15727:         values are XML containing access control settings (see below) 
1.747     albertel 15728: 
                   15729: Internal notes:
                   15730: 
1.749     raeburn  15731:  access controls are stored in file_permissions.db as key=value pairs.
                   15732:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15733:         where scope -> public,guest,course,group,domains or users.
                   15734:               end -> UNIX time for end of access (0 -> no end date)
                   15735:               start -> UNIX time for start of access
                   15736: 
                   15737:     value -> XML description of access control
                   15738:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15739:             <start></start>
                   15740:             <end></end>
                   15741: 
                   15742:             <password></password>  for scope type = guest
                   15743: 
                   15744:             <domain></domain>     for scope type = course or group
                   15745:             <number></number>
                   15746:             <roles id="">
                   15747:              <role></role>
                   15748:              <access></access>
                   15749:              <section></section>
                   15750:              <group></group>
                   15751:             </roles>
                   15752: 
                   15753:             <dom></dom>         for scope type = domains
                   15754: 
                   15755:             <users>             for scope type = users
                   15756:              <user>
                   15757:               <uname></uname>
                   15758:               <udom></udom>
                   15759:              </user>
                   15760:             </users>
                   15761:            </scope> 
                   15762:               
                   15763:  Access data is also aggregated for each file in an additional key=value pair:
                   15764:  key -> path to file/file_name\0accesscontrol 
                   15765:  value -> reference to hash
                   15766:           hash contains key = value pairs
                   15767:           where key = uniqueID:scope_end_start
                   15768:                 value = UNIX time record was last updated
                   15769: 
                   15770:           Used to improve speed of look-ups of access controls for each file.  
                   15771:  
                   15772:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15773: 
1.1198    raeburn  15774: =item *
                   15775: 
1.749     raeburn  15776: modify_access_controls():
                   15777: 
                   15778: Modifies access controls for a portfolio file
                   15779: Args
                   15780: 1. file name
                   15781: 2. reference to hash of required changes,
                   15782: 3. domain
                   15783: 4. username
                   15784:   where domain,username are the domain of the portfolio owner 
                   15785:   (either a user or a course) 
                   15786: 
                   15787: Returns:
                   15788: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15789: 2. result of deletions ('ok' or 'error', with error message).
                   15790: 3. reference to hash of any new or updated access controls.
                   15791: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15792:    key = integer (inbound ID)
1.1198    raeburn  15793:    value = uniqueID
                   15794: 
                   15795: =item *
                   15796: 
                   15797: get_timebased_id():
                   15798: 
                   15799: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15800: course via the Course Editor (e.g., folders, composite pages, 
                   15801: group bulletin boards).
                   15802: 
                   15803: Args: (first three required; six others optional)
                   15804: 
                   15805: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15806:    docssequence, or name of group
                   15807: 
                   15808: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15809:    e.g., num, boardids
                   15810: 
                   15811: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15812:    file will be named nohist_namespace.db
                   15813: 
                   15814: 4. cdom: domain of course; default is current course domain from %env
                   15815: 
                   15816: 5. cnum: course number; default is current course number from %env
                   15817: 
                   15818: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15819:    unix timestamp to form the suffix, if the plain timestamp is already
                   15820:    in use.  Default is to not do this, but simply increment the unix 
                   15821:    timestamp by 1 until a unique key is obtained.
                   15822: 
                   15823: 7. who: holder of locking key; defaults to user:domain for user.
                   15824: 
                   15825: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15826:    retrying); default is 3.
                   15827: 
                   15828: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15829: 
                   15830: Returns:
                   15831: 
                   15832: 1. suffix obtained (numeric)
                   15833: 
                   15834: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15835: 
                   15836: 3. error: contains (localized) error message if an error occurred.
                   15837: 
1.747     albertel 15838: 
1.608     albertel 15839: =back
                   15840: 
1.243     albertel 15841: =head2 HTTP Helper Routines
                   15842: 
                   15843: =over 4
                   15844: 
1.191     harris41 15845: =item *
                   15846: 
                   15847: escape() : unpack non-word characters into CGI-compatible hex codes
                   15848: 
                   15849: =item *
                   15850: 
                   15851: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15852: 
1.243     albertel 15853: =back
                   15854: 
                   15855: =head1 PRIVATE SUBROUTINES
                   15856: 
                   15857: =head2 Underlying communication routines (Shouldn't call)
                   15858: 
                   15859: =over 4
                   15860: 
                   15861: =item *
                   15862: 
                   15863: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15864: 
                   15865: =item *
                   15866: 
                   15867: reply() : uses subreply to send a message to remote machine, logs all failures
                   15868: 
                   15869: =item *
                   15870: 
                   15871: critical() : passes a critical message to another server; if cannot
                   15872: get through then place message in connection buffer directory and
                   15873: returns con_delayed, if incapable of saving message, returns
                   15874: con_failed
                   15875: 
                   15876: =item *
                   15877: 
                   15878: reconlonc() : tries to reconnect lonc client processes.
                   15879: 
                   15880: =back
                   15881: 
                   15882: =head2 Resource Access Logging
                   15883: 
                   15884: =over 4
                   15885: 
                   15886: =item *
                   15887: 
                   15888: flushcourselogs() : flush (save) buffer logs and access logs
                   15889: 
                   15890: =item *
                   15891: 
                   15892: courselog($what) : save message for course in hash
                   15893: 
                   15894: =item *
                   15895: 
                   15896: courseacclog($what) : save message for course using &courselog().  Perform
                   15897: special processing for specific resource types (problems, exams, quizzes, etc).
                   15898: 
1.191     harris41 15899: =item *
                   15900: 
                   15901: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15902: as a PerlChildExitHandler
1.243     albertel 15903: 
                   15904: =back
                   15905: 
                   15906: =head2 Other
                   15907: 
                   15908: =over 4
                   15909: 
                   15910: =item *
                   15911: 
                   15912: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15913: 
                   15914: =back
                   15915: 
                   15916: =cut
1.877     foxr     15917: 

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