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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1388  ! raeburn     4: # $Id: lonnet.pm,v 1.1387 2018/11/01 04:33: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);
1.1388  ! raeburn   240:     if ($context eq 'install') {
1.1387    raeburn   241:         $uselocal = 1;
                    242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   243:         $uselocal = 1;
                    244:     }
1.1387    raeburn   245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   247:         if ($distro eq '') {
                    248:             $uselocal = 0;
                    249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   250:             if ($1 < 6) {
                    251:                 $uselocal = 0;
                    252:             }
1.1346    raeburn   253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    254:             if ($1 < 12) {
                    255:                 $uselocal = 0;
                    256:             }
1.1315    raeburn   257:         }
                    258:     }
                    259:     if ($uselocal) {
1.1383    raeburn   260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   261:     } else {
                    262:         $rep=&reply('servercerts',$lonhost);
                    263:     }
                    264:     my ($result,%returnhash);
                    265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    266:         ($rep eq 'unknown_cmd')) {
                    267:         $result = $rep;
                    268:     } else {
                    269:         $result = 'ok';
                    270:         my @pairs=split(/\&/,$rep);
                    271:         foreach my $item (@pairs) {
                    272:             my ($key,$value)=split(/=/,$item,2);
                    273:             my $what = &unescape($key);
                    274:             $returnhash{$what}=&thaw_unescape($value);
                    275:         }
                    276:     }
                    277:     return ($result,\%returnhash);
                    278: }
                    279: 
1.993     raeburn   280: sub get_server_loncaparev {
1.1073    raeburn   281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   282:     if (defined($lonhost)) {
                    283:         if (!defined(&hostname($lonhost))) {
                    284:             undef($lonhost);
                    285:         }
                    286:     }
                    287:     if (!defined($lonhost)) {
                    288:         if (defined(&domain($dom,'primary'))) {
                    289:             $lonhost=&domain($dom,'primary');
                    290:             if ($lonhost eq 'no_host') {
                    291:                 undef($lonhost);
                    292:             }
                    293:         }
                    294:     }
                    295:     if (defined($lonhost)) {
1.1073    raeburn   296:         my $cachetime = 12*3600;
                    297:         if (!$ignore_cache) {
                    298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    299:             if (defined($cached)) {
                    300:                 return $loncaparev;
                    301:             }
                    302:         }
                    303:         my ($answer,$loncaparev);
                    304:         my @ids=&current_machine_ids();
                    305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    306:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   308:                 $loncaparev = $1;
                    309:             }
                    310:         } else {
                    311:             $answer = &reply('serverloncaparev',$lonhost);
                    312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    313:                 if ($caller eq 'loncron') {
                    314:                     my $protocol = $protocol{$lonhost};
                    315:                     $protocol = 'http' if ($protocol ne 'https');
                    316:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    317:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   318:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   319:                     unless ($response->is_error()) {
                    320:                         my $content = $response->content;
1.1081    raeburn   321:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   322:                             $loncaparev = $1;
                    323:                         }
                    324:                     }
                    325:                 } else {
                    326:                     $loncaparev = $loncaparevs{$lonhost};
                    327:                 }
1.1081    raeburn   328:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   329:                 $loncaparev = $1;
                    330:             }
1.993     raeburn   331:         }
1.1073    raeburn   332:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   333:     }
                    334: }
                    335: 
1.1074    raeburn   336: sub get_server_homeID {
                    337:     my ($hostname,$ignore_cache,$caller) = @_;
                    338:     unless ($ignore_cache) {
                    339:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    340:         if (defined($cached)) {
                    341:             return $serverhomeID;
                    342:         }
                    343:     }
                    344:     my $cachetime = 12*3600;
                    345:     my $serverhomeID;
                    346:     if ($caller eq 'loncron') { 
                    347:         my @machine_ids = &machine_ids($hostname);
                    348:         foreach my $id (@machine_ids) {
                    349:             my $response = &reply('serverhomeID',$id);
                    350:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    351:                 $serverhomeID = $response;
                    352:                 last;
                    353:             }
                    354:         }
                    355:         if ($serverhomeID eq '') {
                    356:             $serverhomeID = $machine_ids[-1];
                    357:         }
                    358:     } else {
                    359:         $serverhomeID = $serverhomeIDs{$hostname};
                    360:     }
                    361:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    362: }
                    363: 
1.1121    raeburn   364: sub get_remote_globals {
                    365:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   366:     my ($result,%returnhash,%whatneeded);
                    367:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   368:         foreach my $what (sort(keys(%{$whathash}))) {
                    369:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   370:             my ($response,$cached);
1.1121    raeburn   371:             unless ($ignore_cache) {
1.1125    raeburn   372:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   373:             }
                    374:             if (defined($cached)) {
1.1125    raeburn   375:                 $returnhash{$what} = $response;
1.1121    raeburn   376:             } else {
1.1125    raeburn   377:                 $whatneeded{$what} = 1;
1.1121    raeburn   378:             }
                    379:         }
1.1125    raeburn   380:         if (keys(%whatneeded) == 0) {
                    381:             $result = 'ok';
                    382:         } else {
1.1121    raeburn   383:             my $requested = &freeze_escape(\%whatneeded);
                    384:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   385:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    386:                 ($rep eq 'unknown_cmd')) {
                    387:                 $result = $rep;
                    388:             } else {
                    389:                 $result = 'ok';
1.1121    raeburn   390:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   391:                 foreach my $item (@pairs) {
                    392:                     my ($key,$value)=split(/=/,$item,2);
                    393:                     my $what = &unescape($key);
                    394:                     my $hashid = $lonhost.'-'.$what;
                    395:                     $returnhash{$what}=&thaw_unescape($value);
                    396:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   397:                 }
                    398:             }
                    399:         }
                    400:     }
1.1125    raeburn   401:     return ($result,\%returnhash);
1.1121    raeburn   402: }
                    403: 
1.1124    raeburn   404: sub remote_devalidate_cache {
1.1241    raeburn   405:     my ($lonhost,$cachekeys) = @_;
                    406:     my $items;
                    407:     return unless (ref($cachekeys) eq 'ARRAY');
                    408:     my $cachestr = join('&',@{$cachekeys});
                    409:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   410:     return $response;
                    411: }
                    412: 
1.1       albertel  413: # -------------------------------------------------- Non-critical communication
                    414: sub subreply {
                    415:     my ($cmd,$server)=@_;
1.838     albertel  416:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      417:     #
                    418:     #  With loncnew process trimming, there's a timing hole between lonc server
                    419:     #  process exit and the master server picking up the listen on the AF_UNIX
                    420:     #  socket.  In that time interval, a lock file will exist:
                    421: 
                    422:     my $lockfile=$peerfile.".lock";
                    423:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   424: 	sleep(0.1);
1.549     foxr      425:     }
                    426:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      427:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      428:     #
1.550     foxr      429:     #   We'll give the connection a few tries before abandoning it.  If
                    430:     #   connection is not possible, we'll con_lost back to the client.
                    431:     #   
                    432:     my $client;
                    433:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    434: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    435: 				      Type    => SOCK_STREAM,
                    436: 				      Timeout => 10);
1.869     albertel  437: 	if ($client) {
1.550     foxr      438: 	    last;		# Connected!
1.850     albertel  439: 	} else {
1.853     albertel  440: 	    &create_connection(&hostname($server),$server);
1.550     foxr      441: 	}
1.1289    damieng   442:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      443:     }
                    444:     my $answer;
                    445:     if ($client) {
1.704     albertel  446: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      447: 	$answer=<$client>;
                    448: 	if (!$answer) { $answer="con_lost"; }
                    449: 	chomp($answer);
                    450:     } else {
                    451: 	$answer = 'con_lost';	# Failed connection.
                    452:     }
1.1       albertel  453:     return $answer;
                    454: }
                    455: 
                    456: sub reply {
                    457:     my ($cmd,$server)=@_;
1.838     albertel  458:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  459:     my $answer=subreply($cmd,$server);
1.65      www       460:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  461:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       462:                 " $cmd to $server returned $answer</font>");
                    463:     }
1.1       albertel  464:     return $answer;
                    465: }
                    466: 
                    467: # ----------------------------------------------------------- Send USR1 to lonc
                    468: 
                    469: sub reconlonc {
1.891     albertel  470:     my ($lonid) = @_;
                    471:     if ($lonid) {
1.1295    raeburn   472:         my $hostname = &hostname($lonid);
1.891     albertel  473: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    474: 	if ($hostname && -e $peerfile) {
                    475: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    476: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    477: 					     Type    => SOCK_STREAM,
                    478: 					     Timeout => 10);
                    479: 	    if ($client) {
                    480: 		print $client ("reset_retries\n");
                    481: 		my $answer=<$client>;
                    482: 		#reset just this one.
                    483: 	    }
                    484: 	}
                    485: 	return;
                    486:     }
                    487: 
1.836     www       488:     &logthis("Trying to reconnect lonc");
1.1       albertel  489:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   490:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  491: 	my $loncpid=<$fh>;
                    492:         chomp($loncpid);
                    493:         if (kill 0 => $loncpid) {
                    494: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    495:             kill USR1 => $loncpid;
                    496:             sleep 1;
1.1295    raeburn   497:         } else {
1.12      www       498: 	    &logthis(
1.672     albertel  499:                "<font color=\"blue\">WARNING:".
1.12      www       500:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  501:         }
                    502:     } else {
1.836     www       503: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  504:     }
                    505: }
                    506: 
                    507: # ------------------------------------------------------ Critical communication
1.12      www       508: 
1.1       albertel  509: sub critical {
                    510:     my ($cmd,$server)=@_;
1.838     albertel  511:     unless (&hostname($server)) {
1.672     albertel  512:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       513:                " Critical message to unknown server ($server)</font>");
                    514:         return 'no_such_host';
                    515:     }
1.1       albertel  516:     my $answer=reply($cmd,$server);
                    517:     if ($answer eq 'con_lost') {
1.1295    raeburn   518: 	&reconlonc($server);
1.589     albertel  519: 	my $answer=reply($cmd,$server);
1.1       albertel  520:         if ($answer eq 'con_lost') {
                    521:             my $now=time;
                    522:             my $middlename=$cmd;
1.5       www       523:             $middlename=substr($middlename,0,16);
1.1       albertel  524:             $middlename=~s/\W//g;
                    525:             my $dfilename=
1.305     www       526:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    527:             $dumpcount++;
1.1       albertel  528:             {
1.448     albertel  529: 		my $dfh;
1.1359    raeburn   530: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  531: 		    print $dfh "$cmd\n"; 
                    532: 		    close($dfh);
                    533: 		}
1.1       albertel  534:             }
1.1288    damieng   535:             sleep 1;
1.1       albertel  536:             my $wcmd='';
                    537:             {
1.448     albertel  538: 		my $dfh;
1.1359    raeburn   539: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  540: 		    $wcmd=<$dfh>; 
                    541: 		    close($dfh);
                    542: 		}
1.1       albertel  543:             }
                    544:             chomp($wcmd);
1.7       www       545:             if ($wcmd eq $cmd) {
1.672     albertel  546: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       547:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  548:                 &logperm("D:$server:$cmd");
                    549: 	        return 'con_delayed';
                    550:             } else {
1.672     albertel  551:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       552:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  553:                 &logperm("F:$server:$cmd");
                    554:                 return 'con_failed';
                    555:             }
                    556:         }
                    557:     }
                    558:     return $answer;
1.405     albertel  559: }
                    560: 
1.755     albertel  561: # ------------------------------------------- check if return value is an error
                    562: 
                    563: sub error {
                    564:     my ($result) = @_;
1.756     albertel  565:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  566: 	if ($2 == 2) { return undef; }
                    567: 	return $1;
                    568:     }
                    569:     return undef;
                    570: }
                    571: 
1.783     albertel  572: sub convert_and_load_session_env {
                    573:     my ($lonidsdir,$handle)=@_;
                    574:     my @profile;
                    575:     {
1.917     albertel  576: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    577: 	if (!$opened) {
1.915     albertel  578: 	    return 0;
                    579: 	}
1.783     albertel  580: 	flock($idf,LOCK_SH);
                    581: 	@profile=<$idf>;
                    582: 	close($idf);
                    583:     }
                    584:     my %temp_env;
                    585:     foreach my $line (@profile) {
1.786     albertel  586: 	if ($line !~ m/=/) {
                    587: 	    return 0;
                    588: 	}
1.783     albertel  589: 	chomp($line);
                    590: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    591: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    592:     }
                    593:     unlink("$lonidsdir/$handle.id");
                    594:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    595: 	    0640)) {
                    596: 	%disk_env = %temp_env;
                    597: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    598: 	untie(%disk_env);
                    599:     }
1.786     albertel  600:     return 1;
1.783     albertel  601: }
                    602: 
1.374     www       603: # ------------------------------------------- Transfer profile into environment
1.780     albertel  604: my $env_loaded;
                    605: sub transfer_profile_to_env {
1.788     albertel  606:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    607:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       608: 
1.720     albertel  609:     if (!defined($lonidsdir)) {
                    610: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    611:     }
                    612:     if (!defined($handle)) {
                    613:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    614:     }
                    615: 
1.786     albertel  616:     my $convert;
                    617:     {
1.917     albertel  618:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    619: 	if (!$opened) {
1.915     albertel  620: 	    return;
                    621: 	}
1.786     albertel  622: 	flock($idf,LOCK_SH);
                    623: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    624: 		&GDBM_READER(),0640)) {
                    625: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    626: 	    untie(%disk_env);
                    627: 	} else {
                    628: 	    $convert = 1;
                    629: 	}
                    630:     }
                    631:     if ($convert) {
                    632: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    633: 	    &logthis("Failed to load session, or convert session.");
                    634: 	}
1.374     www       635:     }
1.783     albertel  636: 
1.786     albertel  637:     my %remove;
1.783     albertel  638:     while ( my $envname = each(%env) ) {
1.433     matthew   639:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    640:             if ($time < time-300) {
1.783     albertel  641:                 $remove{$key}++;
1.433     matthew   642:             }
                    643:         }
                    644:     }
1.783     albertel  645: 
1.619     albertel  646:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  647:     $env_loaded=1;
1.783     albertel  648:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   649:         &delenv($expired_key);
1.374     www       650:     }
1.1       albertel  651: }
                    652: 
1.916     albertel  653: # ---------------------------------------------------- Check for valid session 
                    654: sub check_for_valid_session {
1.1355    raeburn   655:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  656:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   657:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    658:     if ($name eq 'lonDAV') {
                    659:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    660:     } else {
                    661:         $lonidsdir=$r->dir_config('lonIDsDir');
                    662:         if ($name eq '') {
                    663:             $name = 'lonID';
                    664:         }
                    665:     }
                    666:     if ($name eq 'lonID') {
                    667:         $secure = 'lonSID';
1.1337    raeburn   668:         $linkname = 'lonLinkID';
                    669:         $pubname = 'lonPubID';
1.1378    raeburn   670:         if (exists($cookies{$secure})) {
                    671:             $lonid=$cookies{$secure};
                    672:         } elsif (exists($cookies{$name})) {
                    673:             $lonid=$cookies{$name};
                    674:         } elsif (exists($cookies{$linkname})) {
1.1337    raeburn   675:             $lonid=$cookies{$linkname};
1.1378    raeburn   676:         } elsif (exists($cookies{$pubname})) {
                    677:             $lonid=$cookies{$pubname};
1.1337    raeburn   678:         }
1.1378    raeburn   679:     } else {
                    680:         $lonid=$cookies{$name};
1.1337    raeburn   681:     }
1.916     albertel  682:     return undef if (!$lonid);
                    683: 
                    684:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   685:     if (-l "$lonidsdir/$handle.id") {
                    686:         my $link = readlink("$lonidsdir/$handle.id");
                    687:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    688:             $handle = $1;
                    689:         }
1.1155    raeburn   690:     }
1.1355    raeburn   691:     if (!-e "$lonidsdir/$handle.id") {
                    692:         if ((ref($domref)) && ($name eq 'lonID') && 
                    693:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    694:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    695:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    696:                 $$domref = $possudom;
                    697:             }
                    698:         }
                    699:         return undef;
                    700:     }
1.916     albertel  701: 
1.917     albertel  702:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    703:     return undef if (!$opened);
1.916     albertel  704: 
                    705:     flock($idf,LOCK_SH);
                    706:     my %disk_env;
                    707:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    708: 	    &GDBM_READER(),0640)) {
                    709: 	return undef;	
                    710:     }
                    711: 
                    712:     if (!defined($disk_env{'user.name'})
                    713: 	|| !defined($disk_env{'user.domain'})) {
                    714: 	return undef;
                    715:     }
1.1245    raeburn   716: 
                    717:     if (ref($userhashref) eq 'HASH') {
                    718:         $userhashref->{'name'} = $disk_env{'user.name'};
                    719:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   720:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   721:         if ($userhashref->{'lti'}) {
                    722:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    723:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    724:         }
1.1212    raeburn   725:     }
1.1245    raeburn   726: 
1.916     albertel  727:     return $handle;
                    728: }
                    729: 
1.830     albertel  730: sub timed_flock {
                    731:     my ($file,$lock_type) = @_;
                    732:     my $failed=0;
                    733:     eval {
                    734: 	local $SIG{__DIE__}='DEFAULT';
                    735: 	local $SIG{ALRM}=sub {
                    736: 	    $failed=1;
                    737: 	    die("failed lock");
                    738: 	};
                    739: 	alarm(13);
                    740: 	flock($file,$lock_type);
                    741: 	alarm(0);
                    742:     };
                    743:     if ($failed) {
                    744: 	return undef;
                    745:     } else {
                    746: 	return 1;
                    747:     }
                    748: }
                    749: 
1.5       www       750: # ---------------------------------------------------------- Append Environment
                    751: 
                    752: sub appenv {
1.949     raeburn   753:     my ($newenv,$roles) = @_;
                    754:     if (ref($newenv) eq 'HASH') {
                    755:         foreach my $key (keys(%{$newenv})) {
                    756:             my $refused = 0;
                    757: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    758:                 $refused = 1;
                    759:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   760:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   761:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    762:                         $refused = 0;
                    763:                     }
                    764:                 }
                    765:             }
                    766:             if ($refused) {
                    767:                 &logthis("<font color=\"blue\">WARNING: ".
                    768:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    769:                          .'</font>');
                    770: 	        delete($newenv->{$key});
                    771:             } else {
                    772:                 $env{$key}=$newenv->{$key};
                    773:             }
                    774:         }
1.1376    raeburn   775:         my $lonids = $perlvar{'lonIDsDir'};
                    776:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    777:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    778:             if ($opened
                    779: 	        && &timed_flock($env_file,LOCK_EX)
                    780: 	        &&
                    781: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    782: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    783: 	        while (my ($key,$value) = each(%{$newenv})) {
                    784: 	            $disk_env{$key} = $value;
                    785: 	        }
                    786: 	        untie(%disk_env);
                    787:             }
1.35      www       788:         }
1.191     harris41  789:     }
1.56      www       790:     return 'ok';
                    791: }
                    792: # ----------------------------------------------------- Delete from Environment
                    793: 
                    794: sub delenv {
1.1104    raeburn   795:     my ($delthis,$regexp,$roles) = @_;
                    796:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    797:         my $refused = 1;
                    798:         if (ref($roles) eq 'ARRAY') {
                    799:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    800:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    801:                 $refused = 0;
                    802:             }
                    803:         }
                    804:         if ($refused) {
                    805:             &logthis("<font color=\"blue\">WARNING: ".
                    806:                      "Attempt to delete from environment ".$delthis);
                    807:             return 'error';
                    808:         }
1.56      www       809:     }
1.917     albertel  810:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    811:     if ($opened
1.915     albertel  812: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  813: 	&&
                    814: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    815: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  816: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   817: 	    if ($regexp) {
                    818:                 if ($key=~/^$delthis/) {
                    819:                     delete($env{$key});
                    820:                     delete($disk_env{$key});
                    821:                 } 
                    822:             } else {
                    823:                 if ($key=~/^\Q$delthis\E/) {
                    824: 		    delete($env{$key});
                    825: 		    delete($disk_env{$key});
                    826: 	        }
                    827:             }
1.448     albertel  828: 	}
1.783     albertel  829: 	untie(%disk_env);
1.5       www       830:     }
                    831:     return 'ok';
1.369     albertel  832: }
                    833: 
1.790     albertel  834: sub get_env_multiple {
                    835:     my ($name) = @_;
                    836:     my @values;
                    837:     if (defined($env{$name})) {
                    838:         # exists is it an array
                    839:         if (ref($env{$name})) {
                    840:             @values=@{ $env{$name} };
                    841:         } else {
                    842:             $values[0]=$env{$name};
                    843:         }
                    844:     }
                    845:     return(@values);
                    846: }
                    847: 
1.958     www       848: # ------------------------------------------------------------------- Locking
                    849: 
                    850: sub set_lock {
                    851:     my ($text)=@_;
                    852:     $locknum++;
                    853:     my $id=$$.'-'.$locknum;
                    854:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    855:              'session.lock.'.$id => $text});
                    856:     return $id;
                    857: }
                    858: 
                    859: sub get_locks {
                    860:     my $num=0;
                    861:     my %texts=();
                    862:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    863:        if ($lock=~/\w/) {
                    864:           $num++;
                    865:           $texts{$lock}=$env{'session.lock.'.$lock};
                    866:        }
                    867:    }
                    868:    return ($num,%texts);
                    869: }
                    870: 
                    871: sub remove_lock {
                    872:     my ($id)=@_;
                    873:     my $newlocks='';
                    874:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    875:        if (($lock=~/\w/) && ($lock ne $id)) {
                    876:           $newlocks.=','.$lock;
                    877:        }
                    878:     }
                    879:     &appenv({'session.locks' => $newlocks});
                    880:     &delenv('session.lock.'.$id);
                    881: }
                    882: 
                    883: sub remove_all_locks {
                    884:     my $activelocks=$env{'session.locks'};
                    885:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    886:        if ($lock=~/\w/) {
                    887:           &remove_lock($lock);
                    888:        }
                    889:     }
                    890: }
                    891: 
                    892: 
1.369     albertel  893: # ------------------------------------------ Find out current server userload
                    894: sub userload {
                    895:     my $numusers=0;
                    896:     {
                    897: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    898: 	my $filename;
                    899: 	my $curtime=time;
                    900: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  901: 	    next if ($filename eq '.' || $filename eq '..');
                    902: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  905: 	}
                    906: 	closedir(LONIDS);
                    907:     }
                    908:     my $userloadpercent=0;
                    909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    910:     if ($maxuserload) {
1.371     albertel  911: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  912:     }
1.372     albertel  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  914:     return $userloadpercent;
1.283     www       915: }
                    916: 
1.1       albertel  917: # ------------------------------ Find server with least workload from spare.tab
1.11      www       918: 
1.1       albertel  919: sub spareserver {
1.1083    raeburn   920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  921:     my $spare_server;
1.370     albertel  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    924:                                                      :  $userloadpercent;
1.1083    raeburn   925:     my ($uint_dom,$remotesessions);
                    926:     if (($udom ne '') && (&domain($udom) ne '')) {
                    927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    930:         $remotesessions = $udomdefaults{'remotesessions'};
                    931:     }
1.1123    raeburn   932:     my $spareshash = &this_host_spares($udom);
                    933:     if (ref($spareshash) eq 'HASH') {
                    934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    937:                                              $try_server));
1.1123    raeburn   938: 	        ($spare_server, $lowest_load) =
                    939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    940:             }
1.1083    raeburn   941:         }
1.784     albertel  942: 
1.1123    raeburn   943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    944: 
                    945:         if (!$found_server) {
                    946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   948:                     next unless (&spare_can_host($udom,$uint_dom,
                    949:                                                  $remotesessions,$try_server));
1.1123    raeburn   950: 	            ($spare_server, $lowest_load) =
                    951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    952:                 }
                    953: 	    }
                    954:         }
1.784     albertel  955:     }
                    956: 
                    957:     if (!$want_server_name) {
1.968     raeburn   958:         my $protocol = 'http';
                    959:         if ($protocol{$spare_server} eq 'https') {
                    960:             $protocol = $protocol{$spare_server};
                    961:         }
1.1001    raeburn   962:         if (defined($spare_server)) {
                    963:             my $hostname = &hostname($spare_server);
1.1083    raeburn   964:             if (defined($hostname)) {
1.1001    raeburn   965: 	        $spare_server = $protocol.'://'.$hostname;
                    966:             }
                    967:         }
1.784     albertel  968:     }
                    969:     return $spare_server;
                    970: }
                    971: 
                    972: sub compare_server_load {
1.1253    raeburn   973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    974: 
                    975:     if ($required) {
                    976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    979:         if (($major eq '' && $minor eq '') ||
                    980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    981:             return ($spare_server,$lowest_load);
                    982:         }
                    983:     }
1.784     albertel  984: 
                    985:     my $loadans     = &reply('load',    $try_server);
                    986:     my $userloadans = &reply('userload',$try_server);
                    987: 
                    988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  990:     }
                    991: 
                    992:     my $load;
                    993:     if ($loadans =~ /\d/) {
                    994: 	if ($userloadans =~ /\d/) {
                    995: 	    #both are numbers, pick the bigger one
                    996: 	    $load = ($loadans > $userloadans) ? $loadans 
                    997: 		                              : $userloadans;
1.411     albertel  998: 	} else {
1.784     albertel  999: 	    $load = $loadans;
1.411     albertel 1000: 	}
1.784     albertel 1001:     } else {
                   1002: 	$load = $userloadans;
                   1003:     }
                   1004: 
                   1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1006: 	$spare_server = $try_server;
                   1007: 	$lowest_load  = $load;
1.370     albertel 1008:     }
1.784     albertel 1009:     return ($spare_server,$lowest_load);
1.202     matthew  1010: }
1.914     albertel 1011: 
                   1012: # --------------------------- ask offload servers if user already has a session
                   1013: sub find_existing_session {
                   1014:     my ($udom,$uname) = @_;
1.1123    raeburn  1015:     my $spareshash = &this_host_spares($udom);
                   1016:     if (ref($spareshash) eq 'HASH') {
                   1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1020:             }
                   1021:         }
                   1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1025:             }
                   1026:         }
1.914     albertel 1027:     }
                   1028:     return;
                   1029: }
                   1030: 
                   1031: # -------------------------------- ask if server already has a session for user
                   1032: sub has_user_session {
                   1033:     my ($lonid,$udom,$uname) = @_;
                   1034:     my $result = &reply(join(':','userhassession',
                   1035: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1036:     return 1 if ($result eq 'ok');
                   1037: 
                   1038:     return 0;
                   1039: }
                   1040: 
1.1076    raeburn  1041: # --------- determine least loaded server in a user's domain which allows login
                   1042: 
                   1043: sub choose_server {
1.1259    raeburn  1044:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1045:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1046:     my %servers = &get_servers($udom);
1.1076    raeburn  1047:     my $lowest_load = 30000;
1.1259    raeburn  1048:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1049:     if ($skiploadbal) {
                   1050:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1051:         unless (defined($cached)) {
                   1052:             my $cachetime = 60*60*24;
                   1053:             my %domconfig =
                   1054:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1055:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1056:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1057:                                            $cachetime);
                   1058:             }
                   1059:         }
                   1060:     }
1.1076    raeburn  1061:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1062:         if ($skiploadbal) {
                   1063:             if (ref($balancers) eq 'HASH') {
                   1064:                 next if (exists($balancers->{$lonhost}));
                   1065:             }
                   1066:         }   
1.1115    raeburn  1067:         my $loginvia;
                   1068:         if ($checkloginvia) {
                   1069:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1070:             if ($loginvia) {
                   1071:                 my ($server,$path) = split(/:/,$loginvia);
                   1072:                 ($login_host, $lowest_load) =
1.1253    raeburn  1073:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1074:                 if ($login_host eq $server) {
                   1075:                     $portal_path = $path;
1.1151    raeburn  1076:                     $isredirect = 1;
1.1116    raeburn  1077:                 }
                   1078:             } else {
                   1079:                 ($login_host, $lowest_load) =
1.1253    raeburn  1080:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1081:                 if ($login_host eq $lonhost) {
                   1082:                     $portal_path = '';
1.1151    raeburn  1083:                     $isredirect = ''; 
1.1116    raeburn  1084:                 }
                   1085:             }
                   1086:         } else {
1.1076    raeburn  1087:             ($login_host, $lowest_load) =
1.1253    raeburn  1088:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1089:         }
                   1090:     }
                   1091:     if ($login_host ne '') {
1.1116    raeburn  1092:         $hostname = &hostname($login_host);
1.1076    raeburn  1093:     }
1.1331    raeburn  1094:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1095: }
                   1096: 
1.202     matthew  1097: # --------------------------------------------- Try to change a user's password
                   1098: 
                   1099: sub changepass {
1.799     raeburn  1100:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1101:     $currentpass = &escape($currentpass);
                   1102:     $newpass     = &escape($newpass);
1.1030    raeburn  1103:     my $lonhost = $perlvar{'lonHostID'};
                   1104:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1105: 		       $server);
                   1106:     if (! $answer) {
                   1107: 	&logthis("No reply on password change request to $server ".
                   1108: 		 "by $uname in domain $udom.");
                   1109:     } elsif ($answer =~ "^ok") {
                   1110:         &logthis("$uname in $udom successfully changed their password ".
                   1111: 		 "on $server.");
                   1112:     } elsif ($answer =~ "^pwchange_failure") {
                   1113: 	&logthis("$uname in $udom was unable to change their password ".
                   1114: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1115: 		 "or pwchange");
                   1116:     } elsif ($answer =~ "^non_authorized") {
                   1117:         &logthis("$uname in $udom did not get their password correct when ".
                   1118: 		 "attempting to change it on $server.");
                   1119:     } elsif ($answer =~ "^auth_mode_error") {
                   1120:         &logthis("$uname in $udom attempted to change their password despite ".
                   1121: 		 "not being locally or internally authenticated on $server.");
                   1122:     } elsif ($answer =~ "^unknown_user") {
                   1123:         &logthis("$uname in $udom attempted to change their password ".
                   1124: 		 "on $server but were unable to because $server is not ".
                   1125: 		 "their home server.");
                   1126:     } elsif ($answer =~ "^refused") {
                   1127: 	&logthis("$server refused to change $uname in $udom password because ".
                   1128: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1129:     } elsif ($answer =~ "invalid_client") {
                   1130:         &logthis("$server refused to change $uname in $udom password because ".
                   1131:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1132:     }
                   1133:     return $answer;
1.1       albertel 1134: }
                   1135: 
1.169     harris41 1136: # ----------------------- Try to determine user's current authentication scheme
                   1137: 
                   1138: sub queryauthenticate {
                   1139:     my ($uname,$udom)=@_;
1.456     albertel 1140:     my $uhome=&homeserver($uname,$udom);
                   1141:     if (!$uhome) {
                   1142: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1143: 	return 'no_host';
                   1144:     }
                   1145:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1146:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1147: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1148:     }
1.456     albertel 1149:     return $answer;
1.169     harris41 1150: }
                   1151: 
1.1       albertel 1152: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1153: 
1.1       albertel 1154: sub authenticate {
1.1073    raeburn  1155:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1156:     $upass=&escape($upass);
                   1157:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1158:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1159:     my $newhome;
1.836     www      1160:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1161: # Maybe the machine was offline and only re-appeared again recently?
                   1162:         &reconlonc();
                   1163: # One more
1.952     raeburn  1164: 	$uhome=&homeserver($uname,$udom,1);
                   1165:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1166:             if (defined(&domain($udom,'primary'))) {
                   1167:                 $newhome=&domain($udom,'primary');
                   1168:             }
                   1169:             if ($newhome ne '') {
                   1170:                 $uhome = $newhome;
                   1171:             }
                   1172:         }
1.836     www      1173: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1174: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1175: 	    return 'no_host';
                   1176:         }
1.1       albertel 1177:     }
1.1073    raeburn  1178:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1179:     if ($answer eq 'authorized') {
1.952     raeburn  1180:         if ($newhome) {
                   1181:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1182:             return 'no_account_on_host'; 
                   1183:         } else {
                   1184:             &logthis("User $uname at $udom authorized by $uhome");
                   1185:             return $uhome;
                   1186:         }
1.471     albertel 1187:     }
                   1188:     if ($answer eq 'non_authorized') {
                   1189: 	&logthis("User $uname at $udom rejected by $uhome");
                   1190: 	return 'no_host'; 
1.9       www      1191:     }
1.471     albertel 1192:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1193:     return 'no_host';
                   1194: }
                   1195: 
1.1073    raeburn  1196: sub can_host_session {
1.1074    raeburn  1197:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1198:     my $canhost = 1;
1.1074    raeburn  1199:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1200:     if (ref($remotesessions) eq 'HASH') {
                   1201:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1202:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1203:                 $canhost = 0;
                   1204:             } else {
                   1205:                 $canhost = 1;
                   1206:             }
                   1207:         }
                   1208:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1209:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1210:                 $canhost = 1;
                   1211:             } else {
                   1212:                 $canhost = 0;
                   1213:             }
                   1214:         }
                   1215:         if ($canhost) {
                   1216:             if ($remotesessions->{'version'} ne '') {
                   1217:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1218:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1219:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1220:                         my $major = $1;
                   1221:                         my $minor = $2;
                   1222:                         if (($major < $reqmajor ) ||
                   1223:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1224:                             $canhost = 0;
                   1225:                         }
                   1226:                     } else {
                   1227:                         $canhost = 0;
                   1228:                     }
                   1229:                 }
                   1230:             }
                   1231:         }
                   1232:     }
                   1233:     if ($canhost) {
                   1234:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1235:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1236:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1237:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1238:                 if (($uint_dom ne '') && 
                   1239:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1240:                     $canhost = 0;
                   1241:                 } else {
                   1242:                     $canhost = 1;
                   1243:                 }
                   1244:             }
                   1245:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1246:                 if (($uint_dom ne '') && 
                   1247:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1248:                     $canhost = 1;
                   1249:                 } else {
                   1250:                     $canhost = 0;
                   1251:                 }
                   1252:             }
                   1253:         }
                   1254:     }
                   1255:     return $canhost;
                   1256: }
                   1257: 
1.1083    raeburn  1258: sub spare_can_host {
                   1259:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1260:     my $canhost=1;
1.1279    raeburn  1261:     my $try_server_hostname = &hostname($try_server);
                   1262:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1263:     my $serverhomedom = &host_domain($serverhomeID);
                   1264:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1265:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1266:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1267:             $canhost = 0;
                   1268:         }
                   1269:     }
                   1270:     if (($canhost) && ($uint_dom)) {
                   1271:         my @intdoms;
                   1272:         my $internet_names = &get_internet_names($try_server);
                   1273:         if (ref($internet_names) eq 'ARRAY') {
                   1274:             @intdoms = @{$internet_names};
                   1275:         }
                   1276:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1277:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1278:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1279:                                          $remotesessions,
                   1280:                                          $defdomdefaults{'hostedsessions'});
                   1281:         }
1.1083    raeburn  1282:     }
                   1283:     return $canhost;
                   1284: }
                   1285: 
1.1123    raeburn  1286: sub this_host_spares {
                   1287:     my ($dom) = @_;
1.1126    raeburn  1288:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1289:     my @hosts = &current_machine_ids();
                   1290:     foreach my $lonhost (@hosts) {
                   1291:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1292:             $dom_in_use = $dom;
                   1293:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1294:             last;
                   1295:         }
                   1296:     }
1.1126    raeburn  1297:     if ($dom_in_use ne '') {
                   1298:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1299:     }
                   1300:     if (ref($result) ne 'HASH') {
                   1301:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1302:         $dom_in_use = &host_domain($lonhost_in_use);
                   1303:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1304:         if (ref($result) ne 'HASH') {
                   1305:             $result = \%spareid;
                   1306:         }
                   1307:     }
                   1308:     return $result;
                   1309: }
                   1310: 
                   1311: sub spares_for_offload  {
                   1312:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1313:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1314:     if (defined($cached)) {
                   1315:         return $result;
                   1316:     } else {
1.1126    raeburn  1317:         my $cachetime = 60*60*24;
                   1318:         my %domconfig =
                   1319:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1320:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1321:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1322:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1323:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1324:                 }
                   1325:             }
                   1326:         }
                   1327:     }
1.1126    raeburn  1328:     return;
1.1123    raeburn  1329: }
                   1330: 
1.1129    raeburn  1331: sub get_lonbalancer_config {
                   1332:     my ($servers) = @_;
                   1333:     my ($currbalancer,$currtargets);
                   1334:     if (ref($servers) eq 'HASH') {
                   1335:         foreach my $server (keys(%{$servers})) {
                   1336:             my %what = (
                   1337:                          spareid => 1,
                   1338:                          perlvar => 1,
                   1339:                        );
                   1340:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1341:             if ($result eq 'ok') {
                   1342:                 if (ref($returnhash) eq 'HASH') {
                   1343:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1344:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1345:                             $currbalancer = $server;
                   1346:                             $currtargets = {};
                   1347:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1348:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1349:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1350:                                 }
                   1351:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1352:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1353:                                 }
                   1354:                             }
                   1355:                             last;
                   1356:                         }
                   1357:                     }
                   1358:                 }
                   1359:             }
                   1360:         }
                   1361:     }
                   1362:     return ($currbalancer,$currtargets);
                   1363: }
                   1364: 
                   1365: sub check_loadbalancing {
1.1331    raeburn  1366:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1367:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1368:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1369:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1370:     my @hosts = &current_machine_ids();
1.1129    raeburn  1371:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1372:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1373:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1374:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1375:     my $domneedscache;
1.1129    raeburn  1376:     my $cachetime = 60*60*24;
                   1377: 
                   1378:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1379:         $dom_in_use = $udom;
                   1380:         $homeintdom = 1;
                   1381:     } else {
                   1382:         $dom_in_use = $serverhomedom;
                   1383:     }
                   1384:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1385:     unless (defined($cached)) {
                   1386:         my %domconfig =
                   1387:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1388:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1389:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1390:         } else {
                   1391:             $domneedscache = $dom_in_use;
1.1129    raeburn  1392:         }
                   1393:     }
                   1394:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1395:         ($is_balancer,$currtargets,$currrules) = 
                   1396:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1397:         if ($is_balancer) {
                   1398:             if (ref($currrules) eq 'HASH') {
                   1399:                 if ($homeintdom) {
                   1400:                     if ($uname ne '') {
                   1401:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1402:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1403:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1404:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1405:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1406:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1407:                             }
                   1408:                         }
                   1409:                         if ($rule_in_effect eq '') {
                   1410:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1411:                             if ($userenv{'inststatus'} ne '') {
                   1412:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1413:                                 my ($othertitle,$usertypes,$types) =
                   1414:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1415:                                 if (ref($types) eq 'ARRAY') {
                   1416:                                     foreach my $type (@{$types}) {
                   1417:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1418:                                             if (exists($currrules->{$type})) {
                   1419:                                                 $rule_in_effect = $currrules->{$type};
                   1420:                                             }
                   1421:                                         }
                   1422:                                     }
                   1423:                                 }
                   1424:                             } else {
                   1425:                                 if (exists($currrules->{'default'})) {
                   1426:                                     $rule_in_effect = $currrules->{'default'};
                   1427:                                 }
                   1428:                             }
                   1429:                         }
                   1430:                     } else {
                   1431:                         if (exists($currrules->{'default'})) {
                   1432:                             $rule_in_effect = $currrules->{'default'};
                   1433:                         }
                   1434:                     }
                   1435:                 } else {
                   1436:                     if ($currrules->{'_LC_external'} ne '') {
                   1437:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1438:                     }
                   1439:                 }
                   1440:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1441:                                                        $uname,$udom);
                   1442:             }
                   1443:         }
                   1444:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1445:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1446:         unless (defined($cached)) {
                   1447:             my %domconfig =
                   1448:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1449:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1450:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1451:             } else {
                   1452:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1453:             }
                   1454:         }
                   1455:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1456:             ($is_balancer,$currtargets,$currrules) = 
                   1457:                 &check_balancer_result($result,@hosts);
                   1458:             if ($is_balancer) {
1.1129    raeburn  1459:                 if (ref($currrules) eq 'HASH') {
                   1460:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1461:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1462:                     }
                   1463:                 }
                   1464:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1465:                                                        $uname,$udom);
                   1466:             }
                   1467:         } else {
                   1468:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1469:                 $is_balancer = 1;
                   1470:                 $offloadto = &this_host_spares($dom_in_use);
                   1471:             }
1.1307    raeburn  1472:             unless (defined($cached)) {
                   1473:                 $domneedscache = $serverhomedom;
                   1474:             }
1.1129    raeburn  1475:         }
                   1476:     } else {
                   1477:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1478:             $is_balancer = 1;
                   1479:             $offloadto = &this_host_spares($dom_in_use);
                   1480:         }
1.1307    raeburn  1481:         unless (defined($cached)) {
                   1482:             $domneedscache = $serverhomedom;
                   1483:         }
                   1484:     }
                   1485:     if ($domneedscache) {
                   1486:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1487:     }
1.1176    raeburn  1488:     if ($is_balancer) {
                   1489:         my $lowest_load = 30000;
                   1490:         if (ref($offloadto) eq 'HASH') {
                   1491:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1492:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1493:                     ($otherserver,$lowest_load) =
                   1494:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1495:                 }
1.1129    raeburn  1496:             }
1.1176    raeburn  1497:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1498: 
1.1176    raeburn  1499:             if (!$found_server) {
                   1500:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1501:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1502:                         ($otherserver,$lowest_load) =
                   1503:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1504:                     }
                   1505:                 }
                   1506:             }
                   1507:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1508:             if (@{$offloadto} == 1) {
                   1509:                 $otherserver = $offloadto->[0];
                   1510:             } elsif (@{$offloadto} > 1) {
                   1511:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1512:                     ($otherserver,$lowest_load) =
                   1513:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1514:                 }
                   1515:             }
                   1516:         }
1.1331    raeburn  1517:         unless ($caller eq 'login') {
                   1518:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1519:                 $is_balancer = 0;
                   1520:                 if ($uname ne '' && $udom ne '') {
                   1521:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1522:                     
1.1331    raeburn  1523:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1524:                                  'user.loadbalcheck.time' => time});
                   1525:                     }
1.1176    raeburn  1526:                 }
1.1129    raeburn  1527:             }
                   1528:         }
                   1529:     }
                   1530:     return ($is_balancer,$otherserver);
                   1531: }
                   1532: 
1.1191    raeburn  1533: sub check_balancer_result {
                   1534:     my ($result,@hosts) = @_;
                   1535:     my ($is_balancer,$currtargets,$currrules);
                   1536:     if (ref($result) eq 'HASH') {
                   1537:         if ($result->{'lonhost'} ne '') {
                   1538:             my $currbalancer = $result->{'lonhost'};
                   1539:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1540:                 $is_balancer = 1;
                   1541:                 $currtargets = $result->{'targets'};
                   1542:                 $currrules = $result->{'rules'};
                   1543:             }
                   1544:         } else {
                   1545:             foreach my $key (keys(%{$result})) {
                   1546:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1547:                     (ref($result->{$key}) eq 'HASH')) {
                   1548:                     $is_balancer = 1;
                   1549:                     $currrules = $result->{$key}{'rules'};
                   1550:                     $currtargets = $result->{$key}{'targets'};
                   1551:                     last;
                   1552:                 }
                   1553:             }
                   1554:         }
                   1555:     }
                   1556:     return ($is_balancer,$currtargets,$currrules);
                   1557: }
                   1558: 
1.1129    raeburn  1559: sub get_loadbalancer_targets {
                   1560:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1561:     my $offloadto;
1.1175    raeburn  1562:     if ($rule_in_effect eq 'none') {
                   1563:         return [$perlvar{'lonHostID'}];
                   1564:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1565:         $offloadto = $currtargets;
                   1566:     } else {
                   1567:         if ($rule_in_effect eq 'homeserver') {
                   1568:             my $homeserver = &homeserver($uname,$udom);
                   1569:             if ($homeserver ne 'no_host') {
                   1570:                 $offloadto = [$homeserver];
                   1571:             }
                   1572:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1573:             my %domconfig =
                   1574:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1575:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1576:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1577:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1578:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1579:                     }
                   1580:                 }
                   1581:             } else {
1.1178    raeburn  1582:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1583:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1584:                 if (&hostname($remotebalancer) ne '') {
                   1585:                     $offloadto = [$remotebalancer];
                   1586:                 }
                   1587:             }
                   1588:         } elsif (&hostname($rule_in_effect) ne '') {
                   1589:             $offloadto = [$rule_in_effect];
                   1590:         }
                   1591:     }
                   1592:     return $offloadto;
                   1593: }
                   1594: 
1.1127    raeburn  1595: sub internet_dom_servers {
                   1596:     my ($dom) = @_;
                   1597:     my (%uniqservers,%servers);
                   1598:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1599:     my @machinedoms = &machine_domains($primaryserver);
                   1600:     foreach my $mdom (@machinedoms) {
                   1601:         my %currservers = %servers;
                   1602:         my %server = &get_servers($mdom);
                   1603:         %servers = (%currservers,%server);
                   1604:     }
                   1605:     my %by_hostname;
                   1606:     foreach my $id (keys(%servers)) {
                   1607:         push(@{$by_hostname{$servers{$id}}},$id);
                   1608:     }
                   1609:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1610:         if (@{$by_hostname{$hostname}} > 1) {
                   1611:             my $match = 0;
                   1612:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1613:                 if (&host_domain($id) eq $dom) {
                   1614:                     $uniqservers{$id} = $hostname;
                   1615:                     $match = 1;
                   1616:                 }
                   1617:             }
                   1618:             unless ($match) {
                   1619:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1620:             }
                   1621:         } else {
                   1622:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1623:         }
                   1624:     }
                   1625:     return %uniqservers;
                   1626: }
                   1627: 
1.1347    raeburn  1628: sub trusted_domains {
                   1629:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1630:     my ($trusted,$untrusted);
1.1347    raeburn  1631:     if (&domain($calldom) eq '') {
1.1349    raeburn  1632:         return ($trusted,$untrusted);
1.1347    raeburn  1633:     }
                   1634:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1635:         return ($trusted,$untrusted);
1.1347    raeburn  1636:     }
                   1637:     my $callprimary = &domain($calldom,'primary');
                   1638:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1639:     if ($intcalldom eq '') {
1.1349    raeburn  1640:         return ($trusted,$untrusted);
1.1347    raeburn  1641:     }
                   1642: 
                   1643:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1644:     unless (defined($cached)) {
                   1645:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1646:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1647:         $trustconfig = $domconfig{'trust'};
                   1648:     }
                   1649:     if (ref($trustconfig)) {
                   1650:         my (%possexc,%possinc,@allexc,@allinc); 
                   1651:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1652:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1653:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1654:             }
                   1655:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1656:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1657:             }
                   1658:         }
                   1659:         if (keys(%possexc)) {
                   1660:             if (keys(%possinc)) {
                   1661:                 foreach my $key (sort(keys(%possexc))) {
                   1662:                     next if ($key eq $intcalldom);
                   1663:                     unless ($possinc{$key}) {
                   1664:                         push(@allexc,$key);
                   1665:                     }
                   1666:                 }
                   1667:             } else {
                   1668:                 @allexc = sort(keys(%possexc));
                   1669:             }
                   1670:         }
                   1671:         if (keys(%possinc)) {
                   1672:             $possinc{$intcalldom} = 1;
                   1673:             @allinc = sort(keys(%possinc));
                   1674:         }
                   1675:         if ((@allexc > 0) || (@allinc > 0)) {
                   1676:             my %doms_by_intdom;
                   1677:             my %allintdoms = &all_host_intdom();
                   1678:             my %alldoms = &all_host_domain();
                   1679:             foreach my $key (%allintdoms) {
                   1680:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1681:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1682:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1683:                     }
                   1684:                 } else {
                   1685:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1686:                 }
                   1687:             }
                   1688:             foreach my $exc (@allexc) {
                   1689:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1690:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1691:                 }
                   1692:             }
                   1693:             foreach my $inc (@allinc) {
                   1694:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1695:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1696:                 }
                   1697:             }
                   1698:         }
                   1699:     }
1.1349    raeburn  1700:     return ($trusted,$untrusted);
1.1347    raeburn  1701: }
                   1702: 
                   1703: sub will_trust {
                   1704:     my ($cmdtype,$domain,$possdom) = @_;
                   1705:     return 1 if ($domain eq $possdom);
                   1706:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1707:     my $willtrust; 
                   1708:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1709:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1710:             $willtrust = 1;
                   1711:         }
                   1712:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1713:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1714:             $willtrust = 1;
                   1715:         }
                   1716:     } else {
                   1717:         $willtrust = 1;
                   1718:     }
                   1719:     return $willtrust;
                   1720: }
                   1721: 
1.1       albertel 1722: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1723: 
1.599     albertel 1724: my %homecache;
1.1       albertel 1725: sub homeserver {
1.230     stredwic 1726:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1727:     my $index="$uname:$udom";
1.426     albertel 1728: 
1.599     albertel 1729:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1730: 
                   1731:     my %servers = &get_servers($udom,'library');
                   1732:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1733:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1734: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1735: 
                   1736: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1737: 	if ($answer eq 'found') {
                   1738: 	    delete($badServerCache{$tryserver}); 
                   1739: 	    return $homecache{$index}=$tryserver;
                   1740: 	} elsif ($answer eq 'no_host') {
                   1741: 	    $badServerCache{$tryserver}=1;
                   1742: 	}
1.1       albertel 1743:     }    
                   1744:     return 'no_host';
1.70      www      1745: }
                   1746: 
1.1300    raeburn  1747: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1748: 
                   1749: sub idget {
1.1300    raeburn  1750:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1751:     my %returnhash=();
1.1300    raeburn  1752:     my @ids=(); 
                   1753:     if (ref($idsref) eq 'ARRAY') {
                   1754:         @ids = @{$idsref};
                   1755:     } else {
                   1756:         return %returnhash; 
                   1757:     }
                   1758:     if ($namespace eq '') {
                   1759:         $namespace = 'ids';
                   1760:     }
1.70      www      1761:     
1.841     albertel 1762:     my %servers = &get_servers($udom,'library');
                   1763:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1764: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1765: 	if ($namespace eq 'ids') {
                   1766: 	    $idlist=~tr/A-Z/a-z/;
                   1767: 	}
                   1768: 	my $reply;
                   1769: 	if ($namespace eq 'ids') {
                   1770: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1771: 	} else {
                   1772: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1773: 	}
1.841     albertel 1774: 	my @answer=();
                   1775: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1776: 	    @answer=split(/\&/,$reply);
                   1777: 	}                    ;
                   1778: 	my $i;
                   1779: 	for ($i=0;$i<=$#ids;$i++) {
                   1780: 	    if ($answer[$i]) {
1.1299    raeburn  1781: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1782: 	    }
1.841     albertel 1783: 	}
1.1300    raeburn  1784:     }
1.70      www      1785:     return %returnhash;
                   1786: }
                   1787: 
                   1788: # ------------------------------------- Find the IDs behind a list of usernames
                   1789: 
                   1790: sub idrget {
                   1791:     my ($udom,@unames)=@_;
                   1792:     my %returnhash=();
1.800     albertel 1793:     foreach my $uname (@unames) {
                   1794:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1795:     }
1.70      www      1796:     return %returnhash;
                   1797: }
                   1798: 
1.1300    raeburn  1799: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1800: 
                   1801: sub idput {
1.1300    raeburn  1802:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1803:     my %servers=();
1.1300    raeburn  1804:     my %ids=();
                   1805:     my %byid = ();
                   1806:     if (ref($idsref) eq 'HASH') {
                   1807:         %ids=%{$idsref};
                   1808:     }
                   1809:     if ($namespace eq '') {
                   1810:         $namespace = 'ids'; 
                   1811:     }
1.800     albertel 1812:     foreach my $uname (keys(%ids)) {
                   1813: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1814:         if ($uhom eq '') {
                   1815:             $uhom=&homeserver($uname,$udom);
                   1816:         }
1.70      www      1817:         if ($uhom ne 'no_host') {
1.800     albertel 1818:             my $esc_unam=&escape($uname);
1.1300    raeburn  1819:             if ($namespace eq 'ids') {
                   1820:                 my $id=&escape($ids{$uname});
                   1821:                 $id=~tr/A-Z/a-z/;
                   1822:                 my $esc_unam=&escape($uname);
                   1823:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1824:             } else {
1.1300    raeburn  1825:                 my @currids = split(/,/,$ids{$uname});
                   1826:                 foreach my $id (@currids) {
                   1827:                     $byid{$uhom}{$id} .= $uname.',';
                   1828:                 }
                   1829:             }
                   1830:         }
                   1831:     }
                   1832:     if ($namespace eq 'clickers') {
                   1833:         foreach my $server (keys(%byid)) {
                   1834:             if (ref($byid{$server}) eq 'HASH') {
                   1835:                 foreach my $id (keys(%{$byid{$server}})) {
                   1836:                     $byid{$server} =~ s/,$//;
                   1837:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1838:                 }
1.70      www      1839:             }
                   1840:         }
1.191     harris41 1841:     }
1.800     albertel 1842:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1843:         $servers{$server} =~ s/\&$//;
                   1844:         if ($namespace eq 'ids') {     
                   1845:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1846:         } else {
                   1847:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1848:         }
1.191     harris41 1849:     }
1.344     www      1850: }
                   1851: 
1.1300    raeburn  1852: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1853: 
                   1854: sub iddel {
1.1300    raeburn  1855:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1856:     my %result=();
1.1300    raeburn  1857:     my %ids=();
                   1858:     my %byid = ();
                   1859:     if (ref($idshashref) eq 'HASH') {
                   1860:         %ids=%{$idshashref};
                   1861:     } else {
1.1231    raeburn  1862:         return %result;
                   1863:     }
1.1300    raeburn  1864:     if ($namespace eq '') {
                   1865:         $namespace = 'ids';
                   1866:     }
1.1231    raeburn  1867:     my %servers=();
1.1300    raeburn  1868:     while (my ($id,$unamestr) = each(%ids)) {
                   1869:         if ($namespace eq 'ids') {
                   1870:             my $uhom = $uhome;
                   1871:             if ($uhom eq '') { 
                   1872:                 $uhom=&homeserver($unamestr,$udom);
                   1873:             }
                   1874:             if ($uhom ne 'no_host') {
                   1875:                 $servers{$uhom}.='&'.&escape($id);
                   1876:             }
                   1877:          } else {
                   1878:             my @curritems = split(/,/,$ids{$id});
                   1879:             foreach my $uname (@curritems) {
                   1880:                 my $uhom = $uhome;
                   1881:                 if ($uhom eq '') {
                   1882:                     $uhom=&homeserver($uname,$udom);
                   1883:                 }
                   1884:                 if ($uhom ne 'no_host') { 
                   1885:                     $byid{$uhom}{$id} .= $uname.',';
                   1886:                 }
                   1887:             }
1.1231    raeburn  1888:         }
1.1300    raeburn  1889:     }
                   1890:     if ($namespace eq 'clickers') {
                   1891:         foreach my $server (keys(%byid)) {
                   1892:             if (ref($byid{$server}) eq 'HASH') {
                   1893:                 foreach my $id (keys(%{$byid{$server}})) {
                   1894:                     $byid{$server}{$id} =~ s/,$//;
                   1895:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1896:                 }
1.1231    raeburn  1897:             }
                   1898:         }
                   1899:     }
                   1900:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1901:         $servers{$server} =~ s/\&$//;
                   1902:         if ($namespace eq 'ids') {
                   1903:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1904:         } elsif ($namespace eq 'clickers') {
                   1905:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1906:         }
1.1231    raeburn  1907:     }
                   1908:     return %result;
                   1909: }
                   1910: 
1.1300    raeburn  1911: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1912: 
                   1913: sub updateclickers {
                   1914:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1915:     my %clickers;
                   1916:     if (ref($idshashref) eq 'HASH') {
                   1917:         %clickers=%{$idshashref};
                   1918:     } else {
                   1919:         return;
                   1920:     }
                   1921:     my $items='';
                   1922:     foreach my $item (keys(%clickers)) {
                   1923:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1924:     }
                   1925:     $items=~s/\&$//;
                   1926:     my $request = "updateclickers:$udom:$action:$items";
                   1927:     if ($critical) {
                   1928:         return &critical($request,$uhome);
                   1929:     } else {
                   1930:         return &reply($request,$uhome);
                   1931:     }
                   1932: }
                   1933: 
1.1023    raeburn  1934: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1935: sub dump_dom {
1.1165    droeschl 1936:     my ($namespace, $udom, $regexp) = @_;
                   1937: 
                   1938:     $udom ||= $env{'user.domain'};
                   1939: 
                   1940:     return () unless $udom;
                   1941: 
                   1942:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1943: }
                   1944: 
1.1023    raeburn  1945: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1946: 
                   1947: sub get_dom {
1.860     raeburn  1948:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1949:     return if ($udom eq 'public');
1.806     raeburn  1950:     my $items='';
                   1951:     foreach my $item (@$storearr) {
                   1952:         $items.=&escape($item).'&';
                   1953:     }
                   1954:     $items=~s/\&$//;
1.860     raeburn  1955:     if (!$udom) {
                   1956:         $udom=$env{'user.domain'};
1.1267    raeburn  1957:         return if ($udom eq 'public');
1.860     raeburn  1958:         if (defined(&domain($udom,'primary'))) {
                   1959:             $uhome=&domain($udom,'primary');
                   1960:         } else {
1.874     albertel 1961:             undef($uhome);
1.860     raeburn  1962:         }
                   1963:     } else {
                   1964:         if (!$uhome) {
                   1965:             if (defined(&domain($udom,'primary'))) {
                   1966:                 $uhome=&domain($udom,'primary');
                   1967:             }
                   1968:         }
                   1969:     }
                   1970:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  1971:         my $rep;
                   1972:         if ($namespace =~ /^enc/) {
                   1973:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1974:         } else {
                   1975:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1976:         }
1.866     raeburn  1977:         my %returnhash;
1.875     albertel 1978:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1979:             return %returnhash;
                   1980:         }
1.806     raeburn  1981:         my @pairs=split(/\&/,$rep);
                   1982:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1983:             return @pairs;
                   1984:         }
                   1985:         my $i=0;
                   1986:         foreach my $item (@$storearr) {
                   1987:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1988:             $i++;
                   1989:         }
                   1990:         return %returnhash;
                   1991:     } else {
1.880     banghart 1992:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1993:     }
                   1994: }
                   1995: 
                   1996: # -------------------------------------------- put items in domain db files 
                   1997: 
                   1998: sub put_dom {
1.860     raeburn  1999:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2000:     if (!$udom) {
                   2001:         $udom=$env{'user.domain'};
                   2002:         if (defined(&domain($udom,'primary'))) {
                   2003:             $uhome=&domain($udom,'primary');
                   2004:         } else {
1.874     albertel 2005:             undef($uhome);
1.860     raeburn  2006:         }
                   2007:     } else {
                   2008:         if (!$uhome) {
                   2009:             if (defined(&domain($udom,'primary'))) {
                   2010:                 $uhome=&domain($udom,'primary');
                   2011:             }
                   2012:         }
                   2013:     } 
                   2014:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2015:         my $items='';
                   2016:         foreach my $item (keys(%$storehash)) {
                   2017:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2018:         }
                   2019:         $items=~s/\&$//;
1.1344    raeburn  2020:         if ($namespace =~ /^enc/) {
                   2021:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2022:         } else {
                   2023:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2024:         }
1.806     raeburn  2025:     } else {
1.860     raeburn  2026:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2027:     }
                   2028: }
                   2029: 
1.1023    raeburn  2030: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2031: sub newput_dom {
1.1023    raeburn  2032:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2033:     my $result;
                   2034:     if (!$udom) {
                   2035:         $udom=$env{'user.domain'};
                   2036:     }
1.1023    raeburn  2037:     if ($udom) {
                   2038:         my $uname = &get_domainconfiguser($udom);
                   2039:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2040:     }
                   2041:     return $result;
                   2042: }
                   2043: 
1.1023    raeburn  2044: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2045: sub del_dom {
1.1023    raeburn  2046:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2047:     if (ref($storearr) eq 'ARRAY') {
                   2048:         if (!$udom) {
                   2049:             $udom=$env{'user.domain'};
                   2050:         }
1.1023    raeburn  2051:         if ($udom) {
                   2052:             my $uname = &get_domainconfiguser($udom); 
                   2053:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2054:         }
                   2055:     }
                   2056: }
                   2057: 
1.1023    raeburn  2058: # ----------------------------------construct domainconfig user for a domain 
                   2059: sub get_domainconfiguser {
                   2060:     my ($udom) = @_;
                   2061:     return $udom.'-domainconfig';
                   2062: }
                   2063: 
1.837     raeburn  2064: sub retrieve_inst_usertypes {
                   2065:     my ($udom) = @_;
                   2066:     my (%returnhash,@order);
1.989     raeburn  2067:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2068:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2069:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2070:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2071:     } else {
                   2072:         if (defined(&domain($udom,'primary'))) {
                   2073:             my $uhome=&domain($udom,'primary');
                   2074:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2075:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2076:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2077:                 return (\%returnhash,\@order);
                   2078:             }
                   2079:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2080:             my @pairs=split(/\&/,$hashitems);
                   2081:             foreach my $item (@pairs) {
                   2082:                 my ($key,$value)=split(/=/,$item,2);
                   2083:                 $key = &unescape($key);
                   2084:                 next if ($key =~ /^error: 2 /);
                   2085:                 $returnhash{$key}=&thaw_unescape($value);
                   2086:             }
                   2087:             my @esc_order = split(/\&/,$orderitems);
                   2088:             foreach my $item (@esc_order) {
                   2089:                 push(@order,&unescape($item));
                   2090:             }
                   2091:         } else {
1.1256    raeburn  2092:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2093:         }
1.1256    raeburn  2094:         return (\%returnhash,\@order);
1.837     raeburn  2095:     }
                   2096: }
                   2097: 
1.868     raeburn  2098: sub is_domainimage {
                   2099:     my ($url) = @_;
1.1306    raeburn  2100:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2101:         if (&domain($1) ne '') {
                   2102:             return '1';
                   2103:         }
                   2104:     }
                   2105:     return;
                   2106: }
                   2107: 
1.899     raeburn  2108: sub inst_directory_query {
                   2109:     my ($srch) = @_;
                   2110:     my $udom = $srch->{'srchdomain'};
                   2111:     my %results;
                   2112:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2113:     my $outcome;
1.899     raeburn  2114:     if ($homeserver ne '') {
1.1357    raeburn  2115:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2116:             if ($srch->{'srchby'} eq 'email') {
                   2117:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2118:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2119:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2120:                     (($major == 2) && ($minor < 12))) {
                   2121:                     return;
                   2122:                 }
                   2123:             }
                   2124:         }
1.904     albertel 2125: 	my $queryid=&reply("querysend:instdirsearch:".
                   2126: 			   &escape($srch->{'srchby'}).':'.
                   2127: 			   &escape($srch->{'srchterm'}).':'.
                   2128: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2129: 	my $host=&hostname($homeserver);
                   2130: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2131: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2132: 	    return;
                   2133: 	}
                   2134: 	my $response = &get_query_reply($queryid);
                   2135: 	my $maxtries = 5;
                   2136: 	my $tries = 1;
                   2137: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2138: 	    $response = &get_query_reply($queryid);
                   2139: 	    $tries ++;
                   2140: 	}
                   2141: 
                   2142:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2143:             if ($response eq 'unavailable') {
                   2144:                 $outcome = $response;
                   2145:             } else {
                   2146:                 $outcome = 'ok';
                   2147:                 my @matches = split(/\n/,$response);
                   2148:                 foreach my $match (@matches) {
                   2149:                     my ($key,$value) = split(/=/,$match);
                   2150:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2151:                 }
1.899     raeburn  2152:             }
                   2153:         }
                   2154:     }
1.909     raeburn  2155:     return ($outcome,%results);
1.899     raeburn  2156: }
                   2157: 
                   2158: sub usersearch {
                   2159:     my ($srch) = @_;
                   2160:     my $dom = $srch->{'srchdomain'};
                   2161:     my %results;
                   2162:     my %libserv = &all_library();
                   2163:     my $query = 'usersearch';
                   2164:     foreach my $tryserver (keys(%libserv)) {
                   2165:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2166:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2167:                 if ($srch->{'srchby'} eq 'email') {
                   2168:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2169:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2170:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2171:                              (($major == 2) && ($minor < 12)));
                   2172:                 }
                   2173:             }
1.899     raeburn  2174:             my $host=&hostname($tryserver);
                   2175:             my $queryid=
1.911     raeburn  2176:                 &reply("querysend:".&escape($query).':'.
                   2177:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2178:                        &escape($srch->{'srchtype'}).':'.
                   2179:                        &escape($srch->{'srchterm'}),$tryserver);
                   2180:             if ($queryid !~/^\Q$host\E\_/) {
                   2181:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2182:                 next;
1.899     raeburn  2183:             }
                   2184:             my $reply = &get_query_reply($queryid);
                   2185:             my $maxtries = 1;
                   2186:             my $tries = 1;
                   2187:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2188:                 $reply = &get_query_reply($queryid);
                   2189:                 $tries ++;
                   2190:             }
                   2191:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2192:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2193:             } else {
1.911     raeburn  2194:                 my @matches;
                   2195:                 if ($reply =~ /\n/) {
                   2196:                     @matches = split(/\n/,$reply);
                   2197:                 } else {
                   2198:                     @matches = split(/\&/,$reply);
                   2199:                 }
1.899     raeburn  2200:                 foreach my $match (@matches) {
                   2201:                     my ($uname,$udom,%userhash);
1.911     raeburn  2202:                     foreach my $entry (split(/:/,$match)) {
                   2203:                         my ($key,$value) =
                   2204:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2205:                         $userhash{$key} = $value;
                   2206:                         if ($key eq 'username') {
                   2207:                             $uname = $value;
                   2208:                         } elsif ($key eq 'domain') {
                   2209:                             $udom = $value;
1.911     raeburn  2210:                         }
1.899     raeburn  2211:                     }
                   2212:                     $results{$uname.':'.$udom} = \%userhash;
                   2213:                 }
                   2214:             }
                   2215:         }
                   2216:     }
                   2217:     return %results;
                   2218: }
                   2219: 
1.912     raeburn  2220: sub get_instuser {
                   2221:     my ($udom,$uname,$id) = @_;
                   2222:     my $homeserver = &domain($udom,'primary');
                   2223:     my ($outcome,%results);
                   2224:     if ($homeserver ne '') {
                   2225:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2226:                            &escape($id).':'.&escape($udom),$homeserver);
                   2227:         my $host=&hostname($homeserver);
                   2228:         if ($queryid !~/^\Q$host\E\_/) {
                   2229:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2230:             return;
                   2231:         }
                   2232:         my $response = &get_query_reply($queryid);
                   2233:         my $maxtries = 5;
                   2234:         my $tries = 1;
                   2235:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2236:             $response = &get_query_reply($queryid);
                   2237:             $tries ++;
                   2238:         }
                   2239:         if (!&error($response) && $response ne 'refused') {
                   2240:             if ($response eq 'unavailable') {
                   2241:                 $outcome = $response;
                   2242:             } else {
                   2243:                 $outcome = 'ok';
                   2244:                 my @matches = split(/\n/,$response);
                   2245:                 foreach my $match (@matches) {
                   2246:                     my ($key,$value) = split(/=/,$match);
                   2247:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2248:                 }
                   2249:             }
                   2250:         }
                   2251:     }
                   2252:     my %userinfo;
                   2253:     if (ref($results{$uname}) eq 'HASH') {
                   2254:         %userinfo = %{$results{$uname}};
                   2255:     } 
                   2256:     return ($outcome,%userinfo);
                   2257: }
                   2258: 
1.1290    raeburn  2259: sub get_multiple_instusers {
                   2260:     my ($udom,$users,$caller) = @_;
                   2261:     my ($outcome,$results);
                   2262:     if (ref($users) eq 'HASH') {
                   2263:         my $count = keys(%{$users}); 
                   2264:         my $requested = &freeze_escape($users);
                   2265:         my $homeserver = &domain($udom,'primary');
                   2266:         if ($homeserver ne '') {
                   2267:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2268:             my $host=&hostname($homeserver);
                   2269:             if ($queryid !~/^\Q$host\E\_/) {
                   2270:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2271:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2272:                 return ($outcome,$results);
                   2273:             }
                   2274:             my $response = &get_query_reply($queryid);
                   2275:             my $maxtries = 5;
                   2276:             if ($count > 100) {
                   2277:                 $maxtries = 1+int($count/20);
                   2278:             }
                   2279:             my $tries = 1;
                   2280:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2281:                 $response = &get_query_reply($queryid);
                   2282:                 $tries ++;
                   2283:             }
                   2284:             if ($response eq '') {
                   2285:                 $results = {};
                   2286:                 foreach my $key (keys(%{$users})) {
                   2287:                     my ($uname,$id);
                   2288:                     if ($caller eq 'id') {
                   2289:                         $id = $key;
                   2290:                     } else {
                   2291:                         $uname = $key;
                   2292:                     }
                   2293:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2294:                     $outcome = $resp;
1.1290    raeburn  2295:                     if ($resp eq 'ok') {
                   2296:                         %{$results} = (%{$results}, %info);
                   2297:                     } else {
                   2298:                         last;
                   2299:                     }
                   2300:                 }
                   2301:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2302:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2303:                     $outcome = $response;
                   2304:                 } else {
1.1291    raeburn  2305:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2306:                     if ($outcome eq 'ok') {
                   2307:                         $results = &thaw_unescape($userdata); 
                   2308:                     }
                   2309:                 }
                   2310:             }
                   2311:         }
                   2312:     }
                   2313:     return ($outcome,$results);
                   2314: }
                   2315: 
1.912     raeburn  2316: sub inst_rulecheck {
1.923     raeburn  2317:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2318:     my %returnhash;
                   2319:     if ($udom ne '') {
                   2320:         if (ref($rules) eq 'ARRAY') {
                   2321:             @{$rules} = map {&escape($_);} (@{$rules});
                   2322:             my $rulestr = join(':',@{$rules});
                   2323:             my $homeserver=&domain($udom,'primary');
                   2324:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2325:                 my $response;
                   2326:                 if ($item eq 'username') {                
                   2327:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2328:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2329:                                               $homeserver));
1.923     raeburn  2330:                 } elsif ($item eq 'id') {
                   2331:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2332:                                               ':'.&escape($id).':'.$rulestr,
                   2333:                                               $homeserver));
1.945     raeburn  2334:                 } elsif ($item eq 'selfcreate') {
                   2335:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2336:                                                &escape($udom).':'.&escape($uname).
                   2337:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2338:                 }
1.912     raeburn  2339:                 if ($response ne 'refused') {
                   2340:                     my @pairs=split(/\&/,$response);
                   2341:                     foreach my $item (@pairs) {
                   2342:                         my ($key,$value)=split(/=/,$item,2);
                   2343:                         $key = &unescape($key);
                   2344:                         next if ($key =~ /^error: 2 /);
                   2345:                         $returnhash{$key}=&thaw_unescape($value);
                   2346:                     }
                   2347:                 }
                   2348:             }
                   2349:         }
                   2350:     }
                   2351:     return %returnhash;
                   2352: }
                   2353: 
                   2354: sub inst_userrules {
1.923     raeburn  2355:     my ($udom,$check) = @_;
1.912     raeburn  2356:     my (%ruleshash,@ruleorder);
                   2357:     if ($udom ne '') {
                   2358:         my $homeserver=&domain($udom,'primary');
                   2359:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2360:             my $response;
                   2361:             if ($check eq 'id') {
                   2362:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2363:                                  $homeserver);
1.943     raeburn  2364:             } elsif ($check eq 'email') {
                   2365:                 $response=&reply('instemailrules:'.&escape($udom),
                   2366:                                  $homeserver);
1.923     raeburn  2367:             } else {
                   2368:                 $response=&reply('instuserrules:'.&escape($udom),
                   2369:                                  $homeserver);
                   2370:             }
1.912     raeburn  2371:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2372:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2373:                 ($response ne 'no_such_host')) {
                   2374:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2375:                 my @pairs=split(/\&/,$hashitems);
                   2376:                 foreach my $item (@pairs) {
                   2377:                     my ($key,$value)=split(/=/,$item,2);
                   2378:                     $key = &unescape($key);
                   2379:                     next if ($key =~ /^error: 2 /);
                   2380:                     $ruleshash{$key}=&thaw_unescape($value);
                   2381:                 }
                   2382:                 my @esc_order = split(/\&/,$orderitems);
                   2383:                 foreach my $item (@esc_order) {
                   2384:                     push(@ruleorder,&unescape($item));
                   2385:                 }
                   2386:             }
                   2387:         }
                   2388:     }
                   2389:     return (\%ruleshash,\@ruleorder);
                   2390: }
                   2391: 
1.976     raeburn  2392: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2393: 
                   2394: sub get_domain_defaults {
1.1240    raeburn  2395:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2396:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2397:     my $cachetime = 60*60*24;
1.1240    raeburn  2398:     unless ($ignore_cache) {
                   2399:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2400:         if (defined($cached)) {
                   2401:             if (ref($result) eq 'HASH') {
                   2402:                 return %{$result};
                   2403:             }
1.943     raeburn  2404:         }
                   2405:     }
                   2406:     my %domdefaults;
                   2407:     my %domconfig =
1.989     raeburn  2408:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2409:                                   'requestcourses','inststatus',
1.1183    raeburn  2410:                                   'coursedefaults','usersessions',
1.1258    raeburn  2411:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2412:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2413:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2414:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2415:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2416:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2417:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2418:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2419:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2420:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2421:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2422:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2423:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2424:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2425:     } else {
                   2426:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2427:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2428:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2429:     }
1.976     raeburn  2430:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2431:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2432:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2433:         } else {
                   2434:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2435:         }
1.1177    raeburn  2436:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2437:         foreach my $item (@usertools) {
                   2438:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2439:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2440:             }
                   2441:         }
1.1229    raeburn  2442:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2443:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2444:         }
1.976     raeburn  2445:     }
1.985     raeburn  2446:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2447:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2448:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2449:         }
                   2450:     }
1.1183    raeburn  2451:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2452:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2453:     }
1.989     raeburn  2454:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2455:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2456:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2457:         }
                   2458:     }
1.1047    raeburn  2459:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2460:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2461:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2462:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2463:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2464:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2465:         }
1.1254    raeburn  2466:         foreach my $type (@coursetypes) {
                   2467:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2468:                 unless ($type eq 'community') {
                   2469:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2470:                 }
                   2471:             }
                   2472:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2473:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2474:             }
1.1277    raeburn  2475:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2476:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2477:                     $domdefaults{$type.'postsubtimeout'} = 
                   2478:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2479:                 }
                   2480:             }
1.1230    raeburn  2481:         }
1.1286    raeburn  2482:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2483:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2484:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2485:                 if (@clonecodes) {
                   2486:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2487:                 }
                   2488:             }
                   2489:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2490:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2491:         }
1.1356    raeburn  2492:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2493:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2494:         } 
1.1047    raeburn  2495:     }
1.1073    raeburn  2496:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2497:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2498:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2499:         }
                   2500:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2501:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2502:         }
1.1279    raeburn  2503:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2504:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2505:         }
1.1073    raeburn  2506:     }
1.1254    raeburn  2507:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2508:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2509:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2510:                             'approval','limit');
                   2511:             foreach my $type (@coursetypes) {
                   2512:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2513:                     my @mgrdc = ();
                   2514:                     foreach my $item (@settings) {
                   2515:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2516:                             push(@mgrdc,$item);
                   2517:                         }
                   2518:                     }
                   2519:                     if (@mgrdc) {
                   2520:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2521:                     }
                   2522:                 }
                   2523:             }
                   2524:         }
                   2525:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2526:             foreach my $type (@coursetypes) {
                   2527:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2528:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2529:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2530:                     }
                   2531:                 }
                   2532:             }
                   2533:         }
                   2534:     }
1.1258    raeburn  2535:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2536:         $domdefaults{'catauth'} = 'std';
                   2537:         $domdefaults{'catunauth'} = 'std';
                   2538:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2539:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2540:         }
                   2541:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2542:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2543:         }
                   2544:     }
1.1315    raeburn  2545:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2546:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2547:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2548:         }
1.1338    raeburn  2549:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2550:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2551:         }
                   2552:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2553:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2554:         }
                   2555:     }
1.1320    raeburn  2556:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2557:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2558:         foreach my $prefix (@prefixes) {
                   2559:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2560:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2561:             }
                   2562:         }
                   2563:     }
1.1314    raeburn  2564:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2565:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2566:     }
1.1332    raeburn  2567:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2568:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2569:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2570:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2571:         }
                   2572:     }
1.1219    raeburn  2573:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2574:     return %domdefaults;
                   2575: }
                   2576: 
1.1311    raeburn  2577: sub course_portal_url {
                   2578:     my ($cnum,$cdom) = @_;
                   2579:     my $chome = &homeserver($cnum,$cdom);
                   2580:     my $hostname = &hostname($chome);
                   2581:     my $protocol = $protocol{$chome};
                   2582:     $protocol = 'http' if ($protocol ne 'https');
                   2583:     my %domdefaults = &get_domain_defaults($cdom);
                   2584:     my $firsturl;
                   2585:     if ($domdefaults{'portal_def'}) {
                   2586:         $firsturl = $domdefaults{'portal_def'};
                   2587:     } else {
                   2588:         $firsturl = $protocol.'://'.$hostname;
                   2589:     }
                   2590:     return $firsturl;
                   2591: }
                   2592: 
1.344     www      2593: # --------------------------------------------------- Assign a key to a student
                   2594: 
                   2595: sub assign_access_key {
1.364     www      2596: #
                   2597: # a valid key looks like uname:udom#comments
                   2598: # comments are being appended
                   2599: #
1.498     www      2600:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2601:     $kdom=
1.620     albertel 2602:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2603:     $knum=
1.620     albertel 2604:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2605:     $cdom=
1.620     albertel 2606:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2607:     $cnum=
1.620     albertel 2608:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2609:     $udom=$env{'user.name'} unless (defined($udom));
                   2610:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2611:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2612:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2613:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2614:                                                   # assigned to this person
                   2615:                                                   # - this should not happen,
1.345     www      2616:                                                   # unless something went wrong
                   2617:                                                   # the first time around
                   2618: # ready to assign
1.364     www      2619:         $logentry=$1.'; '.$logentry;
1.496     www      2620:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2621:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2622: # key now belongs to user
1.346     www      2623: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2624:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2625:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2626:                 return 'ok';
                   2627:             } else {
                   2628:                 return 
                   2629:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2630: 	    }
                   2631:         } else {
                   2632:             return 'error: Could not assign key, try again later.';
                   2633:         }
1.364     www      2634:     } elsif (!$existing{$ckey}) {
1.345     www      2635: # the key does not exist
                   2636: 	return 'error: The key does not exist';
                   2637:     } else {
                   2638: # the key is somebody else's
                   2639: 	return 'error: The key is already in use';
                   2640:     }
1.344     www      2641: }
                   2642: 
1.364     www      2643: # ------------------------------------------ put an additional comment on a key
                   2644: 
                   2645: sub comment_access_key {
                   2646: #
                   2647: # a valid key looks like uname:udom#comments
                   2648: # comments are being appended
                   2649: #
                   2650:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2651:     $cdom=
1.620     albertel 2652:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2653:     $cnum=
1.620     albertel 2654:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2655:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2656:     if ($existing{$ckey}) {
                   2657:         $existing{$ckey}.='; '.$logentry;
                   2658: # ready to assign
1.367     www      2659:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2660:                                                  $cdom,$cnum) eq 'ok') {
                   2661: 	    return 'ok';
                   2662:         } else {
                   2663: 	    return 'error: Count not store comment.';
                   2664:         }
                   2665:     } else {
                   2666: # the key does not exist
                   2667: 	return 'error: The key does not exist';
                   2668:     }
                   2669: }
                   2670: 
1.344     www      2671: # ------------------------------------------------------ Generate a set of keys
                   2672: 
                   2673: sub generate_access_keys {
1.364     www      2674:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2675:     $cdom=
1.620     albertel 2676:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2677:     $cnum=
1.620     albertel 2678:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2679:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2680:     unless (($cdom) && ($cnum)) { return 0; }
                   2681:     if ($number>10000) { return 0; }
                   2682:     sleep(2); # make sure don't get same seed twice
                   2683:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2684:     my $total=0;
                   2685:     for (my $i=1;$i<=$number;$i++) {
                   2686:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2687:                   sprintf("%lx",int(100000*rand)).'-'.
                   2688:                   sprintf("%lx",int(100000*rand));
                   2689:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2690:        $newkey=~s/0/h/g; # and also 0 and O
                   2691:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2692:        if ($existing{$newkey}) {
                   2693:            $i--;
                   2694:        } else {
1.364     www      2695: 	  if (&put('accesskeys',
                   2696:               { $newkey => '# generated '.localtime().
1.620     albertel 2697:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2698:                            '; '.$logentry },
                   2699: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2700:               $total++;
                   2701: 	  }
                   2702:        }
                   2703:     }
1.620     albertel 2704:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2705:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2706:     return $total;
                   2707: }
                   2708: 
                   2709: # ------------------------------------------------------- Validate an accesskey
                   2710: 
                   2711: sub validate_access_key {
                   2712:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2713:     $cdom=
1.620     albertel 2714:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2715:     $cnum=
1.620     albertel 2716:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2717:     $udom=$env{'user.domain'} unless (defined($udom));
                   2718:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2719:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2720:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2721: }
                   2722: 
                   2723: # ------------------------------------- Find the section of student in a course
1.652     albertel 2724: sub devalidate_getsection_cache {
                   2725:     my ($udom,$unam,$courseid)=@_;
                   2726:     my $hashid="$udom:$unam:$courseid";
                   2727:     &devalidate_cache_new('getsection',$hashid);
                   2728: }
1.298     matthew  2729: 
1.815     albertel 2730: sub courseid_to_courseurl {
                   2731:     my ($courseid) = @_;
                   2732:     #already url style courseid
                   2733:     return $courseid if ($courseid =~ m{^/});
                   2734: 
                   2735:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2736: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2737: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2738: 	return "/$cdom/$cnum";
                   2739:     }
                   2740: 
                   2741:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2742:     if (exists($courseinfo{'num'})) {
                   2743: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2744:     }
                   2745: 
                   2746:     return undef;
                   2747: }
                   2748: 
1.298     matthew  2749: sub getsection {
                   2750:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2751:     my $cachetime=1800;
1.551     albertel 2752: 
                   2753:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2754:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2755:     if (defined($cached)) { return $result; }
                   2756: 
1.298     matthew  2757:     my %Pending; 
                   2758:     my %Expired;
                   2759:     #
                   2760:     # Each role can either have not started yet (pending), be active, 
                   2761:     #    or have expired.
                   2762:     #
                   2763:     # If there is an active role, we are done.
                   2764:     #
                   2765:     # If there is more than one role which has not started yet, 
                   2766:     #     choose the one which will start sooner
                   2767:     # If there is one role which has not started yet, return it.
                   2768:     #
                   2769:     # If there is more than one expired role, choose the one which ended last.
                   2770:     # If there is a role which has expired, return it.
                   2771:     #
1.815     albertel 2772:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2773:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2774:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2775:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2776:         my $section=$1;
                   2777:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2778:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2779:         my $now=time;
1.548     albertel 2780:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2781:             $Expired{$end}=$section;
                   2782:             next;
                   2783:         }
1.548     albertel 2784:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2785:             $Pending{$start}=$section;
                   2786:             next;
                   2787:         }
1.599     albertel 2788:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2789:     }
                   2790:     #
                   2791:     # Presumedly there will be few matching roles from the above
                   2792:     # loop and the sorting time will be negligible.
                   2793:     if (scalar(keys(%Pending))) {
                   2794:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2795:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2796:     } 
                   2797:     if (scalar(keys(%Expired))) {
                   2798:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2799:         my $time = pop(@sorted);
1.599     albertel 2800:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2801:     }
1.599     albertel 2802:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2803: }
1.70      www      2804: 
1.599     albertel 2805: sub save_cache {
                   2806:     &purge_remembered();
1.722     albertel 2807:     #&Apache::loncommon::validate_page();
1.620     albertel 2808:     undef(%env);
1.780     albertel 2809:     undef($env_loaded);
1.599     albertel 2810: }
1.452     albertel 2811: 
1.599     albertel 2812: my $to_remember=-1;
                   2813: my %remembered;
                   2814: my %accessed;
                   2815: my $kicks=0;
                   2816: my $hits=0;
1.849     albertel 2817: sub make_key {
                   2818:     my ($name,$id) = @_;
1.872     albertel 2819:     if (length($id) > 65 
                   2820: 	&& length(&escape($id)) > 200) {
                   2821: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2822:     }
1.849     albertel 2823:     return &escape($name.':'.$id);
                   2824: }
                   2825: 
1.599     albertel 2826: sub devalidate_cache_new {
                   2827:     my ($name,$id,$debug) = @_;
                   2828:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2829:     my $remembered_id=$name.':'.$id;
1.849     albertel 2830:     $id=&make_key($name,$id);
1.599     albertel 2831:     $memcache->delete($id);
1.1319    damieng  2832:     delete($remembered{$remembered_id});
                   2833:     delete($accessed{$remembered_id});
1.599     albertel 2834: }
                   2835: 
                   2836: sub is_cached_new {
                   2837:     my ($name,$id,$debug) = @_;
1.1319    damieng  2838:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2839:     if (exists($remembered{$remembered_id})) {
                   2840: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2841: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2842: 	$hits++;
1.1319    damieng  2843: 	return ($remembered{$remembered_id},1);
1.599     albertel 2844:     }
1.1319    damieng  2845:     $id=&make_key($name,$id);
1.599     albertel 2846:     my $value = $memcache->get($id);
                   2847:     if (!(defined($value))) {
                   2848: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2849: 	return (undef,undef);
1.416     albertel 2850:     }
1.599     albertel 2851:     if ($value eq '__undef__') {
                   2852: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2853: 	$value=undef;
                   2854:     }
1.1319    damieng  2855:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2856:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2857:     return ($value,1);
                   2858: }
                   2859: 
                   2860: sub do_cache_new {
                   2861:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2862:     my $remembered_id=$name.':'.$id;
1.849     albertel 2863:     $id=&make_key($name,$id);
1.599     albertel 2864:     my $setvalue=$value;
                   2865:     if (!defined($setvalue)) {
                   2866: 	$setvalue='__undef__';
                   2867:     }
1.623     albertel 2868:     if (!defined($time) ) {
                   2869: 	$time=600;
                   2870:     }
1.599     albertel 2871:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2872:     my $result = $memcache->set($id,$setvalue,$time);
                   2873:     if (! $result) {
1.872     albertel 2874: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2875: 	$memcache->disconnect_all();
1.872     albertel 2876:     }
1.600     albertel 2877:     # need to make a copy of $value
1.1319    damieng  2878:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2879:     return $value;
                   2880: }
                   2881: 
                   2882: sub make_room {
1.1319    damieng  2883:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2884: 
1.1319    damieng  2885:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2886:                                     : $value;
1.599     albertel 2887:     if ($to_remember<0) { return; }
1.1319    damieng  2888:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2889:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2890:     my $to_kick;
                   2891:     my $max_time=0;
                   2892:     foreach my $other (keys(%accessed)) {
                   2893: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2894: 	    $to_kick=$other;
                   2895: 	    $max_time=&tv_interval($accessed{$other});
                   2896: 	}
                   2897:     }
                   2898:     delete($remembered{$to_kick});
                   2899:     delete($accessed{$to_kick});
                   2900:     $kicks++;
                   2901:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2902:     return;
                   2903: }
                   2904: 
1.599     albertel 2905: sub purge_remembered {
1.604     albertel 2906:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2907:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2908:     undef(%remembered);
                   2909:     undef(%accessed);
1.428     albertel 2910: }
1.70      www      2911: # ------------------------------------- Read an entry from a user's environment
                   2912: 
                   2913: sub userenvironment {
                   2914:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2915:     my $items;
                   2916:     foreach my $item (@what) {
                   2917:         $items.=&escape($item).'&';
                   2918:     }
                   2919:     $items=~s/\&$//;
1.70      www      2920:     my %returnhash=();
1.1009    raeburn  2921:     my $uhome = &homeserver($unam,$udom);
                   2922:     unless ($uhome eq 'no_host') {
                   2923:         my @answer=split(/\&/, 
                   2924:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2925:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2926:             return %returnhash;
                   2927:         }
1.1009    raeburn  2928:         my $i;
                   2929:         for ($i=0;$i<=$#what;$i++) {
                   2930: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2931:         }
1.70      www      2932:     }
                   2933:     return %returnhash;
1.1       albertel 2934: }
                   2935: 
1.617     albertel 2936: # ---------------------------------------------------------- Get a studentphoto
                   2937: sub studentphoto {
                   2938:     my ($udom,$unam,$ext) = @_;
                   2939:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2940:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2941:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2942:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2943:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2944:             } else {
                   2945:                 my ($result,$perm_reqd)=
1.707     albertel 2946: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2947:                 if ($result eq 'ok') {
                   2948:                     if (!($perm_reqd eq 'yes')) {
                   2949:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2950:                     }
                   2951:                 }
                   2952:             }
                   2953:         }
                   2954:     } else {
                   2955:         my ($result,$perm_reqd) = 
1.707     albertel 2956: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2957:         if ($result eq 'ok') {
                   2958:             if (!($perm_reqd eq 'yes')) {
                   2959:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2960:             }
                   2961:         }
                   2962:     }
                   2963:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2964: }
                   2965: 
                   2966: sub retrievestudentphoto {
                   2967:     my ($udom,$unam,$ext,$type) = @_;
                   2968:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2969:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2970:     if ($ret eq 'ok') {
                   2971:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2972:         if ($type eq 'thumbnail') {
                   2973:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2974:         }
                   2975:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2976:         return $tokenurl;
                   2977:     } else {
                   2978:         if ($type eq 'thumbnail') {
                   2979:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2980:         } else { 
                   2981:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2982:         }
1.617     albertel 2983:     }
                   2984: }
                   2985: 
1.263     www      2986: # -------------------------------------------------------------------- New chat
                   2987: 
                   2988: sub chatsend {
1.724     raeburn  2989:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2990:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2991:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2992:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2993:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2994: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2995: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2996: }
                   2997: 
                   2998: # ------------------------------------------ Find current version of a resource
                   2999: 
                   3000: sub getversion {
                   3001:     my $fname=&clutter(shift);
1.1189    raeburn  3002:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3003:     return &currentversion(&filelocation('',$fname));
                   3004: }
                   3005: 
                   3006: sub currentversion {
                   3007:     my $fname=shift;
                   3008:     my $author=$fname;
                   3009:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3010:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3011:     my $home=&homeserver($uname,$udom);
1.292     www      3012:     if ($home eq 'no_host') { 
                   3013:         return -1; 
                   3014:     }
1.1112    www      3015:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3016:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3017: 	return -1;
                   3018:     }
1.1112    www      3019:     return $answer;
1.263     www      3020: }
                   3021: 
1.1111    www      3022: #
                   3023: # Return special version number of resource if set by override, empty otherwise
                   3024: #
                   3025: sub usedversion {
                   3026:     my $fname=shift;
                   3027:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3028:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3029:     if ($urlversion) { return $urlversion; }
                   3030:     return '';
                   3031: }
                   3032: 
1.1       albertel 3033: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3034: 
1.1       albertel 3035: sub subscribe {
                   3036:     my $fname=shift;
1.761     raeburn  3037:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3038:     $fname=~s/[\n\r]//g;
1.1       albertel 3039:     my $author=$fname;
                   3040:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3041:     my ($udom,$uname)=split(/\//,$author);
                   3042:     my $home=homeserver($uname,$udom);
1.335     albertel 3043:     if ($home eq 'no_host') {
                   3044:         return 'not_found';
1.1       albertel 3045:     }
                   3046:     my $answer=reply("sub:$fname",$home);
1.64      www      3047:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3048: 	$answer.=' by '.$home;
                   3049:     }
1.1       albertel 3050:     return $answer;
                   3051: }
                   3052:     
1.8       www      3053: # -------------------------------------------------------------- Replicate file
                   3054: 
                   3055: sub repcopy {
                   3056:     my $filename=shift;
1.23      www      3057:     $filename=~s/\/+/\//g;
1.1142    raeburn  3058:     my $londocroot = $perlvar{'lonDocRoot'};
                   3059:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3060:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3061:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3062: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3063: 	return &repcopy_userfile($filename);
                   3064:     }
1.532     albertel 3065:     $filename=~s/[\n\r]//g;
1.8       www      3066:     my $transname="$filename.in.transfer";
1.828     www      3067: # FIXME: this should flock
1.607     raeburn  3068:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3069:     my $remoteurl=subscribe($filename);
1.64      www      3070:     if ($remoteurl =~ /^con_lost by/) {
                   3071: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3072:            return 'unavailable';
1.8       www      3073:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3074: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3075: 	   return 'not_found';
1.64      www      3076:     } elsif ($remoteurl =~ /^rejected by/) {
                   3077: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3078:            return 'forbidden';
1.20      www      3079:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3080:            return 'ok';
1.8       www      3081:     } else {
1.290     www      3082:         my $author=$filename;
                   3083:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3084:         my ($udom,$uname)=split(/\//,$author);
                   3085:         my $home=homeserver($uname,$udom);
                   3086:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3087:            my @parts=split(/\//,$filename);
                   3088:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3089:            if ($path ne "$londocroot/res") {
1.8       www      3090:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3091: 	       return 'bad_request';
1.8       www      3092:            }
                   3093:            my $count;
                   3094:            for ($count=5;$count<$#parts;$count++) {
                   3095:                $path.="/$parts[$count]";
                   3096:                if ((-e $path)!=1) {
                   3097: 		   mkdir($path,0777);
                   3098:                }
                   3099:            }
                   3100:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3101:            my $response;
                   3102:            if ($remoteurl =~ m{/raw/}) {
                   3103:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3104:            } else {
                   3105:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3106:            }
1.8       www      3107:            if ($response->is_error()) {
                   3108: 	       unlink($transname);
                   3109:                my $message=$response->status_line;
1.672     albertel 3110:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3111:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3112:                return 'unavailable';
1.8       www      3113:            } else {
1.16      www      3114: 	       if ($remoteurl!~/\.meta$/) {
                   3115:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3116:                   my $mresponse;
                   3117:                   if ($remoteurl =~ m{/raw/}) {
                   3118:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3119:                   } else {
                   3120:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3121:                   }
1.16      www      3122:                   if ($mresponse->is_error()) {
                   3123: 		      unlink($filename.'.meta');
                   3124:                       &logthis(
1.672     albertel 3125:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3126:                   }
                   3127: 	       }
1.8       www      3128:                rename($transname,$filename);
1.607     raeburn  3129:                return 'ok';
1.8       www      3130:            }
1.290     www      3131:        }
1.8       www      3132:     }
1.330     www      3133: }
                   3134: 
                   3135: # ------------------------------------------------ Get server side include body
                   3136: sub ssi_body {
1.381     albertel 3137:     my ($filelink,%form)=@_;
1.606     matthew  3138:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3139:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3140:     }
1.953     www      3141:     my $output='';
                   3142:     my $response;
1.980     raeburn  3143:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3144:        ($output,$response)=&externalssi($filelink);
1.953     www      3145:     } else {
1.1004    droeschl 3146:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3147:        $filelink .= 'inhibitmenu=yes';
1.953     www      3148:        ($output,$response)=&ssi($filelink,%form);
                   3149:     }
1.778     albertel 3150:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3151:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3152:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3153:     if (wantarray) {
                   3154:         return ($output, $response);
                   3155:     } else {
                   3156:         return $output;
                   3157:     }
1.8       www      3158: }
                   3159: 
1.15      www      3160: # --------------------------------------------------------- Server Side Include
                   3161: 
1.782     albertel 3162: sub absolute_url {
                   3163:     my ($host_name) = @_;
                   3164:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3165:     if ($host_name eq '') {
                   3166: 	$host_name = $ENV{'SERVER_NAME'};
                   3167:     }
                   3168:     return $protocol.$host_name;
                   3169: }
                   3170: 
1.942     foxr     3171: #
                   3172: #   Server side include.
                   3173: # Parameters:
                   3174: #  fn     Possibly encrypted resource name/id.
                   3175: #  form   Hash that describes how the rendering should be done
                   3176: #         and other things.
1.944     foxr     3177: # Returns:
1.950     raeburn  3178: #   Scalar context: The content of the response.
                   3179: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3180: #     
1.15      www      3181: sub ssi {
                   3182: 
1.944     foxr     3183:     my ($fn,%form)=@_;
1.23      www      3184:     my $request;
1.711     albertel 3185: 
                   3186:     $form{'no_update_last_known'}=1;
1.895     albertel 3187:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3188:     if (%form) {
1.782     albertel 3189:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3190:       $request->content(join('&',map { 
                   3191:             my $name = escape($_);
                   3192:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3193:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3194:             : &escape($form{$_}) );    
                   3195:         } keys(%form)));
1.23      www      3196:     } else {
1.782     albertel 3197:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3198:     }
                   3199: 
1.15      www      3200:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3201:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3202:     my $islocal;
                   3203:     if (($env{'request.course.id'}) &&
                   3204:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3205:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3206:         ($form{'grade_symb'} ne '') &&
                   3207:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3208:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3209:         $islocal = 1;
                   3210:     }
1.1384    raeburn  3211:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3212:                                                 '','','',$islocal);
1.1182    foxr     3213: 
1.944     foxr     3214:     if (wantarray) {
1.1345    raeburn  3215: 	return ($response->content, $response);
1.944     foxr     3216:     } else {
1.1345    raeburn  3217: 	return $response->content;
1.942     foxr     3218:     }
1.324     www      3219: }
                   3220: 
                   3221: sub externalssi {
                   3222:     my ($url)=@_;
                   3223:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3224:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3225:     if (wantarray) {
                   3226:         return ($response->content, $response);
                   3227:     } else {
                   3228:         return $response->content;
                   3229:     }
1.15      www      3230: }
1.254     www      3231: 
1.1354    raeburn  3232: 
                   3233: # If the local copy of a replicated resource is outdated, trigger a  
                   3234: # connection from the homeserver to flush the delayed queue. If no update 
                   3235: # happens, remove local copies of outdated resource (and corresponding
                   3236: # metadata file).
                   3237: 
1.1352    raeburn  3238: sub remove_stale_resfile {
                   3239:     my ($url) = @_;
1.1354    raeburn  3240:     my $removed;
1.1352    raeburn  3241:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3242:         my $audom = $1;
                   3243:         my $auname = $2;
1.1353    raeburn  3244:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3245:             my $homeserver = &homeserver($auname,$audom);
                   3246:             unless (($homeserver eq 'no_host') ||
                   3247:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3248:                 my $fname = &filelocation('',$url);
                   3249:                 if (-e $fname) {
                   3250:                     my $protocol = $protocol{$homeserver};
                   3251:                     $protocol = 'http' if ($protocol ne 'https');
                   3252:                     my $hostname = &hostname($homeserver);
                   3253:                     if ($hostname) {
                   3254:                         my $uri = &declutter($url);
                   3255:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3256:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3257:                         if ($response->is_success()) {
                   3258:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3259:                             my $locmodtime = (stat($fname))[9];
                   3260:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3261:                                 my $stale;
                   3262:                                 my $answer = &reply('pong',$homeserver);
                   3263:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3264:                                     sleep(0.2);
                   3265:                                     $locmodtime = (stat($fname))[9];
                   3266:                                     if ($locmodtime < $remmodtime) {
                   3267:                                         my $posstransfer = $fname.'.in.transfer';
                   3268:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3269:                                             $removed = 1;
                   3270:                                         } else {
                   3271:                                             $stale = 1;
                   3272:                                         }
                   3273:                                     } else {
                   3274:                                         $removed = 1;
                   3275:                                     }
                   3276:                                 } else {
                   3277:                                     $stale = 1;
                   3278:                                 }
                   3279:                                 if ($stale) {
                   3280:                                     unlink($fname);
                   3281:                                     if ($uri!~/\.meta$/) {
                   3282:                                         unlink($fname.'.meta');
                   3283:                                     }
                   3284:                                     &reply("unsub:$fname",$homeserver);
                   3285:                                     $removed = 1;
1.1352    raeburn  3286:                                 }
                   3287:                             }
                   3288:                         }
                   3289:                     }
                   3290:                 }
                   3291:             }
                   3292:         }
                   3293:     }
1.1354    raeburn  3294:     return $removed;
1.1352    raeburn  3295: }
                   3296: 
1.492     albertel 3297: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3298: 
                   3299: sub allowuploaded {
                   3300:     my ($srcurl,$url)=@_;
                   3301:     $url=&clutter(&declutter($url));
                   3302:     my $dir=$url;
                   3303:     $dir=~s/\/[^\/]+$//;
                   3304:     my %httpref=();
                   3305:     my $httpurl=&hreflocation('',$url);
                   3306:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3307:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3308: }
1.477     raeburn  3309: 
1.1193    raeburn  3310: #
                   3311: # Determine if the current user should be able to edit a particular resource,
                   3312: # when viewing in course context.
                   3313: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3314: #     Functions.
                   3315: # (b) When displaying folder contents in course editor, used to determine if
                   3316: #     "Edit" link will be displayed alongside resource.
                   3317: #
1.1196    raeburn  3318: #  input: six args -- filename (decluttered), course number, course domain,
                   3319: #                   url, symb (if registered) and group (if this is a group
                   3320: #                   item -- e.g., bulletin board, group page etc.).
                   3321: #  output: array of five scalars -- 
1.1193    raeburn  3322: #          $cfile -- url for file editing if editable on current server
                   3323: #          $home -- homeserver of resource (i.e., for author if published,
                   3324: #                                           or course if uploaded.).
                   3325: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3326: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3327: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3328: #
                   3329: 
                   3330: sub can_edit_resource {
1.1194    raeburn  3331:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3332:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3333: #
                   3334: # For aboutme pages user can only edit his/her own.
                   3335: #
1.1199    raeburn  3336:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3337:         my ($sdom,$sname) = ($1,$2);
                   3338:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3339:             $home = $env{'user.home'};
                   3340:             $cfile = $resurl;
                   3341:             if ($env{'form.forceedit'}) {
                   3342:                 $forceview = 1;
                   3343:             } else {
                   3344:                 $forceedit = 1;
                   3345:             }
                   3346:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3347:         } else {
                   3348:             return;
                   3349:         }
                   3350:     }
                   3351: 
                   3352:     if ($env{'request.course.id'}) {
                   3353:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3354:         if ($group ne '') {
                   3355: # if this is a group homepage or group bulletin board, check group privs
                   3356:             my $allowed = 0;
1.1197    raeburn  3357:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3358:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3359:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3360:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3361:                     $allowed = 1;
                   3362:                 }
1.1197    raeburn  3363:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3364:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3365:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3366:                     $allowed = 1;
                   3367:                 }
                   3368:             }
                   3369:             if ($allowed) {
                   3370:                 $home=&homeserver($cnum,$cdom);
                   3371:                 if ($env{'form.forceedit'}) {
                   3372:                     $forceview = 1;
                   3373:                 } else {
                   3374:                     $forceedit = 1;
                   3375:                 }
                   3376:                 $cfile = $resurl;
                   3377:             } else {
                   3378:                 return;
                   3379:             }
                   3380:         } else {
1.1208    raeburn  3381:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3382:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3383:                     return;
                   3384:                 }
                   3385:             } elsif (!$crsedit) {
1.1194    raeburn  3386: #
                   3387: # No edit allowed where CC has switched to student role.
                   3388: #
                   3389:                 return;
                   3390:             }
                   3391:         }
                   3392:     }
                   3393: 
1.1193    raeburn  3394:     if ($file ne '') {
                   3395:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3396:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3397:                 $uploaded = 1;
                   3398:                 $incourse = 1;
1.1193    raeburn  3399:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3400:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3401:                     if ($env{'form.forceedit'}) {
                   3402:                         $forceview = 1;
                   3403:                     } else {
                   3404:                         $forceedit = 1;
                   3405:                     }
1.1194    raeburn  3406:                 }
                   3407:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3408:                 $incourse = 1;
                   3409:                 if ($env{'form.forceedit'}) {
                   3410:                     $forceview = 1;
                   3411:                 } else {
                   3412:                     $forceedit = 1;
                   3413:                 }
                   3414:                 $cfile = $resurl;
                   3415:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3416:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3417:                     $incourse = 1;
                   3418:                     if ($env{'form.forceedit'}) {
                   3419:                         $forceview = 1;
                   3420:                     } else {
                   3421:                         $forceedit = 1;
                   3422:                     }
                   3423:                     $cfile = $resurl;
1.1199    raeburn  3424:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3425:                     $incourse = 1;
                   3426:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3427:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3428:                     $incourse = 1;
1.1199    raeburn  3429:                     if ($env{'form.forceedit'}) {
                   3430:                         $forceview = 1;
                   3431:                     } else {
                   3432:                         $forceedit = 1;
                   3433:                     }
                   3434:                     $cfile = $resurl;
1.1343    raeburn  3435:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3436:                     $incourse = 1;
                   3437:                     if ($env{'form.forceedit'}) {
                   3438:                         $forceview = 1;
                   3439:                     } else {
                   3440:                         $forceedit = 1;
                   3441:                     }
                   3442:                     $cfile = $resurl;
1.1208    raeburn  3443:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3444:                     $incourse = 1;
                   3445:                     if ($env{'form.forceedit'}) {
                   3446:                         $forceview = 1;
                   3447:                     } else {
                   3448:                         $forceedit = 1;
                   3449:                     }
                   3450:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3451:                 }
                   3452:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3453:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3454:                 if (&is_on_map($template)) { 
                   3455:                     $incourse = 1;
                   3456:                     $forceview = 1;
                   3457:                     $cfile = $template;
1.1193    raeburn  3458:                 }
1.1199    raeburn  3459:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3460:                     $incourse = 1;
                   3461:                     if ($env{'form.forceedit'}) {
                   3462:                         $forceview = 1;
                   3463:                     } else {
                   3464:                         $forceedit = 1;
                   3465:                     }
                   3466:                     $cfile = $resurl;
1.1343    raeburn  3467:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3468:                 $incourse = 1;
                   3469:                 if ($env{'form.forceedit'}) {
                   3470:                     $forceview = 1;
                   3471:                 } else {
                   3472:                     $forceedit = 1;
                   3473:                 }
                   3474:                 $cfile = $resurl;
1.1199    raeburn  3475:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3476:                 $incourse = 1;
                   3477:                 $forceview = 1;
                   3478:                 if ($symb) {
                   3479:                     my ($map,$id,$res)=&decode_symb($symb);
                   3480:                     $env{'request.symb'} = $symb;
                   3481:                     $cfile = &clutter($res);
                   3482:                 } else {
                   3483:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3484:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3485:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3486:                         $cfile = '/adm/wrapper'.$escfile;
                   3487:                     } else {
                   3488:                         $escfile =~ s{^http://}{};
                   3489:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3490:                     }
1.1199    raeburn  3491:                 }
1.1234    raeburn  3492:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3493:                 if ($env{'form.forceedit'}) {
                   3494:                     $forceview = 1;
                   3495:                 } else {
                   3496:                     $forceedit = 1;
                   3497:                 }
                   3498:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3499:             }
                   3500:         }
1.1194    raeburn  3501:         if ($uploaded || $incourse) {
                   3502:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3503:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3504:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3505:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3506:             # Check that the user has permission to edit this resource
                   3507:             my $setpriv = 1;
                   3508:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3509:             if (defined($cfudom)) {
                   3510:                 $home=&homeserver($cfuname,$cfudom);
                   3511:                 $cfile=$file;
                   3512:             }
                   3513:         }
1.1194    raeburn  3514:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3515:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3516:             my @ids=&current_machine_ids();
                   3517:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3518:                 $switchserver=1;
                   3519:             }
                   3520:         }
                   3521:     }
1.1194    raeburn  3522:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3523: }
                   3524: 
                   3525: sub is_course_upload {
                   3526:     my ($file,$cnum,$cdom) = @_;
                   3527:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3528:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3529:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3530:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3531:         return 1;
                   3532:     }
                   3533:     return;
                   3534: }
                   3535: 
1.1194    raeburn  3536: sub in_course {
1.1195    raeburn  3537:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3538:     if ($hideprivileged) {
                   3539:         my $skipuser;
1.1219    raeburn  3540:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3541:         my @possdoms = ($cdom);  
                   3542:         if ($coursehash{'checkforpriv'}) { 
                   3543:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3544:         }
                   3545:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3546:             $skipuser = 1;
                   3547:             if ($coursehash{'nothideprivileged'}) {
                   3548:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3549:                     my $user;
                   3550:                     if ($item =~ /:/) {
                   3551:                         $user = $item;
                   3552:                     } else {
                   3553:                         $user = join(':',split(/[\@]/,$item));
                   3554:                     }
                   3555:                     if ($user eq $uname.':'.$udom) {
                   3556:                         undef($skipuser);
                   3557:                         last;
                   3558:                     }
                   3559:                 }
                   3560:             }
                   3561:             if ($skipuser) {
                   3562:                 return 0;
                   3563:             }
                   3564:         }
                   3565:     }
1.1194    raeburn  3566:     $type ||= 'any';
                   3567:     if (!defined($cdom) || !defined($cnum)) {
                   3568:         my $cid  = $env{'request.course.id'};
                   3569:         $cdom = $env{'course.'.$cid.'.domain'};
                   3570:         $cnum = $env{'course.'.$cid.'.num'};
                   3571:     }
                   3572:     my $typesref;
1.1195    raeburn  3573:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3574:         $typesref = ['active','previous','future'];
                   3575:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3576:         $typesref = [$type];
                   3577:     }
                   3578:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3579:                               $typesref,undef,[$cdom]);
                   3580:     my ($tmp) = keys(%roles);
                   3581:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3582:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3583:     if (@course_roles > 0) {
                   3584:         return 1;
                   3585:     }
                   3586:     return 0;
                   3587: }
                   3588: 
1.478     albertel 3589: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3590: # input: action, courseID, current domain, intended
1.637     raeburn  3591: #        path to file, source of file, instruction to parse file for objects,
                   3592: #        ref to hash for embedded objects,
                   3593: #        ref to hash for codebase of java objects.
1.1095    raeburn  3594: #        reference to scalar to accommodate mime type determined
                   3595: #          from File::MMagic if $parser = parse.
1.637     raeburn  3596: #
1.485     raeburn  3597: # output: url to file (if action was uploaddoc), 
                   3598: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3599: #
1.478     albertel 3600: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3601: # course.
1.477     raeburn  3602: #
1.478     albertel 3603: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3604: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3605: #          course's home server.
1.477     raeburn  3606: #
1.478     albertel 3607: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3608: #          be copied from $source (current location) to 
                   3609: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3610: #         and will then be copied to
                   3611: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3612: #         course's home server.
1.485     raeburn  3613: #
1.481     raeburn  3614: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3615: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3616: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3617: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3618: #         in course's home server.
1.637     raeburn  3619: #
1.477     raeburn  3620: 
                   3621: sub process_coursefile {
1.1095    raeburn  3622:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3623:         $mimetype)=@_;
1.477     raeburn  3624:     my $fetchresult;
1.638     albertel 3625:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3626:     if ($action eq 'propagate') {
1.638     albertel 3627:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3628: 			     $home);
1.481     raeburn  3629:     } else {
1.477     raeburn  3630:         my $fpath = '';
                   3631:         my $fname = $file;
1.478     albertel 3632:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3633:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3634:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3635:         if ($action eq 'copy') {
                   3636:             if ($source eq '') {
                   3637:                 $fetchresult = 'no source file';
                   3638:                 return $fetchresult;
                   3639:             } else {
                   3640:                 my $destination = $filepath.'/'.$fname;
                   3641:                 rename($source,$destination);
                   3642:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3643:                                  $home);
1.481     raeburn  3644:             }
                   3645:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3646:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3647:             print $fh $env{'form.'.$source};
1.481     raeburn  3648:             close($fh);
1.637     raeburn  3649:             if ($parser eq 'parse') {
1.1024    raeburn  3650:                 my $mm = new File::MMagic;
1.1095    raeburn  3651:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3652:                 if ($type eq 'text/html') {
1.1024    raeburn  3653:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3654:                     unless ($parse_result eq 'ok') {
                   3655:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3656:                     }
1.637     raeburn  3657:                 }
1.1095    raeburn  3658:                 if (ref($mimetype)) {
                   3659:                     $$mimetype = $type;
                   3660:                 } 
1.637     raeburn  3661:             }
1.477     raeburn  3662:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3663:                                  $home);
1.481     raeburn  3664:             if ($fetchresult eq 'ok') {
                   3665:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3666:             } else {
                   3667:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3668:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3669:                 return '/adm/notfound.html';
                   3670:             }
1.477     raeburn  3671:         }
                   3672:     }
1.485     raeburn  3673:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3674:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3675:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3676:     }
                   3677:     return $fetchresult;
                   3678: }
                   3679: 
1.637     raeburn  3680: sub build_filepath {
                   3681:     my ($fpath) = @_;
                   3682:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3683:     unless ($fpath eq '') {
                   3684:         my @parts=split('/',$fpath);
                   3685:         foreach my $part (@parts) {
                   3686:             $filepath.= '/'.$part;
                   3687:             if ((-e $filepath)!=1) {
                   3688:                 mkdir($filepath,0777);
                   3689:             }
                   3690:         }
                   3691:     }
                   3692:     return $filepath;
                   3693: }
                   3694: 
                   3695: sub store_edited_file {
1.638     albertel 3696:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3697:     my $file = $primary_url;
                   3698:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3699:     my $fpath = '';
                   3700:     my $fname = $file;
                   3701:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3702:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3703:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3704:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3705:     print $fh $content;
                   3706:     close($fh);
1.638     albertel 3707:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3708:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3709: 			  $home);
1.637     raeburn  3710:     if ($$fetchresult eq 'ok') {
                   3711:         return '/uploaded/'.$fpath.'/'.$fname;
                   3712:     } else {
1.638     albertel 3713:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3714: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3715:         return '/adm/notfound.html';
                   3716:     }
                   3717: }
                   3718: 
1.531     albertel 3719: sub clean_filename {
1.831     albertel 3720:     my ($fname,$args)=@_;
1.315     www      3721: # Replace Windows backslashes by forward slashes
1.257     www      3722:     $fname=~s/\\/\//g;
1.831     albertel 3723:     if (!$args->{'keep_path'}) {
                   3724:         # Get rid of everything but the actual filename
                   3725: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3726:     }
1.315     www      3727: # Replace spaces by underscores
                   3728:     $fname=~s/\s+/\_/g;
                   3729: # Replace all other weird characters by nothing
1.831     albertel 3730:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3731: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3732: # numbers
                   3733:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3734:     return $fname;
                   3735: }
1.1051    raeburn  3736: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3737: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3738: # image with the same aspect ratio as the original, but with dimensions which do 
                   3739: # not exceed $resizewidth and $resizeheight.
                   3740:  
1.984     neumanie 3741: sub resizeImage {
1.1051    raeburn  3742:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3743:     my $ima = Image::Magick->new;
                   3744:     my $resized;
                   3745:     if (-e $img_path) {
                   3746:         $ima->Read($img_path);
                   3747:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3748:             my $width = $ima->Get('width');
                   3749:             my $height = $ima->Get('height');
                   3750:             if ($width > $resizewidth) {
                   3751: 	        my $factor = $width/$resizewidth;
                   3752:                 my $newheight = $height/$factor;
                   3753:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3754:                 $resized = 1;
                   3755:             }
                   3756:         }
                   3757:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3758:             my $width = $ima->Get('width');
                   3759:             my $height = $ima->Get('height');
                   3760:             if ($height > $resizeheight) {
                   3761:                 my $factor = $height/$resizeheight;
                   3762:                 my $newwidth = $width/$factor;
                   3763:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3764:                 $resized = 1;
                   3765:             }
                   3766:         }
                   3767:         if ($resized) {
                   3768:             $ima->Write($img_path);
                   3769:         }
                   3770:     }
                   3771:     return;
1.977     amueller 3772: }
                   3773: 
1.608     albertel 3774: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3775: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3776: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3777: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3778: #                                    canceloverwrite, or ''. 
                   3779: #                   if 'coursedoc': upload to the current course
                   3780: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3781: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3782: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3783: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3784: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3785: #        $allfiles - reference to hash for embedded objects
                   3786: #        $codebase - reference to hash for codebase of java objects
                   3787: #        $desuname - username for permanent storage of uploaded file
                   3788: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3789: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3790: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3791: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3792: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3793: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3794: #                    from File::MMagic.
1.858     raeburn  3795: # 
1.686     albertel 3796: # output: url of file in userspace, or error: <message> 
                   3797: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3798: 
1.531     albertel 3799: sub userfileupload {
1.1090    raeburn  3800:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3801:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3802:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3803:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3804:     $fname=&clean_filename($fname);
1.1090    raeburn  3805:     # See if there is anything left
1.257     www      3806:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3807:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3808:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3809:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3810:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3811:         my $now = time;
1.1090    raeburn  3812:         my $filepath;
1.1095    raeburn  3813:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3814:              $filepath = 'tmp/helprequests/'.$now;
                   3815:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3816:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3817:                          '_'.$env{'user.domain'}.'/pending';
                   3818:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3819:             my ($docuname,$docudom);
1.1350    raeburn  3820:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3821:                 $docudom = $destudom;
                   3822:             } else {
                   3823:                 $docudom = $env{'user.domain'};
                   3824:             }
1.1350    raeburn  3825:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3826:                 $docuname = $destuname;
                   3827:             } else {
                   3828:                 $docuname = $env{'user.name'};
                   3829:             }
                   3830:             if (exists($env{'form.group'})) {
                   3831:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3832:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3833:             }
                   3834:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3835:             if ($context eq 'canceloverwrite') {
                   3836:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3837:                 if (-e  $tempfile) {
                   3838:                     my @info = stat($tempfile);
                   3839:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3840:                         unlink($tempfile);
                   3841:                     }
                   3842:                 }
                   3843:                 return;
1.523     raeburn  3844:             }
                   3845:         }
1.1090    raeburn  3846:         # Create the directory if not present
1.741     raeburn  3847:         my @parts=split(/\//,$filepath);
                   3848:         my $fullpath = $perlvar{'lonDaemons'};
                   3849:         for (my $i=0;$i<@parts;$i++) {
                   3850:             $fullpath .= '/'.$parts[$i];
                   3851:             if ((-e $fullpath)!=1) {
                   3852:                 mkdir($fullpath,0777);
                   3853:             }
                   3854:         }
1.1359    raeburn  3855:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3856:         print $fh $env{'form.'.$formname};
                   3857:         close($fh);
1.1090    raeburn  3858:         if ($context eq 'existingfile') {
                   3859:             my @info = stat($fullpath.'/'.$fname);
                   3860:             return ($fullpath.'/'.$fname,$info[9]);
                   3861:         } else {
                   3862:             return $fullpath.'/'.$fname;
                   3863:         }
1.523     raeburn  3864:     }
1.995     raeburn  3865:     if ($subdir eq 'scantron') {
                   3866:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3867:     } else {
1.995     raeburn  3868:         $fname="$subdir/$fname";
                   3869:     }
1.1090    raeburn  3870:     if ($context eq 'coursedoc') {
1.638     albertel 3871: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3872: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3873:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3874:             return &finishuserfileupload($docuname,$docudom,
                   3875: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3876: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3877:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3878:         } else {
1.1218    raeburn  3879:             if ($env{'form.folder'}) {
                   3880:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3881:             }
1.638     albertel 3882:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3883: 				       $fname,$formname,$parser,
1.1095    raeburn  3884: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3885:         }
1.719     banghart 3886:     } elsif (defined($destuname)) {
                   3887:         my $docuname=$destuname;
                   3888:         my $docudom=$destudom;
1.860     raeburn  3889: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3890: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3891:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3892:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3893:     } else {
1.638     albertel 3894:         my $docuname=$env{'user.name'};
                   3895:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3896:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3897:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3898:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3899:         }
1.860     raeburn  3900: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3901: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3902:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3903:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3904:     }
1.271     www      3905: }
                   3906: 
                   3907: sub finishuserfileupload {
1.860     raeburn  3908:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3909:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3910:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3911:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3912:   
1.860     raeburn  3913:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3914:     $file=$fname;
                   3915:     if ($fname=~m|/|) {
                   3916:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3917: 	$path.=$fnamepath.'/';
                   3918:     }
1.259     www      3919:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3920:     my $count;
                   3921:     for ($count=4;$count<=$#parts;$count++) {
                   3922:         $filepath.="/$parts[$count]";
                   3923:         if ((-e $filepath)!=1) {
                   3924: 	    mkdir($filepath,0777);
                   3925:         }
                   3926:     }
1.984     neumanie 3927: 
1.258     www      3928: # Save the file
                   3929:     {
1.1359    raeburn  3930: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3931: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3932: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3933: 	    return '/adm/notfound.html';
                   3934: 	}
1.1090    raeburn  3935:         if ($context eq 'overwrite') {
1.1117    foxr     3936:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3937:             my $target = $filepath.'/'.$file;
                   3938:             if (-e $source) {
                   3939:                 my @info = stat($source);
                   3940:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3941:                     unless (&File::Copy::move($source,$target)) {
                   3942:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3943:                         return "Moving from $source failed";
                   3944:                     }
                   3945:                 } else {
                   3946:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3947:                 }
                   3948:             } else {
                   3949:                 return "Temporary file: $source missing";
                   3950:             }
                   3951:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3952: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3953: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3954: 	    return '/adm/notfound.html';
                   3955: 	}
1.570     albertel 3956: 	close(FH);
1.1051    raeburn  3957:         if ($resizewidth && $resizeheight) {
                   3958:             my $mm = new File::MMagic;
                   3959:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3960:             if ($mime_type =~ m{^image/}) {
                   3961: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3962:             }  
1.977     amueller 3963: 	}
1.258     www      3964:     }
1.1152    raeburn  3965:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3966:         if (ref($mimetype)) {
                   3967:             if ($$mimetype eq '') {
                   3968:                 my $mm = new File::MMagic;
                   3969:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3970:                 $$mimetype = $type;
                   3971:             }
                   3972:         }
                   3973:     }
1.637     raeburn  3974:     if ($parser eq 'parse') {
1.1152    raeburn  3975:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3976:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3977:                                                        $allfiles,$codebase);
                   3978:             unless ($parse_result eq 'ok') {
                   3979:                 &logthis('Failed to parse '.$filepath.$file.
                   3980: 	   	         ' for embedded media: '.$parse_result); 
                   3981:             }
1.637     raeburn  3982:         }
                   3983:     }
1.860     raeburn  3984:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3985:         my $input = $filepath.'/'.$file;
                   3986:         my $output = $filepath.'/'.'tn-'.$file;
                   3987:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  3988:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3989:         system({$args[0]} @args);
1.860     raeburn  3990:         if (-e $filepath.'/'.'tn-'.$file) {
                   3991:             $fetchthumb  = 1; 
                   3992:         }
                   3993:     }
1.858     raeburn  3994:  
1.259     www      3995: # Notify homeserver to grep it
                   3996: #
1.984     neumanie 3997:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3998:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3999:     if ($fetchresult eq 'ok') {
1.860     raeburn  4000:         if ($fetchthumb) {
                   4001:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4002:             if ($thumbresult ne 'ok') {
                   4003:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4004:                          $docuhome.': '.$thumbresult);
                   4005:             }
                   4006:         }
1.259     www      4007: #
1.258     www      4008: # Return the URL to it
1.494     albertel 4009:         return '/uploaded/'.$path.$file;
1.263     www      4010:     } else {
1.494     albertel 4011:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4012: 		 ': '.$fetchresult);
1.263     www      4013:         return '/adm/notfound.html';
1.858     raeburn  4014:     }
1.493     albertel 4015: }
                   4016: 
1.637     raeburn  4017: sub extract_embedded_items {
1.961     raeburn  4018:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4019:     my @state = ();
1.1164    raeburn  4020:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4021:     my %javafiles = (
                   4022:                       codebase => '',
                   4023:                       code => '',
                   4024:                       archive => ''
                   4025:                     );
                   4026:     my %mediafiles = (
                   4027:                       src => '',
                   4028:                       movie => '',
                   4029:                      );
1.648     raeburn  4030:     my $p;
                   4031:     if ($content) {
                   4032:         $p = HTML::LCParser->new($content);
                   4033:     } else {
1.961     raeburn  4034:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4035:     }
1.641     albertel 4036:     while (my $t=$p->get_token()) {
1.640     albertel 4037: 	if ($t->[0] eq 'S') {
                   4038: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4039: 	    push(@state, $tagname);
1.648     raeburn  4040:             if (lc($tagname) eq 'allow') {
                   4041:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4042:             }
1.640     albertel 4043: 	    if (lc($tagname) eq 'img') {
                   4044: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4045: 	    }
1.886     albertel 4046: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4047:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4048:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4049:                 }
1.886     albertel 4050: 	    }
1.645     raeburn  4051:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4052:                 my $src;
1.645     raeburn  4053:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4054:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4055:                 } else {
1.1164    raeburn  4056:                     if ($attr->{'src'} ne '') {
                   4057:                         $src = $attr->{'src'};
                   4058:                         &add_filetype($allfiles,$src,'src');
                   4059:                     }
                   4060:                 }
                   4061:                 my $text = $p->get_trimmed_text();
                   4062:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4063:                     my @swfargs = split(/,/,$1);
                   4064:                     foreach my $item (@swfargs) {
                   4065:                         $item =~ s/["']//g;
                   4066:                         $item =~ s/^\s+//;
                   4067:                         $item =~ s/\s+$//;
                   4068:                     }
                   4069:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4070:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4071:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4072:                         } else {
                   4073:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4074:                         }
                   4075:                     }
1.645     raeburn  4076:                 }
                   4077:             }
                   4078:             if (lc($tagname) eq 'link') {
                   4079:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4080:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4081:                 }
                   4082:             }
1.640     albertel 4083: 	    if (lc($tagname) eq 'object' ||
                   4084: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4085: 		foreach my $item (keys(%javafiles)) {
                   4086: 		    $javafiles{$item} = '';
                   4087: 		}
1.1164    raeburn  4088:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4089:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4090:                 }
1.640     albertel 4091: 	    }
                   4092: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4093: 		my $name = lc($attr->{'name'});
                   4094: 		foreach my $item (keys(%javafiles)) {
                   4095: 		    if ($name eq $item) {
                   4096: 			$javafiles{$item} = $attr->{'value'};
                   4097: 			last;
                   4098: 		    }
                   4099: 		}
1.1164    raeburn  4100:                 my $pathfrom;
1.640     albertel 4101: 		foreach my $item (keys(%mediafiles)) {
                   4102: 		    if ($name eq $item) {
1.1164    raeburn  4103:                         $pathfrom = $attr->{'value'};
                   4104:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4105: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4106: 			last;
                   4107: 		    }
                   4108: 		}
1.1164    raeburn  4109:                 if ($name eq 'flashvars') {
                   4110:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4111:                 }
                   4112:                 if ($pathfrom ne '') {
                   4113:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4114:                                          $pathfrom);
                   4115:                 }
1.640     albertel 4116: 	    }
                   4117: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4118: 		foreach my $item (keys(%javafiles)) {
                   4119: 		    if ($attr->{$item}) {
                   4120: 			$javafiles{$item} = $attr->{$item};
                   4121: 			last;
                   4122: 		    }
                   4123: 		}
                   4124: 		foreach my $item (keys(%mediafiles)) {
                   4125: 		    if ($attr->{$item}) {
                   4126: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4127: 			last;
                   4128: 		    }
                   4129: 		}
1.1164    raeburn  4130:                 if (lc($tagname) eq 'embed') {
                   4131:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4132:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4133:                                              $attr->{'src'});
                   4134:                     }
                   4135:                 }
1.640     albertel 4136: 	    }
1.1243    raeburn  4137:             if (lc($tagname) eq 'iframe') {
                   4138:                 my $src = $attr->{'src'} ;
                   4139:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4140:                     &add_filetype($allfiles,$src,'src');
                   4141:                 } elsif ($src =~ m{^/}) {
                   4142:                     if ($env{'request.course.id'}) {
                   4143:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4144:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4145:                         my $url = &hreflocation('',$fullpath);
                   4146:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4147:                             my $relpath = $1;
                   4148:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4149:                                 &add_filetype($allfiles,$1,'src');
                   4150:                             }
                   4151:                         }
                   4152:                     }
                   4153:                 }
                   4154:             }
1.1164    raeburn  4155:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4156:                 pop(@state);
1.1164    raeburn  4157:             }
1.640     albertel 4158: 	} elsif ($t->[0] eq 'E') {
                   4159: 	    my ($tagname) = ($t->[1]);
                   4160: 	    if ($javafiles{'codebase'} ne '') {
                   4161: 		$javafiles{'codebase'} .= '/';
                   4162: 	    }  
                   4163: 	    if (lc($tagname) eq 'applet' ||
                   4164: 		lc($tagname) eq 'object' ||
                   4165: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4166: 		) {
                   4167: 		foreach my $item (keys(%javafiles)) {
                   4168: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4169: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4170: 			&add_filetype($allfiles,$file,$item);
                   4171: 		    }
                   4172: 		}
                   4173: 	    } 
                   4174: 	    pop @state;
                   4175: 	}
                   4176:     }
1.1164    raeburn  4177:     foreach my $id (sort(keys(%flashvars))) {
                   4178:         if ($shockwave{$id} ne '') {
                   4179:             my @pairs = split(/\&/,$flashvars{$id});
                   4180:             foreach my $pair (@pairs) {
                   4181:                 my ($key,$value) = split(/\=/,$pair);
                   4182:                 if ($key eq 'thumb') {
                   4183:                     &add_filetype($allfiles,$value,$key);
                   4184:                 } elsif ($key eq 'content') {
                   4185:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4186:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4187:                     if ($ext ne '') {
                   4188:                         &add_filetype($allfiles,$path.$value,$ext);
                   4189:                     }
                   4190:                 }
                   4191:             }
                   4192:         }
                   4193:     }
1.637     raeburn  4194:     return 'ok';
                   4195: }
                   4196: 
1.639     albertel 4197: sub add_filetype {
                   4198:     my ($allfiles,$file,$type)=@_;
                   4199:     if (exists($allfiles->{$file})) {
                   4200: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4201: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4202: 	}
                   4203:     } else {
                   4204: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4205:     }
                   4206: }
                   4207: 
1.1164    raeburn  4208: sub embedded_dependency {
                   4209:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4210:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4211:         if (($identifier ne '') &&
                   4212:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4213:             ($pathfrom ne '')) {
                   4214:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4215:             foreach my $dep (@{$related->{$identifier}}) {
                   4216:                 &add_filetype($allfiles,$path.$dep,'object');
                   4217:             }
                   4218:         }
                   4219:     }
                   4220:     return;
                   4221: }
                   4222: 
1.493     albertel 4223: sub removeuploadedurl {
1.984     neumanie 4224:     my ($url)=@_;	
                   4225:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4226:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4227: }
                   4228: 
                   4229: sub removeuserfile {
                   4230:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4231:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4232:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4233:     if ($result eq 'ok') {	
1.798     raeburn  4234:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4235:             my $metafile = $fname.'.meta';
                   4236:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4237: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4238:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4239:             my $sqlresult = 
1.823     albertel 4240:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4241:                                         'portfolio_metadata',$group,
                   4242:                                         'delete');
1.798     raeburn  4243:         }
                   4244:     }
                   4245:     return $result;
1.257     www      4246: }
1.15      www      4247: 
1.530     albertel 4248: sub mkdiruserfile {
                   4249:     my ($docuname,$docudom,$dir)=@_;
                   4250:     my $home=&homeserver($docuname,$docudom);
                   4251:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4252: }
                   4253: 
1.531     albertel 4254: sub renameuserfile {
                   4255:     my ($docuname,$docudom,$old,$new)=@_;
                   4256:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4257:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4258:                         &escape("$old").':'.&escape("$new"),$home);
                   4259:     if ($result eq 'ok') {
                   4260:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4261:             my $oldmeta = $old.'.meta';
                   4262:             my $newmeta = $new.'.meta';
                   4263:             my $metaresult = 
                   4264:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4265: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4266:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4267:             my $sqlresult = 
1.823     albertel 4268:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4269:                                         'portfolio_metadata',$group,
                   4270:                                         'delete');
1.798     raeburn  4271:         }
                   4272:     }
                   4273:     return $result;
1.531     albertel 4274: }
                   4275: 
1.14      www      4276: # ------------------------------------------------------------------------- Log
                   4277: 
                   4278: sub log {
                   4279:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4280:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4281: }
                   4282: 
                   4283: # ------------------------------------------------------------------ Course Log
1.352     www      4284: #
                   4285: # This routine flushes several buffers of non-mission-critical nature
                   4286: #
1.157     www      4287: 
                   4288: sub flushcourselogs {
1.352     www      4289:     &logthis('Flushing log buffers');
                   4290: #
                   4291: # course logs
                   4292: # This is a log of all transactions in a course, which can be used
                   4293: # for data mining purposes
                   4294: #
                   4295: # It also collects the courseid database, which lists last transaction
                   4296: # times and course titles for all courseids
                   4297: #
                   4298:     my %courseidbuffer=();
1.921     raeburn  4299:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4300:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4301: 		          &escape($courselogs{$crsid}),
                   4302: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4303: 	    delete $courselogs{$crsid};
                   4304:         } else {
                   4305:             &logthis('Failed to flush log buffer for '.$crsid);
                   4306:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4307:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4308:                         " exceeded maximum size, deleting.</font>");
                   4309:                delete $courselogs{$crsid};
                   4310:             }
1.352     www      4311:         }
1.920     raeburn  4312:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4313:             'description' => $coursedescrbuf{$crsid},
                   4314:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4315:             'type'        => $coursetypebuf{$crsid},
                   4316:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4317:         };
1.191     harris41 4318:     }
1.352     www      4319: #
                   4320: # Write course id database (reverse lookup) to homeserver of courses 
                   4321: # Is used in pickcourse
                   4322: #
1.840     albertel 4323:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4324:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4325:                                     $courseidbuffer{$crs_home},
                   4326:                                     $crs_home,'timeonly');
1.352     www      4327:     }
                   4328: #
                   4329: # File accesses
                   4330: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4331: #
1.449     matthew  4332:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4333:         if ($entry =~ /___count$/) {
                   4334:             my ($dom,$name);
1.807     albertel 4335:             ($dom,$name,undef)=
1.811     albertel 4336: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4337:             if (! defined($dom) || $dom eq '' || 
                   4338:                 ! defined($name) || $name eq '') {
1.620     albertel 4339:                 my $cid = $env{'request.course.id'};
                   4340:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4341:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4342:             }
1.450     matthew  4343:             my $value = $accesshash{$entry};
                   4344:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4345:             my %temphash=($url => $value);
1.449     matthew  4346:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4347:             if ($result eq 'ok') {
                   4348:                 delete $accesshash{$entry};
                   4349:             }
                   4350:         } else {
1.811     albertel 4351:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4352:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4353:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4354:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4355:                 delete $accesshash{$entry};
                   4356:             }
1.185     www      4357:         }
1.191     harris41 4358:     }
1.352     www      4359: #
                   4360: # Roles
                   4361: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4362: #
1.800     albertel 4363:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4364:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4365: 	    split(/\:/,$entry);
                   4366:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4367:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4368:                 $rudom,$runame) eq 'ok') {
                   4369: 	    delete $userrolehash{$entry};
                   4370:         }
                   4371:     }
1.662     raeburn  4372: #
1.1334    raeburn  4373: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4374: #
                   4375:     my %domrolebuffer = ();
1.1000    raeburn  4376:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4377:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4378:         if ($domrolebuffer{$rudom}) {
                   4379:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4380:                       '='.&escape($domainrolehash{$entry});
                   4381:         } else {
                   4382:             $domrolebuffer{$rudom}.=&escape($entry).
                   4383:                       '='.&escape($domainrolehash{$entry});
                   4384:         }
                   4385:         delete $domainrolehash{$entry};
                   4386:     }
                   4387:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4388: 	my %servers;
                   4389: 	if (defined(&domain($dom,'primary'))) {
                   4390: 	    my $primary=&domain($dom,'primary');
                   4391: 	    my $hostname=&hostname($primary);
                   4392: 	    $servers{$primary} = $hostname;
                   4393: 	} else { 
                   4394: 	    %servers = &get_servers($dom,'library');
                   4395: 	}
1.841     albertel 4396: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4397: 	    if (&reply('domroleput:'.$dom.':'.
                   4398: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4399: 		last;
                   4400: 	    } else {  
1.841     albertel 4401: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4402: 	    }
1.662     raeburn  4403:         }
                   4404:     }
1.186     www      4405:     $dumpcount++;
1.157     www      4406: }
                   4407: 
                   4408: sub courselog {
                   4409:     my $what=shift;
1.158     www      4410:     $what=time.':'.$what;
1.620     albertel 4411:     unless ($env{'request.course.id'}) { return ''; }
                   4412:     $coursedombuf{$env{'request.course.id'}}=
                   4413:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4414:     $coursenumbuf{$env{'request.course.id'}}=
                   4415:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4416:     $coursehombuf{$env{'request.course.id'}}=
                   4417:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4418:     $coursedescrbuf{$env{'request.course.id'}}=
                   4419:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4420:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4421:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4422:     $courseownerbuf{$env{'request.course.id'}}=
                   4423:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4424:     $coursetypebuf{$env{'request.course.id'}}=
                   4425:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4426:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4427: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4428:     } else {
1.620     albertel 4429: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4430:     }
1.620     albertel 4431:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4432: 	&flushcourselogs();
                   4433:     }
1.158     www      4434: }
                   4435: 
                   4436: sub courseacclog {
                   4437:     my $fnsymb=shift;
1.620     albertel 4438:     unless ($env{'request.course.id'}) { return ''; }
                   4439:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4440:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4441:         $what.=':POST';
1.583     matthew  4442:         # FIXME: Probably ought to escape things....
1.800     albertel 4443: 	foreach my $key (keys(%env)) {
                   4444:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4445:                 my $formitem = $1;
                   4446:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4447:                     $what.=':'.$formitem.'='.$env{$key};
                   4448:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4449:                     $what.=':'.$formitem.'='.$env{$key};
                   4450:                 }
1.158     www      4451:             }
1.191     harris41 4452:         }
1.583     matthew  4453:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4454:         # FIXME: We should not be depending on a form parameter that someone
                   4455:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4456:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4457:             $what.= ':POST';
                   4458:             # FIXME: Probably ought to escape things....
                   4459:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4460:                                  'crsdiscuss') {
1.620     albertel 4461:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4462:             }
                   4463:         }
1.158     www      4464:     }
                   4465:     &courselog($what);
1.149     www      4466: }
                   4467: 
1.185     www      4468: sub countacc {
                   4469:     my $url=&declutter(shift);
1.458     matthew  4470:     return if (! defined($url) || $url eq '');
1.620     albertel 4471:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4472: #
                   4473: # Mark that this url was used in this course
                   4474: #
1.620     albertel 4475:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4476: #
                   4477: # Increase the access count for this resource in this child process
                   4478: #
1.281     www      4479:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4480:     $accesshash{$key}++;
1.185     www      4481: }
1.349     www      4482: 
1.361     www      4483: sub linklog {
                   4484:     my ($from,$to)=@_;
                   4485:     $from=&declutter($from);
                   4486:     $to=&declutter($to);
                   4487:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4488:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4489: }
1.1160    www      4490: 
                   4491: sub statslog {
                   4492:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4493:     if ($users<2) { return; }
                   4494:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4495:             'course'       => $env{'request.course.id'},
                   4496:             'sections'     => '"all"',
                   4497:             'num_students' => $users,
                   4498:             'part'         => $part,
                   4499:             'symb'         => $symb,
                   4500:             'mean_tries'   => $av_attempts,
                   4501:             'deg_of_diff'  => $degdiff});
                   4502:     foreach my $key (keys(%dynstore)) {
                   4503:         $accesshash{$key}=$dynstore{$key};
                   4504:     }
                   4505: }
1.361     www      4506:   
1.349     www      4507: sub userrolelog {
                   4508:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4509:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4510:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4511:        $userrolehash
                   4512:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4513:                     =$tend.':'.$tstart;
1.662     raeburn  4514:     }
1.1169    droeschl 4515:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4516:        $userrolehash
                   4517:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4518:                     =$tend.':'.$tstart;
                   4519:     }
1.1334    raeburn  4520:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4521:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4522:        $domainrolehash
                   4523:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4524:                     = $tend.':'.$tstart;
                   4525:     }
1.351     www      4526: }
                   4527: 
1.957     raeburn  4528: sub courserolelog {
                   4529:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4530:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4531:         my $cdom = $1;
                   4532:         my $cnum = $2;
                   4533:         my $sec = $3;
                   4534:         my $namespace = 'rolelog';
                   4535:         my %storehash = (
                   4536:                            role    => $trole,
                   4537:                            start   => $tstart,
                   4538:                            end     => $tend,
                   4539:                            selfenroll => $selfenroll,
                   4540:                            context    => $context,
                   4541:                         );
                   4542:         if ($trole eq 'gr') {
                   4543:             $namespace = 'groupslog';
                   4544:             $storehash{'group'} = $sec;
                   4545:         } else {
                   4546:             $storehash{'section'} = $sec;
                   4547:         }
1.1188    raeburn  4548:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4549:                    $domain,$cnum,$cdom);
1.1184    raeburn  4550:         if (($trole ne 'st') || ($sec ne '')) {
                   4551:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4552:         }
                   4553:     }
                   4554:     return;
                   4555: }
                   4556: 
1.1184    raeburn  4557: sub domainrolelog {
                   4558:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4559:     if ($area =~ m{^/($match_domain)/$}) {
                   4560:         my $cdom = $1;
                   4561:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4562:         my $namespace = 'rolelog';
                   4563:         my %storehash = (
                   4564:                            role    => $trole,
                   4565:                            start   => $tstart,
                   4566:                            end     => $tend,
                   4567:                            context => $context,
                   4568:                         );
1.1188    raeburn  4569:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4570:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4571:     }
                   4572:     return;
                   4573: 
                   4574: }
                   4575: 
                   4576: sub coauthorrolelog {
                   4577:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4578:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4579:         my $audom = $1;
                   4580:         my $auname = $2;
                   4581:         my $namespace = 'rolelog';
                   4582:         my %storehash = (
                   4583:                            role    => $trole,
                   4584:                            start   => $tstart,
                   4585:                            end     => $tend,
                   4586:                            context => $context,
                   4587:                         );
1.1188    raeburn  4588:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4589:                    $domain,$auname,$audom);
1.1184    raeburn  4590:     }
                   4591:     return;
                   4592: }
                   4593: 
1.351     www      4594: sub get_course_adv_roles {
1.948     raeburn  4595:     my ($cid,$codes) = @_;
1.620     albertel 4596:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4597:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4598:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4599:     my %nothide=();
1.800     albertel 4600:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4601:         if ($user !~ /:/) {
                   4602: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4603:         } else {
                   4604:             $nothide{$user}=1;
                   4605:         }
1.470     www      4606:     }
1.1219    raeburn  4607:     my @possdoms = ($coursehash{'domain'});
                   4608:     if ($coursehash{'checkforpriv'}) {
                   4609:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4610:     }
1.351     www      4611:     my %returnhash=();
                   4612:     my %dumphash=
                   4613:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4614:     my $now=time;
1.997     raeburn  4615:     my %privileged;
1.1000    raeburn  4616:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4617: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4618:         if (($tstart) && ($tstart<0)) { next; }
                   4619:         if (($tend) && ($tend<$now)) { next; }
                   4620:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4621:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4622: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4623:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4624:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4625: 	if ($role eq 'cr') { next; }
1.948     raeburn  4626:         if ($codes) {
                   4627:             if ($section) { $role .= ':'.$section; }
                   4628:             if ($returnhash{$role}) {
                   4629:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4630:             } else {
                   4631:                 $returnhash{$role}=$username.':'.$domain;
                   4632:             }
1.351     www      4633:         } else {
1.988     raeburn  4634:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4635:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4636:             if ($returnhash{$key}) {
                   4637: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4638:             } else {
                   4639:                 $returnhash{$key}=$username.':'.$domain;
                   4640:             }
1.351     www      4641:         }
1.948     raeburn  4642:     }
1.400     www      4643:     return %returnhash;
                   4644: }
                   4645: 
                   4646: sub get_my_roles {
1.937     raeburn  4647:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4648:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4649:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4650:     my (%dumphash,%nothide);
1.1086    raeburn  4651:     if ($context eq 'userroles') {
1.1166    raeburn  4652:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4653:     } else {
1.1219    raeburn  4654:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4655:         if ($hidepriv) {
                   4656:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4657:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4658:                 if ($user !~ /:/) {
                   4659:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4660:                 } else {
                   4661:                     $nothide{$user} = 1;
                   4662:                 }
                   4663:             }
                   4664:         }
1.858     raeburn  4665:     }
1.400     www      4666:     my %returnhash=();
                   4667:     my $now=time;
1.999     raeburn  4668:     my %privileged;
1.800     albertel 4669:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4670:         my ($role,$tend,$tstart);
                   4671:         if ($context eq 'userroles') {
1.1149    raeburn  4672:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4673: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4674:         } else {
                   4675:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4676:         }
1.400     www      4677:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4678:         my $status = 'active';
1.939     raeburn  4679:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4680:             $status = 'previous';
                   4681:         } 
                   4682:         if (($tstart) && ($now<$tstart)) {
                   4683:             $status = 'future';
                   4684:         }
                   4685:         if (ref($types) eq 'ARRAY') {
                   4686:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4687:                 next;
                   4688:             } 
                   4689:         } else {
                   4690:             if ($status ne 'active') {
                   4691:                 next;
                   4692:             }
                   4693:         }
1.867     raeburn  4694:         my ($rolecode,$username,$domain,$section,$area);
                   4695:         if ($context eq 'userroles') {
1.1186    raeburn  4696:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4697:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4698:         } else {
                   4699:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4700:         }
1.832     raeburn  4701:         if (ref($roledoms) eq 'ARRAY') {
                   4702:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4703:                 next;
                   4704:             }
                   4705:         }
                   4706:         if (ref($roles) eq 'ARRAY') {
                   4707:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4708:                 if ($role =~ /^cr\//) {
                   4709:                     if (!grep(/^cr$/,@{$roles})) {
                   4710:                         next;
                   4711:                     }
1.1104    raeburn  4712:                 } elsif ($role =~ /^gr\//) {
                   4713:                     if (!grep(/^gr$/,@{$roles})) {
                   4714:                         next;
                   4715:                     }
1.922     raeburn  4716:                 } else {
                   4717:                     next;
                   4718:                 }
1.832     raeburn  4719:             }
1.867     raeburn  4720:         }
1.937     raeburn  4721:         if ($hidepriv) {
1.1219    raeburn  4722:             my @privroles = ('dc','su');
1.999     raeburn  4723:             if ($context eq 'userroles') {
1.1219    raeburn  4724:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4725:             } else {
1.1219    raeburn  4726:                 my $possdoms = [$domain];
                   4727:                 if (ref($roledoms) eq 'ARRAY') {
                   4728:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4729:                 }
1.1219    raeburn  4730:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4731:                     if (!$nothide{$username.':'.$domain}) {
                   4732:                         next;
                   4733:                     }
                   4734:                 }
1.937     raeburn  4735:             }
                   4736:         }
1.933     raeburn  4737:         if ($withsec) {
                   4738:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4739:                 $tstart.':'.$tend;
                   4740:         } else {
                   4741:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4742:         }
1.832     raeburn  4743:     }
1.373     www      4744:     return %returnhash;
1.399     www      4745: }
                   4746: 
1.1333    raeburn  4747: sub get_all_adhocroles {
                   4748:     my ($dom) = @_;
                   4749:     my @roles_by_num = ();
                   4750:     my %domdefaults = &get_domain_defaults($dom);
                   4751:     my (%description,%access_in_dom,%access_info);
                   4752:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4753:         my $count = 0;
                   4754:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4755:         my %ordered;
                   4756:         foreach my $role (sort(keys(%domcurrent))) {
                   4757:             my ($order,$desc,$access_in_dom);
                   4758:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4759:                 $order = $domcurrent{$role}{'order'};
                   4760:                 $desc = $domcurrent{$role}{'desc'};
                   4761:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4762:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4763:             }
                   4764:             if ($order eq '') {
                   4765:                 $order = $count;
                   4766:             }
                   4767:             $ordered{$order} = $role;
                   4768:             if ($desc ne '') {
                   4769:                 $description{$role} = $desc;
                   4770:             } else {
                   4771:                 $description{$role}= $role;
                   4772:             }
                   4773:             $count++;
                   4774:         }
                   4775:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4776:             push(@roles_by_num,$ordered{$item});
                   4777:         }
                   4778:     }
                   4779:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4780: }
                   4781: 
1.1332    raeburn  4782: sub get_my_adhocroles {
1.1333    raeburn  4783:     my ($cid,$checkreg) = @_;
                   4784:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4785:     if ($env{'request.course.id'} eq $cid) {
                   4786:         $cdom = $env{'course.'.$cid.'.domain'};
                   4787:         $cnum = $env{'course.'.$cid.'.num'};
                   4788:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4789:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4790:         $cdom = $1;
                   4791:         $cnum = $2;
                   4792:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4793:                                      $cdom,$cnum);
                   4794:     }
                   4795:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4796:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4797:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4798:         if ($rosterhash{$user} ne '') {
                   4799:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4800:             return ([],{}) if ($type eq 'auto');
                   4801:         }
                   4802:     }
                   4803:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4804:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4805:             my $then=$env{'user.login.time'};
                   4806:             my $update=$env{'user.update.time'};
1.1335    raeburn  4807:             if (!$update) {
                   4808:                 $update = $then;
                   4809:             }
                   4810:             my @liveroles;
1.1334    raeburn  4811:             foreach my $role ('dh','da') {
                   4812:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4813:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4814:                     my $limit = $update;
                   4815:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4816:                         $limit = $then;
                   4817:                     }
1.1335    raeburn  4818:                     my $activerole = 1;
                   4819:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4820:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4821:                     if ($activerole) {
                   4822:                         push(@liveroles,$role);
                   4823:                     }
1.1334    raeburn  4824:                 }
1.1332    raeburn  4825:             }
1.1335    raeburn  4826:             if (@liveroles) {
1.1332    raeburn  4827:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4828:                     my ($accessref,$accessinfo,%access_in_dom);
                   4829:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4830:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4831:                         if (@{$roles_by_num}) {
1.1332    raeburn  4832:                             my %settings;
                   4833:                             if ($env{'request.course.id'} eq $cid) {
                   4834:                                 foreach my $envkey (keys(%env)) {
                   4835:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4836:                                         $settings{$1} = $env{$envkey};
                   4837:                                     }
                   4838:                                 }
                   4839:                             } else {
                   4840:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4841:                             }
                   4842:                             my %setincrs;
                   4843:                             if ($settings{'internal.adhocaccess'}) {
                   4844:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4845:                             }
                   4846:                             my @statuses;
                   4847:                             if ($env{'environment.inststatus'}) {
                   4848:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4849:                             }
                   4850:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4851:                             if (ref($accessref) eq 'HASH') {
                   4852:                                 %access_in_dom = %{$accessref};
                   4853:                             }
                   4854:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4855:                                 my ($curraccess,@okstatus,@personnel);
                   4856:                                 if ($setincrs{$role}) {
                   4857:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4858:                                     if ($curraccess eq 'status') {
                   4859:                                         @okstatus = split(/\&/,$rest);
                   4860:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4861:                                         @personnel = split(/\&/,$rest);
                   4862:                                     }
                   4863:                                 } else {
                   4864:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4865:                                     if (ref($accessinfo) eq 'HASH') {
                   4866:                                         if ($curraccess eq 'status') {
                   4867:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4868:                                                 @okstatus = @{$accessinfo->{$role}};
                   4869:                                             }
                   4870:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4871:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4872:                                                 @personnel = @{$accessinfo->{$role}};
                   4873:                                             }
1.1332    raeburn  4874:                                         }
                   4875:                                     }
                   4876:                                 }
                   4877:                                 if ($curraccess eq 'none') {
                   4878:                                     next;
                   4879:                                 } elsif ($curraccess eq 'all') {
                   4880:                                     push(@possroles,$role);
1.1336    raeburn  4881:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4882:                                     if (grep(/^dh$/,@liveroles)) {
                   4883:                                         push(@possroles,$role);
                   4884:                                     } else {
                   4885:                                         next;
                   4886:                                     }
1.1336    raeburn  4887:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4888:                                     if (grep(/^da$/,@liveroles)) {
                   4889:                                         push(@possroles,$role);
                   4890:                                     } else {
                   4891:                                         next;
                   4892:                                     }
1.1332    raeburn  4893:                                 } elsif ($curraccess eq 'status') {
                   4894:                                     if (@okstatus) {
                   4895:                                         if (!@statuses) {
                   4896:                                             if (grep(/^default$/,@okstatus)) {
                   4897:                                                 push(@possroles,$role);
                   4898:                                             }
                   4899:                                         } else {
                   4900:                                             foreach my $status (@okstatus) {
                   4901:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4902:                                                     push(@possroles,$role);
                   4903:                                                     last;
                   4904:                                                 }
                   4905:                                             }
                   4906:                                         }
                   4907:                                     }
                   4908:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4909:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4910:                                         if ($curraccess eq 'exc') {
                   4911:                                             push(@possroles,$role);
                   4912:                                         }
                   4913:                                     } elsif ($curraccess eq 'inc') {
                   4914:                                         push(@possroles,$role);
                   4915:                                     }
                   4916:                                 }
                   4917:                             }
                   4918:                         }
                   4919:                     }
                   4920:                 }
                   4921:             }
                   4922:         }
                   4923:     }
1.1333    raeburn  4924:     unless (ref($description) eq 'HASH') {
                   4925:         if (ref($roles_by_num) eq 'ARRAY') {
                   4926:             my %desc;
                   4927:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4928:             $description = \%desc;
                   4929:         } else {
                   4930:             $description = {};
                   4931:         }
                   4932:     }
                   4933:     return (\@possroles,$description);
1.1332    raeburn  4934: }
                   4935: 
1.399     www      4936: # ----------------------------------------------------- Frontpage Announcements
                   4937: #
                   4938: #
                   4939: 
                   4940: sub postannounce {
                   4941:     my ($server,$text)=@_;
1.844     albertel 4942:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4943:     unless ($text=~/\w/) { $text=''; }
                   4944:     return &reply('setannounce:'.&escape($text),$server);
                   4945: }
                   4946: 
                   4947: sub getannounce {
1.448     albertel 4948: 
1.1359    raeburn  4949:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4950: 	my $announcement='';
1.800     albertel 4951: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4952: 	close($fh);
1.399     www      4953: 	if ($announcement=~/\w/) { 
                   4954: 	    return 
                   4955:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4956:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4957: 	} else {
                   4958: 	    return '';
                   4959: 	}
                   4960:     } else {
                   4961: 	return '';
                   4962:     }
1.351     www      4963: }
1.353     www      4964: 
                   4965: # ---------------------------------------------------------- Course ID routines
                   4966: # Deal with domain's nohist_courseid.db files
                   4967: #
                   4968: 
                   4969: sub courseidput {
1.921     raeburn  4970:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4971:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4972:     my $outcome;
                   4973:     if ($caller eq 'timeonly') {
                   4974:         my $cids = '';
                   4975:         foreach my $item (keys(%$storehash)) {
                   4976:             $cids.=&escape($item).'&';
                   4977:         }
                   4978:         $cids=~s/\&$//;
                   4979:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4980:                           $coursehome);       
                   4981:     } else {
                   4982:         my $items = '';
                   4983:         foreach my $item (keys(%$storehash)) {
                   4984:             $items.= &escape($item).'='.
                   4985:                      &freeze_escape($$storehash{$item}).'&';
                   4986:         }
                   4987:         $items=~s/\&$//;
                   4988:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4989:                           $coursehome);
1.918     raeburn  4990:     }
                   4991:     if ($outcome eq 'unknown_cmd') {
                   4992:         my $what;
                   4993:         foreach my $cid (keys(%$storehash)) {
                   4994:             $what .= &escape($cid).'=';
1.921     raeburn  4995:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4996:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4997:             }
                   4998:             $what =~ s/\:$/&/;
                   4999:         }
                   5000:         $what =~ s/\&$//;  
                   5001:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5002:     } else {
                   5003:         return $outcome;
                   5004:     }
1.353     www      5005: }
                   5006: 
                   5007: sub courseiddump {
1.921     raeburn  5008:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5009:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5010:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5011:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5012:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5013:     my $as_hash = 1;
                   5014:     my %returnhash;
                   5015:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5016:     my %libserv = &all_library();
                   5017:     foreach my $tryserver (keys(%libserv)) {
                   5018:         if ( (  $hostidflag == 1 
                   5019: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5020: 	     || (!defined($hostidflag)) ) {
                   5021: 
1.918     raeburn  5022: 	    if (($domfilter eq '') ||
                   5023: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5024:                 my $rep;
                   5025:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5026:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5027:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5028:                                 &escape($descfilter), &escape($instcodefilter), 
                   5029:                                 &escape($ownerfilter), &escape($coursefilter),
                   5030:                                 &escape($typefilter), &escape($regexp_ok), 
                   5031:                                 $as_hash, &escape($selfenrollonly), 
                   5032:                                 &escape($catfilter), $showhidden, $caller, 
                   5033:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5034:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5035:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5036:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5037:                 } else {
                   5038:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5039:                              $sincefilter.':'.&escape($descfilter).':'.
                   5040:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5041:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5042:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5043:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5044:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5045:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5046:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5047:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5048:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5049:                 }
                   5050:                      
1.918     raeburn  5051:                 my @pairs=split(/\&/,$rep);
                   5052:                 foreach my $item (@pairs) {
                   5053:                     my ($key,$value)=split(/\=/,$item,2);
                   5054:                     $key = &unescape($key);
                   5055:                     next if ($key =~ /^error: 2 /);
                   5056:                     my $result = &thaw_unescape($value);
                   5057:                     if (ref($result) eq 'HASH') {
                   5058:                         $returnhash{$key}=$result;
                   5059:                     } else {
1.921     raeburn  5060:                         my @responses = split(/:/,$value);
                   5061:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5062:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5063:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5064:                         }
1.1008    raeburn  5065:                     }
1.353     www      5066:                 }
                   5067:             }
                   5068:         }
                   5069:     }
                   5070:     return %returnhash;
                   5071: }
                   5072: 
1.1055    raeburn  5073: sub courselastaccess {
                   5074:     my ($cdom,$cnum,$hostidref) = @_;
                   5075:     my %returnhash;
                   5076:     if ($cdom && $cnum) {
                   5077:         my $chome = &homeserver($cnum,$cdom);
                   5078:         if ($chome ne 'no_host') {
                   5079:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5080:             &extract_lastaccess(\%returnhash,$rep);
                   5081:         }
                   5082:     } else {
                   5083:         if (!$cdom) { $cdom=''; }
                   5084:         my %libserv = &all_library();
                   5085:         foreach my $tryserver (keys(%libserv)) {
                   5086:             if (ref($hostidref) eq 'ARRAY') {
                   5087:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5088:             } 
                   5089:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5090:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5091:                 &extract_lastaccess(\%returnhash,$rep);
                   5092:             }
                   5093:         }
                   5094:     }
                   5095:     return %returnhash;
                   5096: }
                   5097: 
                   5098: sub extract_lastaccess {
                   5099:     my ($returnhash,$rep) = @_;
                   5100:     if (ref($returnhash) eq 'HASH') {
                   5101:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5102:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5103:                  $rep eq '') {
                   5104:             my @pairs=split(/\&/,$rep);
                   5105:             foreach my $item (@pairs) {
                   5106:                 my ($key,$value)=split(/\=/,$item,2);
                   5107:                 $key = &unescape($key);
                   5108:                 next if ($key =~ /^error: 2 /);
                   5109:                 $returnhash->{$key} = &thaw_unescape($value);
                   5110:             }
                   5111:         }
                   5112:     }
                   5113:     return;
                   5114: }
                   5115: 
1.658     raeburn  5116: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5117: 
                   5118: sub dcmailput {
1.685     raeburn  5119:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5120:     my $status = &Apache::lonnet::critical(
1.740     www      5121:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5122:        &escape($message),$server);
1.662     raeburn  5123:     return $status;
                   5124: }
                   5125: 
1.658     raeburn  5126: sub dcmaildump {
                   5127:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5128:     my %returnhash=();
1.846     albertel 5129: 
                   5130:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5131:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5132:                                                          &escape($enddate).':';
                   5133: 	my @esc_senders=map { &escape($_)} @$senders;
                   5134: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5135: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5136:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5137:             if (($key) && ($value)) {
                   5138:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5139:             }
                   5140:         }
                   5141:     }
                   5142:     return %returnhash;
                   5143: }
1.662     raeburn  5144: # ---------------------------------------------------------- Domain roles
                   5145: 
                   5146: sub get_domain_roles {
                   5147:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5148:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5149:         $startdate = '.';
                   5150:     }
1.1018    raeburn  5151:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5152:         $enddate = '.';
                   5153:     }
1.922     raeburn  5154:     my $rolelist;
                   5155:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5156:         $rolelist = join('&',@{$roles});
1.922     raeburn  5157:     }
1.662     raeburn  5158:     my %personnel = ();
1.841     albertel 5159: 
                   5160:     my %servers = &get_servers($dom,'library');
                   5161:     foreach my $tryserver (keys(%servers)) {
                   5162: 	%{$personnel{$tryserver}}=();
                   5163: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5164: 					    &escape($startdate).':'.
                   5165: 					    &escape($enddate).':'.
                   5166: 					    &escape($rolelist), $tryserver))) {
                   5167: 	    my ($key,$value) = split(/\=/,$line,2);
                   5168: 	    if (($key) && ($value)) {
                   5169: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5170: 	    }
                   5171: 	}
1.662     raeburn  5172:     }
                   5173:     return %personnel;
                   5174: }
1.658     raeburn  5175: 
1.1332    raeburn  5176: sub get_active_domroles {
                   5177:     my ($dom,$roles) = @_;
                   5178:     return () unless (ref($roles) eq 'ARRAY');
                   5179:     my $now = time;
                   5180:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5181:     my %domroles;
                   5182:     foreach my $server (keys(%dompersonnel)) {
                   5183:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5184:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5185:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5186:         }
                   5187:     }
                   5188:     return %domroles;
                   5189: }
                   5190: 
1.1057    www      5191: # ----------------------------------------------------------- Interval timing 
1.149     www      5192: 
1.1153    www      5193: {
                   5194: # Caches needed for speedup of navmaps
                   5195: # We don't want to cache this for very long at all (5 seconds at most)
                   5196: # 
                   5197: # The user for whom we cache
                   5198: my $cachedkey='';
                   5199: # The cached times for this user
                   5200: my %cachedtimes=();
                   5201: # When this was last done
1.1282    raeburn  5202: my $cachedtime='';
1.1153    www      5203: 
                   5204: sub load_all_first_access {
1.1308    raeburn  5205:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5206:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5207:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5208:         (!$ignorecache)) {
1.1154    raeburn  5209:         return;
                   5210:     }
                   5211:     $cachedtime=time;
                   5212:     $cachedkey=$uname.':'.$udom;
                   5213:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5214: }
                   5215: 
1.504     albertel 5216: sub get_first_access {
1.1308    raeburn  5217:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5218:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5219:     if ($argsymb) { $symb=$argsymb; }
                   5220:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5221:     if ($argmap) { $map = $argmap; }
1.926     albertel 5222:     if ($type eq 'course') {
                   5223: 	$res='course';
                   5224:     } elsif ($type eq 'map') {
1.588     albertel 5225: 	$res=&symbread($map);
                   5226:     } else {
                   5227: 	$res=$symb;
                   5228:     }
1.1308    raeburn  5229:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5230:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5231: }
                   5232: 
                   5233: sub set_first_access {
1.1162    raeburn  5234:     my ($type,$interval)=@_;
1.790     albertel 5235:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5236:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5237:     if ($type eq 'course') {
                   5238: 	$res='course';
                   5239:     } elsif ($type eq 'map') {
1.588     albertel 5240: 	$res=&symbread($map);
                   5241:     } else {
                   5242: 	$res=$symb;
                   5243:     }
1.1153    www      5244:     $cachedkey='';
1.1162    raeburn  5245:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5246:     if ($firstaccess) {
                   5247:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5248:                  "to set new value (type: $type, extent: $res) for $uname:$udom ". 
                   5249:                  "in $courseid"); 
                   5250:         return 'already_set';
                   5251:     } else {
1.1162    raeburn  5252:         my $start = time;
                   5253: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5254:                           $udom,$uname);
                   5255:         if ($putres eq 'ok') {
                   5256:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5257:                  $udom,$uname); 
                   5258:             &appenv(
                   5259:                      {
                   5260:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5261:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5262:                      }
                   5263:                   );
1.1365    raeburn  5264:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5265:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5266:             }
1.1386    raeburn  5267:         } elsif ($putres ne 'refused') {
                   5268:             &logthis("Result: $putres when attempting to set first access time ".
                   5269:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5270:         }
                   5271:         return $putres;
1.505     albertel 5272:     }
                   5273:     return 'already_set';
1.504     albertel 5274: }
1.1153    www      5275: }
1.1282    raeburn  5276: 
1.110     www      5277: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5278: 
                   5279: sub expirespread {
                   5280:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5281:     my $cid=$env{'request.course.id'}; 
1.110     www      5282:     if ($cid) {
                   5283:        my $now=time;
                   5284:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5285:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5286:                             $env{'course.'.$cid.'.num'}.
1.110     www      5287: 	        	    ':nohist_expirationdates:'.
                   5288:                             &escape($key).'='.$now,
1.620     albertel 5289:                             $env{'course.'.$cid.'.home'})
1.110     www      5290:     }
                   5291:     return 'ok';
1.14      www      5292: }
                   5293: 
1.109     www      5294: # ----------------------------------------------------- Devalidate Spreadsheets
                   5295: 
                   5296: sub devalidate {
1.325     www      5297:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5298:     my $cid=$env{'request.course.id'}; 
1.109     www      5299:     if ($cid) {
1.391     matthew  5300:         # delete the stored spreadsheets for
                   5301:         # - the student level sheet of this user in course's homespace
                   5302:         # - the assessment level sheet for this resource 
                   5303:         #   for this user in user's homespace
1.553     albertel 5304: 	# - current conditional state info
1.325     www      5305: 	my $key=$uname.':'.$udom.':';
1.109     www      5306:         my $status=
1.299     matthew  5307: 	    &del('nohist_calculatedsheets',
1.391     matthew  5308: 		 [$key.'studentcalc:'],
1.620     albertel 5309: 		 $env{'course.'.$cid.'.domain'},
                   5310: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5311: 		.' '.
                   5312: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5313: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5314:         unless ($status eq 'ok ok') {
                   5315:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5316:                     $uname.' at '.$udom.' for '.
1.109     www      5317: 		    $symb.': '.$status);
1.133     albertel 5318:         }
1.553     albertel 5319: 	&delenv('user.state.'.$cid);
1.109     www      5320:     }
                   5321: }
                   5322: 
1.265     albertel 5323: sub get_scalar {
                   5324:     my ($string,$end) = @_;
                   5325:     my $value;
                   5326:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5327: 	$value = $1;
                   5328:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5329: 	$value = $1;
                   5330:     }
                   5331:     return &unescape($value);
                   5332: }
                   5333: 
                   5334: sub array2str {
                   5335:   my (@array) = @_;
                   5336:   my $result=&arrayref2str(\@array);
                   5337:   $result=~s/^__ARRAY_REF__//;
                   5338:   $result=~s/__END_ARRAY_REF__$//;
                   5339:   return $result;
                   5340: }
                   5341: 
1.204     albertel 5342: sub arrayref2str {
                   5343:   my ($arrayref) = @_;
1.265     albertel 5344:   my $result='__ARRAY_REF__';
1.204     albertel 5345:   foreach my $elem (@$arrayref) {
1.265     albertel 5346:     if(ref($elem) eq 'ARRAY') {
                   5347:       $result.=&arrayref2str($elem).'&';
                   5348:     } elsif(ref($elem) eq 'HASH') {
                   5349:       $result.=&hashref2str($elem).'&';
                   5350:     } elsif(ref($elem)) {
                   5351:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5352:     } else {
                   5353:       $result.=&escape($elem).'&';
                   5354:     }
                   5355:   }
                   5356:   $result=~s/\&$//;
1.265     albertel 5357:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5358:   return $result;
                   5359: }
                   5360: 
1.168     albertel 5361: sub hash2str {
1.204     albertel 5362:   my (%hash) = @_;
                   5363:   my $result=&hashref2str(\%hash);
1.265     albertel 5364:   $result=~s/^__HASH_REF__//;
                   5365:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5366:   return $result;
                   5367: }
                   5368: 
                   5369: sub hashref2str {
                   5370:   my ($hashref)=@_;
1.265     albertel 5371:   my $result='__HASH_REF__';
1.800     albertel 5372:   foreach my $key (sort(keys(%$hashref))) {
                   5373:     if (ref($key) eq 'ARRAY') {
                   5374:       $result.=&arrayref2str($key).'=';
                   5375:     } elsif (ref($key) eq 'HASH') {
                   5376:       $result.=&hashref2str($key).'=';
                   5377:     } elsif (ref($key)) {
1.265     albertel 5378:       $result.='=';
1.800     albertel 5379:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5380:     } else {
1.1132    raeburn  5381: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5382:     }
                   5383: 
1.800     albertel 5384:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5385:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5386:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5387:       $result.=&hashref2str($hashref->{$key}).'&';
                   5388:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5389:        $result.='&';
1.800     albertel 5390:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5391:     } else {
1.800     albertel 5392:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5393:     }
                   5394:   }
1.168     albertel 5395:   $result=~s/\&$//;
1.265     albertel 5396:   $result .= '__END_HASH_REF__';
1.168     albertel 5397:   return $result;
                   5398: }
                   5399: 
                   5400: sub str2hash {
1.265     albertel 5401:     my ($string)=@_;
                   5402:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5403:     return %$hash;
                   5404: }
                   5405: 
                   5406: sub str2hashref {
1.168     albertel 5407:   my ($string) = @_;
1.265     albertel 5408: 
                   5409:   my %hash;
                   5410: 
                   5411:   if($string !~ /^__HASH_REF__/) {
                   5412:       if (! ($string eq '' || !defined($string))) {
                   5413: 	  $hash{'error'}='Not hash reference';
                   5414:       }
                   5415:       return (\%hash, $string);
                   5416:   }
                   5417: 
                   5418:   $string =~ s/^__HASH_REF__//;
                   5419: 
                   5420:   while($string !~ /^__END_HASH_REF__/) {
                   5421:       #key
                   5422:       my $key='';
                   5423:       if($string =~ /^__HASH_REF__/) {
                   5424:           ($key, $string)=&str2hashref($string);
                   5425:           if(defined($key->{'error'})) {
                   5426:               $hash{'error'}='Bad data';
                   5427:               return (\%hash, $string);
                   5428:           }
                   5429:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5430:           ($key, $string)=&str2arrayref($string);
                   5431:           if($key->[0] eq 'Array reference error') {
                   5432:               $hash{'error'}='Bad data';
                   5433:               return (\%hash, $string);
                   5434:           }
                   5435:       } else {
                   5436:           $string =~ s/^(.*?)=//;
1.267     albertel 5437: 	  $key=&unescape($1);
1.265     albertel 5438:       }
                   5439:       $string =~ s/^=//;
                   5440: 
                   5441:       #value
                   5442:       my $value='';
                   5443:       if($string =~ /^__HASH_REF__/) {
                   5444:           ($value, $string)=&str2hashref($string);
                   5445:           if(defined($value->{'error'})) {
                   5446:               $hash{'error'}='Bad data';
                   5447:               return (\%hash, $string);
                   5448:           }
                   5449:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5450:           ($value, $string)=&str2arrayref($string);
                   5451:           if($value->[0] eq 'Array reference error') {
                   5452:               $hash{'error'}='Bad data';
                   5453:               return (\%hash, $string);
                   5454:           }
                   5455:       } else {
                   5456: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5457:       }
                   5458:       $string =~ s/^&//;
                   5459: 
                   5460:       $hash{$key}=$value;
1.204     albertel 5461:   }
1.265     albertel 5462: 
                   5463:   $string =~ s/^__END_HASH_REF__//;
                   5464: 
                   5465:   return (\%hash, $string);
1.204     albertel 5466: }
                   5467: 
                   5468: sub str2array {
1.265     albertel 5469:     my ($string)=@_;
                   5470:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5471:     return @$array;
                   5472: }
                   5473: 
                   5474: sub str2arrayref {
1.204     albertel 5475:   my ($string) = @_;
1.265     albertel 5476:   my @array;
                   5477: 
                   5478:   if($string !~ /^__ARRAY_REF__/) {
                   5479:       if (! ($string eq '' || !defined($string))) {
                   5480: 	  $array[0]='Array reference error';
                   5481:       }
                   5482:       return (\@array, $string);
                   5483:   }
                   5484: 
                   5485:   $string =~ s/^__ARRAY_REF__//;
                   5486: 
                   5487:   while($string !~ /^__END_ARRAY_REF__/) {
                   5488:       my $value='';
                   5489:       if($string =~ /^__HASH_REF__/) {
                   5490:           ($value, $string)=&str2hashref($string);
                   5491:           if(defined($value->{'error'})) {
                   5492:               $array[0] ='Array reference error';
                   5493:               return (\@array, $string);
                   5494:           }
                   5495:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5496:           ($value, $string)=&str2arrayref($string);
                   5497:           if($value->[0] eq 'Array reference error') {
                   5498:               $array[0] ='Array reference error';
                   5499:               return (\@array, $string);
                   5500:           }
                   5501:       } else {
                   5502: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5503:       }
                   5504:       $string =~ s/^&//;
                   5505: 
                   5506:       push(@array, $value);
1.191     harris41 5507:   }
1.265     albertel 5508: 
                   5509:   $string =~ s/^__END_ARRAY_REF__//;
                   5510: 
                   5511:   return (\@array, $string);
1.168     albertel 5512: }
                   5513: 
1.167     albertel 5514: # -------------------------------------------------------------------Temp Store
                   5515: 
1.168     albertel 5516: sub tmpreset {
                   5517:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5518:   if (!$symb) {
                   5519:     $symb=&symbread();
1.620     albertel 5520:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5521:   }
                   5522:   $symb=escape($symb);
                   5523: 
1.620     albertel 5524:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5525:   $namespace=~s/\//\_/g;
                   5526:   $namespace=~s/\W//g;
                   5527: 
1.620     albertel 5528:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5529:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5530:   if ($domain eq 'public' && $stuname eq 'public') {
                   5531:       $stuname=$ENV{'REMOTE_ADDR'};
                   5532:   }
1.1117    foxr     5533:   my $path=LONCAPA::tempdir();
1.168     albertel 5534:   my %hash;
                   5535:   if (tie(%hash,'GDBM_File',
                   5536: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5537: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5538:     foreach my $key (keys(%hash)) {
1.180     albertel 5539:       if ($key=~ /:$symb/) {
1.168     albertel 5540: 	delete($hash{$key});
                   5541:       }
                   5542:     }
                   5543:   }
                   5544: }
                   5545: 
1.167     albertel 5546: sub tmpstore {
1.168     albertel 5547:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5548: 
                   5549:   if (!$symb) {
                   5550:     $symb=&symbread();
1.620     albertel 5551:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5552:   }
                   5553:   $symb=escape($symb);
                   5554: 
                   5555:   if (!$namespace) {
                   5556:     # I don't think we would ever want to store this for a course.
                   5557:     # it seems this will only be used if we don't have a course.
1.620     albertel 5558:     #$namespace=$env{'request.course.id'};
1.168     albertel 5559:     #if (!$namespace) {
1.620     albertel 5560:       $namespace=$env{'request.state'};
1.168     albertel 5561:     #}
                   5562:   }
                   5563:   $namespace=~s/\//\_/g;
                   5564:   $namespace=~s/\W//g;
1.620     albertel 5565:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5566:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5567:   if ($domain eq 'public' && $stuname eq 'public') {
                   5568:       $stuname=$ENV{'REMOTE_ADDR'};
                   5569:   }
1.168     albertel 5570:   my $now=time;
                   5571:   my %hash;
1.1117    foxr     5572:   my $path=LONCAPA::tempdir();
1.168     albertel 5573:   if (tie(%hash,'GDBM_File',
                   5574: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5575: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5576:     $hash{"version:$symb"}++;
                   5577:     my $version=$hash{"version:$symb"};
                   5578:     my $allkeys=''; 
                   5579:     foreach my $key (keys(%$storehash)) {
                   5580:       $allkeys.=$key.':';
1.591     albertel 5581:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5582:     }
                   5583:     $hash{"$version:$symb:timestamp"}=$now;
                   5584:     $allkeys.='timestamp';
                   5585:     $hash{"$version:keys:$symb"}=$allkeys;
                   5586:     if (untie(%hash)) {
                   5587:       return 'ok';
                   5588:     } else {
                   5589:       return "error:$!";
                   5590:     }
                   5591:   } else {
                   5592:     return "error:$!";
                   5593:   }
                   5594: }
1.167     albertel 5595: 
1.168     albertel 5596: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5597: 
1.168     albertel 5598: sub tmprestore {
                   5599:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5600: 
1.168     albertel 5601:   if (!$symb) {
                   5602:     $symb=&symbread();
1.620     albertel 5603:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5604:   }
                   5605:   $symb=escape($symb);
                   5606: 
1.620     albertel 5607:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5608: 
1.620     albertel 5609:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5610:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5611:   if ($domain eq 'public' && $stuname eq 'public') {
                   5612:       $stuname=$ENV{'REMOTE_ADDR'};
                   5613:   }
1.168     albertel 5614:   my %returnhash;
                   5615:   $namespace=~s/\//\_/g;
                   5616:   $namespace=~s/\W//g;
                   5617:   my %hash;
1.1117    foxr     5618:   my $path=LONCAPA::tempdir();
1.168     albertel 5619:   if (tie(%hash,'GDBM_File',
                   5620: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5621: 	  &GDBM_READER(),0640)) {
1.168     albertel 5622:     my $version=$hash{"version:$symb"};
                   5623:     $returnhash{'version'}=$version;
                   5624:     my $scope;
                   5625:     for ($scope=1;$scope<=$version;$scope++) {
                   5626:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5627:       my @keys=split(/:/,$vkeys);
                   5628:       my $key;
                   5629:       $returnhash{"$scope:keys"}=$vkeys;
                   5630:       foreach $key (@keys) {
1.591     albertel 5631: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5632: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5633:       }
                   5634:     }
1.168     albertel 5635:     if (!(untie(%hash))) {
                   5636:       return "error:$!";
                   5637:     }
                   5638:   } else {
                   5639:     return "error:$!";
                   5640:   }
                   5641:   return %returnhash;
1.167     albertel 5642: }
                   5643: 
1.9       www      5644: # ----------------------------------------------------------------------- Store
                   5645: 
                   5646: sub store {
1.1269    raeburn  5647:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5648:     my $home='';
                   5649: 
1.168     albertel 5650:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5651: 
1.213     www      5652:     $symb=&symbclean($symb);
1.122     albertel 5653:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5654: 
1.620     albertel 5655:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5656:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5657: 
                   5658:     &devalidate($symb,$stuname,$domain);
1.109     www      5659: 
                   5660:     $symb=escape($symb);
1.187     www      5661:     if (!$namespace) { 
1.620     albertel 5662:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5663:           return ''; 
                   5664:        } 
                   5665:     }
1.620     albertel 5666:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5667: 
                   5668:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5669:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5670: 
1.12      www      5671:     my $namevalue='';
1.800     albertel 5672:     foreach my $key (keys(%$storehash)) {
                   5673:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5674:     }
1.12      www      5675:     $namevalue=~s/\&$//;
1.187     www      5676:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5677:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5678: }
                   5679: 
1.47      www      5680: # -------------------------------------------------------------- Critical Store
                   5681: 
                   5682: sub cstore {
1.1269    raeburn  5683:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5684:     my $home='';
                   5685: 
1.168     albertel 5686:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5687: 
1.213     www      5688:     $symb=&symbclean($symb);
1.122     albertel 5689:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5690: 
1.620     albertel 5691:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5692:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5693: 
                   5694:     &devalidate($symb,$stuname,$domain);
1.109     www      5695: 
                   5696:     $symb=escape($symb);
1.187     www      5697:     if (!$namespace) { 
1.620     albertel 5698:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5699:           return ''; 
                   5700:        } 
                   5701:     }
1.620     albertel 5702:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5703: 
                   5704:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5705:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5706: 
1.47      www      5707:     my $namevalue='';
1.800     albertel 5708:     foreach my $key (keys(%$storehash)) {
                   5709:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5710:     }
1.47      www      5711:     $namevalue=~s/\&$//;
1.187     www      5712:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5713:     return critical
1.1269    raeburn  5714:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5715: }
                   5716: 
1.9       www      5717: # --------------------------------------------------------------------- Restore
                   5718: 
                   5719: sub restore {
1.124     www      5720:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5721:     my $home='';
                   5722: 
1.168     albertel 5723:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5724: 
1.122     albertel 5725:     if (!$symb) {
1.1224    raeburn  5726:         return if ($namespace eq 'courserequests');
                   5727:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5728:     } else {
1.1224    raeburn  5729:         unless ($namespace eq 'courserequests') {
                   5730:             $symb=&escape(&symbclean($symb));
                   5731:         }
1.122     albertel 5732:     }
1.188     www      5733:     if (!$namespace) { 
1.620     albertel 5734:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5735:           return ''; 
                   5736:        } 
                   5737:     }
1.620     albertel 5738:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5739:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5740:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5741:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5742: 
1.12      www      5743:     my %returnhash=();
1.800     albertel 5744:     foreach my $line (split(/\&/,$answer)) {
                   5745: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5746:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5747:     }
1.75      www      5748:     my $version;
                   5749:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5750:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5751:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5752:        }
1.75      www      5753:     }
1.13      www      5754:     return %returnhash;
1.34      www      5755: }
                   5756: 
                   5757: # ---------------------------------------------------------- Course Description
1.1118    foxr     5758: #
                   5759: #  
1.34      www      5760: 
                   5761: sub coursedescription {
1.731     albertel 5762:     my ($courseid,$args)=@_;
1.34      www      5763:     $courseid=~s/^\///;
1.49      www      5764:     $courseid=~s/\_/\//g;
1.34      www      5765:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5766:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5767:     my $normalid=$cdomain.'_'.$cnum;
                   5768:     # need to always cache even if we get errors otherwise we keep 
                   5769:     # trying and trying and trying to get the course description.
                   5770:     my %envhash=();
                   5771:     my %returnhash=();
1.731     albertel 5772:     
                   5773:     my $expiretime=600;
                   5774:     if ($env{'request.course.id'} eq $normalid) {
                   5775: 	$expiretime=120;
                   5776:     }
                   5777: 
                   5778:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5779:     if (!$args->{'freshen_cache'}
                   5780: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5781: 	foreach my $key (keys(%env)) {
                   5782: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5783: 	    my ($setting) = $1;
                   5784: 	    $returnhash{$setting} = $env{$key};
                   5785: 	}
                   5786: 	return %returnhash;
                   5787:     }
                   5788: 
1.1118    foxr     5789:     # get the data again
                   5790: 
1.731     albertel 5791:     if (!$args->{'one_time'}) {
                   5792: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5793:     }
1.811     albertel 5794: 
1.34      www      5795:     if ($chome ne 'no_host') {
1.302     albertel 5796:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5797:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5798: 	   my $username = $env{'user.name'}; # Defult username
                   5799: 	   if(defined $args->{'user'}) {
                   5800: 	       $username = $args->{'user'};
                   5801: 	   }
1.129     albertel 5802:            $returnhash{'home'}= $chome;
                   5803: 	   $returnhash{'domain'} = $cdomain;
                   5804: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5805:            if (!defined($returnhash{'type'})) {
                   5806:                $returnhash{'type'} = 'Course';
                   5807:            }
1.130     albertel 5808:            while (my ($name,$value) = each %returnhash) {
1.53      www      5809:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5810:            }
1.270     www      5811:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5812:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5813: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5814:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5815:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5816:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5817:        }
                   5818:     }
1.731     albertel 5819:     if (!$args->{'one_time'}) {
1.949     raeburn  5820: 	&appenv(\%envhash);
1.731     albertel 5821:     }
1.302     albertel 5822:     return %returnhash;
1.461     www      5823: }
                   5824: 
1.1080    raeburn  5825: sub update_released_required {
                   5826:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5827:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5828:         $cid = $env{'request.course.id'};
                   5829:         $cdom = $env{'course.'.$cid.'.domain'};
                   5830:         $cnum = $env{'course.'.$cid.'.num'};
                   5831:         $chome = $env{'course.'.$cid.'.home'};
                   5832:     }
                   5833:     if ($needsrelease) {
                   5834:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5835:         my $needsupdate;
                   5836:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5837:             $needsupdate = 1;
                   5838:         } else {
                   5839:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5840:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5841:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5842:                 $needsupdate = 1;
                   5843:             }
                   5844:         }
                   5845:         if ($needsupdate) {
                   5846:             my %needshash = (
                   5847:                              'internal.releaserequired' => $needsrelease,
                   5848:                             );
                   5849:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5850:             if ($putresult eq 'ok') {
                   5851:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5852:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5853:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5854:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5855:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5856:                 }
                   5857:             }
                   5858:         }
                   5859:     }
                   5860:     return;
                   5861: }
                   5862: 
1.461     www      5863: # -------------------------------------------------See if a user is privileged
                   5864: 
                   5865: sub privileged {
1.1219    raeburn  5866:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5867:     my $now = time;
1.1219    raeburn  5868:     my $roles;
                   5869:     if (ref($possroles) eq 'ARRAY') {
                   5870:         $roles = $possroles; 
                   5871:     } else {
                   5872:         $roles = ['dc','su'];
                   5873:     }
                   5874:     if (ref($possdomains) eq 'ARRAY') {
                   5875:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5876:         foreach my $dom (@{$possdomains}) {
                   5877:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5878:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5879:                 foreach my $role (@{$roles}) {
                   5880:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5881:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5882:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5883:                             return 1 unless (($end && $end < $now) ||
                   5884:                                              ($start && $start > $now));
                   5885:                         }
                   5886:                     }
                   5887:                 }
                   5888:             }
                   5889:         }
                   5890:     } else {
                   5891:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5892:         my $now = time;
1.1170    droeschl 5893: 
1.1275    musolffc 5894:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5895:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5896:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5897:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5898:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5899:             }
1.1219    raeburn  5900:         }
                   5901:     }
                   5902:     return 0;
                   5903: }
1.1170    droeschl 5904: 
1.1219    raeburn  5905: sub privileged_by_domain {
                   5906:     my ($domains,$roles) = @_;
                   5907:     my %privileged = ();
                   5908:     my $cachetime = 60*60*24;
                   5909:     my $now = time;
                   5910:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5911:         return %privileged;
                   5912:     }
                   5913:     foreach my $dom (@{$domains}) {
                   5914:         next if (ref($privileged{$dom}) eq 'HASH');
                   5915:         my $needroles;
                   5916:         foreach my $role (@{$roles}) {
                   5917:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5918:             if (defined($cached)) {
                   5919:                 if (ref($result) eq 'HASH') {
                   5920:                     $privileged{$dom}{$role} = $result;
                   5921:                 }
                   5922:             } else {
                   5923:                 $needroles = 1;
                   5924:             }
                   5925:         }
                   5926:         if ($needroles) {
                   5927:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5928:             $privileged{$dom} = {};
                   5929:             foreach my $server (keys(%dompersonnel)) {
                   5930:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5931:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5932:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5933:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5934:                         next if ($end && $end < $now);
                   5935:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5936:                             $dompersonnel{$server}{$item};
                   5937:                     }
                   5938:                 }
                   5939:             }
                   5940:             if (ref($privileged{$dom}) eq 'HASH') {
                   5941:                 foreach my $role (@{$roles}) {
                   5942:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5943:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5944:                     } else {
                   5945:                         my %hash = ();
                   5946:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5947:                     }
                   5948:                 }
                   5949:             }
                   5950:         }
                   5951:     }
                   5952:     return %privileged;
1.9       www      5953: }
1.1       albertel 5954: 
1.103     harris41 5955: # -------------------------------------------------------- Get user privileges
1.11      www      5956: 
                   5957: sub rolesinit {
1.1169    droeschl 5958:     my ($domain, $username) = @_;
                   5959:     my %userroles = ('user.login.time' => time);
                   5960:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5961: 
                   5962:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5963:     # also, blocking can be triggered by an activating timer
                   5964:     # it's saved in the user's %env.
                   5965:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5966:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5967:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5968:         %timerintchk, %timerintenv);
                   5969: 
1.1162    raeburn  5970:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5971:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5972:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5973:     }
1.1169    droeschl 5974: 
1.1162    raeburn  5975:     foreach my $key (keys(%timerinterval)) {
                   5976:         my ($cid,$rest) = split(/\0/,$key);
                   5977:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5978:     }
1.1169    droeschl 5979: 
1.11      www      5980:     my %allroles=();
1.1162    raeburn  5981:     my %allgroups=();
1.11      www      5982: 
1.1274    raeburn  5983:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5984:         my $role = $rolesdump{$area};
                   5985:         $area =~ s/\_\w\w$//;
                   5986: 
                   5987:         my ($trole, $tend, $tstart, $group_privs);
                   5988: 
                   5989:         if ($role =~ /^cr/) {
                   5990:         # Custom role, defined by a user 
                   5991:         # e.g., user.role.cr/msu/smith/mynewrole
                   5992:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5993:                 $trole = $1;
                   5994:                 ($tend, $tstart) = split('_', $2);
                   5995:             } else {
                   5996:                 $trole = $role;
                   5997:             }
                   5998:         } elsif ($role =~ m|^gr/|) {
                   5999:         # Role of member in a group, defined within a course/community
                   6000:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6001:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6002:             next if $tstart eq '-1';
                   6003:             ($trole, $group_privs) = split(/\//, $trole);
                   6004:             $group_privs = &unescape($group_privs);
                   6005:         } else {
                   6006:         # Just a normal role, defined in roles.tab
                   6007:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6008:         }
                   6009: 
                   6010:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6011:                  $username);
                   6012:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6013: 
                   6014:         # role expired or not available yet?
                   6015:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6016:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6017: 
                   6018:         next if $area eq '' or $trole eq '';
                   6019: 
                   6020:         my $spec = "$trole.$area";
                   6021:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6022: 
                   6023:         if ($trole =~ /^cr\//) {
                   6024:         # Custom role, defined by a user
                   6025:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6026:         } elsif ($trole eq 'gr') {
                   6027:         # Role of a member in a group, defined within a course/community
                   6028:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6029:             next;
                   6030:         } else {
                   6031:         # Normal role, defined in roles.tab
                   6032:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6033:         }
                   6034: 
                   6035:         my $cid = $tdomain.'_'.$trest;
                   6036:         unless ($firstaccchk{$cid}) {
                   6037:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6038:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6039:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6040:                         $coursetimerstarts{$cid}{$item}; 
                   6041:                 }
                   6042:             }
                   6043:             $firstaccchk{$cid} = 1;
                   6044:         }
                   6045:         unless ($timerintchk{$cid}) {
                   6046:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6047:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6048:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6049:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6050:                 }
1.12      www      6051:             }
1.1169    droeschl 6052:             $timerintchk{$cid} = 1;
1.191     harris41 6053:         }
1.11      www      6054:     }
1.1169    droeschl 6055: 
1.1341    raeburn  6056:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6057:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6058:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6059:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6060: 
1.1162    raeburn  6061:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6062: }
                   6063: 
1.567     raeburn  6064: sub set_arearole {
1.1215    raeburn  6065:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6066:     unless ($nolog) {
1.567     raeburn  6067: # log the associated role with the area
1.1215    raeburn  6068:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6069:     }
1.743     albertel 6070:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6071: }
                   6072: 
                   6073: sub custom_roleprivs {
                   6074:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6075:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6076:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6077:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6078:         my ($rdummy,$roledef)=
                   6079:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6080:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6081:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6082:             if (defined($syspriv)) {
1.1043    raeburn  6083:                 if ($trest =~ /^$match_community$/) {
                   6084:                     $syspriv =~ s/bre\&S//; 
                   6085:                 }
1.567     raeburn  6086:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6087:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6088:             }
                   6089:             if ($tdomain ne '') {
                   6090:                 if (defined($dompriv)) {
                   6091:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6092:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6093:                 }
                   6094:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6095:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6096:                         my $rolename = $1;
                   6097:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6098:                     }
1.567     raeburn  6099:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6100:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6101:                 }
                   6102:             }
                   6103:         }
                   6104:     }
                   6105: }
                   6106: 
1.1332    raeburn  6107: sub course_adhocrole_privs {
                   6108:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6109:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6110:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6111:         my (%currprivs,%storeprivs);
                   6112:         foreach my $item (split(/:/,$coursepriv)) {
                   6113:             my ($priv,$restrict) = split(/\&/,$item);
                   6114:             $currprivs{$priv} = $restrict;
                   6115:         }
                   6116:         my (%possadd,%possremove,%full);
                   6117:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6118:             my ($priv,$restrict)=split(/\&/,$item);
                   6119:             $full{$priv} = $restrict;
                   6120:         }
                   6121:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6122:              next if ($item eq '');
                   6123:              my ($rule,$rest) = split(/=/,$item);
                   6124:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6125:              foreach my $priv (split(/:/,$rest)) {
                   6126:                  if ($priv ne '') {
                   6127:                      if ($rule eq 'off') {
                   6128:                          $possremove{$priv} = 1;
                   6129:                      } else {
                   6130:                          $possadd{$priv} = 1;
                   6131:                      }
                   6132:                  }
                   6133:              }
                   6134:          }
                   6135:          foreach my $priv (sort(keys(%full))) {
                   6136:              if (exists($currprivs{$priv})) {
                   6137:                  unless (exists($possremove{$priv})) {
                   6138:                      $storeprivs{$priv} = $currprivs{$priv};
                   6139:                  }
                   6140:              } elsif (exists($possadd{$priv})) {
                   6141:                  $storeprivs{$priv} = $full{$priv};
                   6142:              }
                   6143:          }
                   6144:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6145:      }
                   6146:      return $coursepriv;
                   6147: }
                   6148: 
1.678     raeburn  6149: sub group_roleprivs {
                   6150:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6151:     my $access = 1;
                   6152:     my $now = time;
                   6153:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6154:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6155:     if ($access) {
1.811     albertel 6156:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6157:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6158:     }
                   6159: }
1.567     raeburn  6160: 
                   6161: sub standard_roleprivs {
                   6162:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6163:     if (defined($pr{$trole.':s'})) {
                   6164:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6165:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6166:     }
                   6167:     if ($tdomain ne '') {
                   6168:         if (defined($pr{$trole.':d'})) {
                   6169:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6170:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6171:         }
                   6172:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6173:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6174:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6175:         }
                   6176:     }
                   6177: }
                   6178: 
                   6179: sub set_userprivs {
1.1064    raeburn  6180:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6181:     my $author=0;
                   6182:     my $adv=0;
1.1341    raeburn  6183:     my $rar=0;
1.678     raeburn  6184:     my %grouproles = ();
                   6185:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6186:         my @groupkeys; 
1.1000    raeburn  6187:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6188:             push(@groupkeys,$role);
                   6189:         }
                   6190:         if (ref($groups_roles) eq 'HASH') {
                   6191:             foreach my $key (keys(%{$groups_roles})) {
                   6192:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6193:                     push(@groupkeys,$key);
                   6194:                 }
                   6195:             }
                   6196:         }
                   6197:         if (@groupkeys > 0) {
                   6198:             foreach my $role (@groupkeys) {
                   6199:                 my ($trole,$area,$sec,$extendedarea);
                   6200:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6201:                     $trole = $1;
                   6202:                     $area = $2;
                   6203:                     $sec = $3;
                   6204:                     $extendedarea = $area.$sec;
                   6205:                     if (exists($$allgroups{$area})) {
                   6206:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6207:                             my $spec = $trole.'.'.$extendedarea;
                   6208:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6209:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6210:                         }
1.678     raeburn  6211:                     }
                   6212:                 }
                   6213:             }
                   6214:         }
                   6215:     }
1.800     albertel 6216:     foreach my $group (keys(%grouproles)) {
                   6217:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6218:     }
1.800     albertel 6219:     foreach my $role (keys(%{$allroles})) {
                   6220:         my %thesepriv;
1.941     raeburn  6221:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6222:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6223:             if ($item ne '') {
                   6224:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6225:                 if ($restrictions eq '') {
                   6226:                     $thesepriv{$privilege}='F';
                   6227:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6228:                     $thesepriv{$privilege}.=$restrictions;
                   6229:                 }
                   6230:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6231:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6232:             }
                   6233:         }
                   6234:         my $thesestr='';
1.1104    raeburn  6235:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6236: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6237: 	}
                   6238:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6239:     }
1.1341    raeburn  6240:     return ($author,$adv,$rar);
1.567     raeburn  6241: }
                   6242: 
1.994     raeburn  6243: sub role_status {
1.1104    raeburn  6244:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6245:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6246:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6247:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6248:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6249:             $$where = '/'.$two;
1.994     raeburn  6250:             $$trolecode=$$role.'.'.$$where;
                   6251:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6252:             $$tstatus='is';
1.1104    raeburn  6253:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6254:                 $$tstatus='future';
1.1034    raeburn  6255:                 if ($$tstart<$now) {
                   6256:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6257:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6258:                             my (%allroles,%allgroups,$group_privs,
                   6259:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6260:                             my %userroles = (
                   6261:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6262:                             );
1.1064    raeburn  6263:                             @rolecodes = ('cm'); 
1.1002    raeburn  6264:                             my $spec=$$role.'.'.$$where;
                   6265:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6266:                             if ($$role =~ /^cr\//) {
                   6267:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6268:                                 push(@rolecodes,'cr');
1.1002    raeburn  6269:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6270:                                 push(@rolecodes,$$role);
1.1002    raeburn  6271:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6272:                                                     $env{'user.name'});
1.1064    raeburn  6273:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6274:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6275:                                 $group_privs = &unescape($group_privs);
                   6276:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6277:                                 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  6278:                                 &get_groups_roles($tdomain,$trest,
                   6279:                                                   \%course_roles,\@rolecodes,
                   6280:                                                   \%groups_roles);
1.1002    raeburn  6281:                             } else {
1.1064    raeburn  6282:                                 push(@rolecodes,$$role);
1.1002    raeburn  6283:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6284:                             }
1.1341    raeburn  6285:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6286:                                                                    \%groups_roles);
1.1064    raeburn  6287:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6288:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6289:                         }
                   6290:                     }
1.1034    raeburn  6291:                     $$tstatus = 'is';
1.1002    raeburn  6292:                 }
1.994     raeburn  6293:             }
                   6294:             if ($$tend) {
1.1104    raeburn  6295:                 if ($$tend<$update) {
1.994     raeburn  6296:                     $$tstatus='expired';
                   6297:                 } elsif ($$tend<$now) {
                   6298:                     $$tstatus='will_not';
                   6299:                 }
                   6300:             }
                   6301:         }
                   6302:     }
                   6303: }
                   6304: 
1.1104    raeburn  6305: sub get_groups_roles {
                   6306:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6307:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6308:                   (ref($rolecodes) eq 'ARRAY') && 
                   6309:                   (ref($groups_roles) eq 'HASH')); 
                   6310:     if (keys(%{$cdom_courseroles}) > 0) {
                   6311:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6312:         if ($cdom ne '' && $cnum ne '') {
                   6313:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6314:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6315:                     my $crsrole = $1;
                   6316:                     my $crssec = $2;
                   6317:                     if ($crsrole =~ /^cr/) {
                   6318:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6319:                             push(@{$rolecodes},'cr');
                   6320:                         }
                   6321:                     } else {
                   6322:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6323:                             push(@{$rolecodes},$crsrole);
                   6324:                         }
                   6325:                     }
                   6326:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6327:                     if ($crssec ne '') {
                   6328:                         $rolekey .= "/$crssec";
                   6329:                     }
                   6330:                     $rolekey .= './';
                   6331:                     $groups_roles->{$rolekey} = $rolecodes;
                   6332:                 }
                   6333:             }
                   6334:         }
                   6335:     }
                   6336:     return;
                   6337: }
                   6338: 
                   6339: sub delete_env_groupprivs {
                   6340:     my ($where,$courseroles,$possroles) = @_;
                   6341:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6342:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6343:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6344:         %{$courseroles->{$udom}} =
                   6345:             &get_my_roles('','','userroles',['active'],
                   6346:                           $possroles,[$udom],1);
                   6347:     }
                   6348:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6349:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6350:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6351:             my $area = '/'.$cdom.'/'.$cnum;
                   6352:             my $privkey = "user.priv.$crsrole.$area";
                   6353:             if ($crssec ne '') {
                   6354:                 $privkey .= '/'.$crssec;
                   6355:             }
                   6356:             $privkey .= ".$area/$group";
                   6357:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6358:         }
                   6359:     }
                   6360:     return;
                   6361: }
                   6362: 
1.994     raeburn  6363: sub check_adhoc_privs {
1.1329    raeburn  6364:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6365:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6366:     if ($sec) {
                   6367:         $cckey .= '/'.$sec;
                   6368:     } 
1.1185    raeburn  6369:     my $setprivs;
1.994     raeburn  6370:     if ($env{$cckey}) {
                   6371:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6372:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6373:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6374:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6375:             $setprivs = 1;
1.994     raeburn  6376:         }
                   6377:     } else {
1.1330    raeburn  6378:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6379:         $setprivs = 1;
1.994     raeburn  6380:     }
1.1185    raeburn  6381:     return $setprivs;
1.994     raeburn  6382: }
                   6383: 
                   6384: sub set_adhoc_privileges {
1.1326    raeburn  6385: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6386:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6387:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6388:     if ($sec ne '') {
                   6389:         $area .= '/'.$sec;
                   6390:     }
1.994     raeburn  6391:     my $spec = $role.'.'.$area;
                   6392:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6393:                                   $env{'user.name'},1);
1.1326    raeburn  6394:     my %rolehash = ();
1.1332    raeburn  6395:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6396:         my $rolename = $1;
1.1326    raeburn  6397:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6398:         my %domdef = &get_domain_defaults($dcdom);
                   6399:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6400:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6401:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6402:             }
                   6403:         }
1.1326    raeburn  6404:     } else {
                   6405:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6406:     }
1.1341    raeburn  6407:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6408:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6409:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6410:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6411:         &appenv( {'request.role'        => $spec,
                   6412:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6413:                   'request.course.sec'  => $sec,
1.1088    raeburn  6414:                  }
                   6415:                );
                   6416:         my $tadv=0;
                   6417:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6418:         &appenv({'request.role.adv'    => $tadv});
                   6419:     }
1.994     raeburn  6420: }
                   6421: 
1.12      www      6422: # --------------------------------------------------------------- get interface
                   6423: 
                   6424: sub get {
1.131     albertel 6425:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6426:    my $items='';
1.800     albertel 6427:    foreach my $item (@$storearr) {
                   6428:        $items.=&escape($item).'&';
1.191     harris41 6429:    }
1.12      www      6430:    $items=~s/\&$//;
1.620     albertel 6431:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6432:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6433:    my $uhome=&homeserver($uname,$udomain);
                   6434: 
1.133     albertel 6435:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6436:    my @pairs=split(/\&/,$rep);
1.273     albertel 6437:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6438:      return @pairs;
                   6439:    }
1.15      www      6440:    my %returnhash=();
1.42      www      6441:    my $i=0;
1.800     albertel 6442:    foreach my $item (@$storearr) {
                   6443:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6444:       $i++;
1.191     harris41 6445:    }
1.15      www      6446:    return %returnhash;
1.27      www      6447: }
                   6448: 
                   6449: # --------------------------------------------------------------- del interface
                   6450: 
                   6451: sub del {
1.133     albertel 6452:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6453:    my $items='';
1.800     albertel 6454:    foreach my $item (@$storearr) {
                   6455:        $items.=&escape($item).'&';
1.191     harris41 6456:    }
1.984     neumanie 6457: 
1.27      www      6458:    $items=~s/\&$//;
1.620     albertel 6459:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6460:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6461:    my $uhome=&homeserver($uname,$udomain);
                   6462:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6463: }
                   6464: 
                   6465: # -------------------------------------------------------------- dump interface
                   6466: 
1.1180    droeschl 6467: sub unserialize {
                   6468:     my ($rep, $escapedkeys) = @_;
                   6469: 
                   6470:     return {} if $rep =~ /^error/;
                   6471: 
                   6472:     my %returnhash=();
1.1252    raeburn  6473: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6474: 	    my ($key, $value) = split(/=/, $item, 2);
                   6475: 	    $key = unescape($key) unless $escapedkeys;
                   6476: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6477: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6478: 	}
                   6479:     #return %returnhash;
                   6480:     return \%returnhash;
                   6481: }        
                   6482: 
                   6483: # see Lond::dump_with_regexp
                   6484: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6485: sub dump {
1.1180    droeschl 6486:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6487:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6488:     if (!$uname) { $uname=$env{'user.name'}; }
                   6489:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6490: 
1.1266    raeburn  6491:     if ($regexp) {
                   6492:         $regexp=&escape($regexp);
                   6493:     } else {
                   6494:         $regexp='.';
                   6495:     }
1.1180    droeschl 6496:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6497:         # user is hosted on this machine
1.1266    raeburn  6498:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6499:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6500:         return %{unserialize($reply, $escapedkeys)};
                   6501:     }
1.1166    raeburn  6502:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6503:     my @pairs=split(/\&/,$rep);
                   6504:     my %returnhash=();
1.1098    foxr     6505:     if (!($rep =~ /^error/ )) {
                   6506: 	foreach my $item (@pairs) {
                   6507: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6508:         $key = unescape($key) unless $escapedkeys;
                   6509:         #$key = &unescape($key);
1.1098    foxr     6510: 	    next if ($key =~ /^error: 2 /);
                   6511: 	    $returnhash{$key}=&thaw_unescape($value);
                   6512: 	}
1.755     albertel 6513:     }
                   6514:     return %returnhash;
1.407     www      6515: }
                   6516: 
1.1098    foxr     6517: 
1.717     albertel 6518: # --------------------------------------------------------- dumpstore interface
                   6519: 
                   6520: sub dumpstore {
                   6521:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6522:    # same as dump but keys must be escaped. They may contain colon separated
                   6523:    # lists of values that may themself contain colons (e.g. symbs).
                   6524:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6525: }
                   6526: 
1.407     www      6527: # -------------------------------------------------------------- keys interface
                   6528: 
                   6529: sub getkeys {
                   6530:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6531:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6532:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6533:    my $uhome=&homeserver($uname,$udomain);
                   6534:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6535:    my @keyarray=();
1.800     albertel 6536:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6537:       next if ($key =~ /^error: 2 /);
1.800     albertel 6538:       push(@keyarray,&unescape($key));
1.407     www      6539:    }
                   6540:    return @keyarray;
1.318     matthew  6541: }
                   6542: 
1.319     matthew  6543: # --------------------------------------------------------------- currentdump
                   6544: sub currentdump {
1.328     matthew  6545:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6546:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6547:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6548:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6549:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6550:    my $rep;
                   6551: 
                   6552:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6553:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6554:                    $courseid)));
                   6555:    } else {
                   6556:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6557:    }
                   6558: 
1.318     matthew  6559:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6560:    #
1.318     matthew  6561:    my %returnhash=();
1.319     matthew  6562:    #
1.1343    raeburn  6563:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6564:        # an old lond will not know currentdump
                   6565:        # Do a dump and make it look like a currentdump
1.822     albertel 6566:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6567:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6568:        my %hash = @tmp;
                   6569:        @tmp=();
1.424     matthew  6570:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6571:    } else {
                   6572:        my @pairs=split(/\&/,$rep);
1.800     albertel 6573:        foreach my $pair (@pairs) {
                   6574:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6575:            my ($symb,$param) = split(/:/,$key);
                   6576:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6577:                                                         &thaw_unescape($value);
1.319     matthew  6578:        }
1.191     harris41 6579:    }
1.12      www      6580:    return %returnhash;
1.424     matthew  6581: }
                   6582: 
                   6583: sub convert_dump_to_currentdump{
                   6584:     my %hash = %{shift()};
                   6585:     my %returnhash;
                   6586:     # Code ripped from lond, essentially.  The only difference
                   6587:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6588:     # we might run in to problems with parameter names =~ /^v\./
                   6589:     while (my ($key,$value) = each(%hash)) {
                   6590:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6591: 	$symb  = &unescape($symb);
                   6592: 	$param = &unescape($param);
1.424     matthew  6593:         next if ($v eq 'version' || $symb eq 'keys');
                   6594:         next if (exists($returnhash{$symb}) &&
                   6595:                  exists($returnhash{$symb}->{$param}) &&
                   6596:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6597:         $returnhash{$symb}->{$param}=$value;
                   6598:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6599:     }
                   6600:     #
                   6601:     # Remove all of the keys in the hashes which keep track of
                   6602:     # the version of the parameter.
                   6603:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6604:         # use a foreach because we are going to delete from the hash.
                   6605:         foreach my $key (keys(%$param_hash)) {
                   6606:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6607:         }
                   6608:     }
                   6609:     return \%returnhash;
1.12      www      6610: }
                   6611: 
1.627     albertel 6612: # ------------------------------------------------------ critical inc interface
                   6613: 
                   6614: sub cinc {
                   6615:     return &inc(@_,'critical');
                   6616: }
                   6617: 
1.449     matthew  6618: # --------------------------------------------------------------- inc interface
                   6619: 
                   6620: sub inc {
1.627     albertel 6621:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6622:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6623:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6624:     my $uhome=&homeserver($uname,$udomain);
                   6625:     my $items='';
                   6626:     if (! ref($store)) {
                   6627:         # got a single value, so use that instead
                   6628:         $items = &escape($store).'=&';
                   6629:     } elsif (ref($store) eq 'SCALAR') {
                   6630:         $items = &escape($$store).'=&';        
                   6631:     } elsif (ref($store) eq 'ARRAY') {
                   6632:         $items = join('=&',map {&escape($_);} @{$store});
                   6633:     } elsif (ref($store) eq 'HASH') {
                   6634:         while (my($key,$value) = each(%{$store})) {
                   6635:             $items.= &escape($key).'='.&escape($value).'&';
                   6636:         }
                   6637:     }
                   6638:     $items=~s/\&$//;
1.627     albertel 6639:     if ($critical) {
                   6640: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6641:     } else {
                   6642: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6643:     }
1.449     matthew  6644: }
                   6645: 
1.12      www      6646: # --------------------------------------------------------------- put interface
                   6647: 
                   6648: sub put {
1.134     albertel 6649:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6650:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6651:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6652:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6653:    my $items='';
1.800     albertel 6654:    foreach my $item (keys(%$storehash)) {
                   6655:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6656:    }
1.12      www      6657:    $items=~s/\&$//;
1.134     albertel 6658:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6659: }
                   6660: 
1.631     albertel 6661: # ------------------------------------------------------------ newput interface
                   6662: 
                   6663: sub newput {
                   6664:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6665:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6666:    if (!$uname) { $uname=$env{'user.name'}; }
                   6667:    my $uhome=&homeserver($uname,$udomain);
                   6668:    my $items='';
                   6669:    foreach my $key (keys(%$storehash)) {
                   6670:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6671:    }
                   6672:    $items=~s/\&$//;
                   6673:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6674: }
                   6675: 
                   6676: # ---------------------------------------------------------  putstore interface
                   6677: 
1.524     raeburn  6678: sub putstore {
1.1269    raeburn  6679:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6680:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6681:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6682:    my $uhome=&homeserver($uname,$udomain);
                   6683:    my $items='';
1.715     albertel 6684:    foreach my $key (keys(%$storehash)) {
                   6685:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6686:    }
1.715     albertel 6687:    $items=~s/\&$//;
1.716     albertel 6688:    my $esc_symb=&escape($symb);
                   6689:    my $esc_v=&escape($version);
1.715     albertel 6690:    my $reply =
1.716     albertel 6691:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6692: 	      $uhome);
1.1269    raeburn  6693:    if (($tolog) && ($reply eq 'ok')) {
                   6694:        my $namevalue='';
                   6695:        foreach my $key (keys(%{$storehash})) {
                   6696:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6697:        }
                   6698:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6699:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6700:                      '&version='.$esc_v.
                   6701:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6702:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6703:    }
1.715     albertel 6704:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6705:        # gfall back to way things use to be done
1.715     albertel 6706:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6707: 			    $uname);
1.524     raeburn  6708:    }
1.715     albertel 6709:    return $reply;
                   6710: }
                   6711: 
                   6712: sub old_putstore {
1.716     albertel 6713:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6714:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6715:     if (!$uname) { $uname=$env{'user.name'}; }
                   6716:     my $uhome=&homeserver($uname,$udomain);
                   6717:     my %newstorehash;
1.800     albertel 6718:     foreach my $item (keys(%$storehash)) {
                   6719: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6720: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6721:     }
                   6722:     my $items='';
                   6723:     my %allitems = ();
1.800     albertel 6724:     foreach my $item (keys(%newstorehash)) {
                   6725: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6726: 	    my $key = $1.':keys:'.$2;
                   6727: 	    $allitems{$key} .= $3.':';
                   6728: 	}
1.800     albertel 6729: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6730:     }
1.800     albertel 6731:     foreach my $item (keys(%allitems)) {
                   6732: 	$allitems{$item} =~ s/\:$//;
                   6733: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6734:     }
                   6735:     $items=~s/\&$//;
                   6736:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6737: }
                   6738: 
1.47      www      6739: # ------------------------------------------------------ critical put interface
                   6740: 
                   6741: sub cput {
1.134     albertel 6742:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6743:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6744:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6745:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6746:    my $items='';
1.800     albertel 6747:    foreach my $item (keys(%$storehash)) {
                   6748:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6749:    }
1.47      www      6750:    $items=~s/\&$//;
1.134     albertel 6751:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6752: }
                   6753: 
                   6754: # -------------------------------------------------------------- eget interface
                   6755: 
                   6756: sub eget {
1.133     albertel 6757:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6758:    my $items='';
1.800     albertel 6759:    foreach my $item (@$storearr) {
                   6760:        $items.=&escape($item).'&';
1.191     harris41 6761:    }
1.12      www      6762:    $items=~s/\&$//;
1.620     albertel 6763:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6764:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6765:    my $uhome=&homeserver($uname,$udomain);
                   6766:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6767:    my @pairs=split(/\&/,$rep);
                   6768:    my %returnhash=();
1.42      www      6769:    my $i=0;
1.800     albertel 6770:    foreach my $item (@$storearr) {
                   6771:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6772:       $i++;
1.191     harris41 6773:    }
1.12      www      6774:    return %returnhash;
                   6775: }
                   6776: 
1.667     albertel 6777: # ------------------------------------------------------------ tmpput interface
                   6778: sub tmpput {
1.802     raeburn  6779:     my ($storehash,$server,$context)=@_;
1.667     albertel 6780:     my $items='';
1.800     albertel 6781:     foreach my $item (keys(%$storehash)) {
                   6782: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6783:     }
                   6784:     $items=~s/\&$//;
1.802     raeburn  6785:     if (defined($context)) {
                   6786:         $items .= ':'.&escape($context);
                   6787:     }
1.667     albertel 6788:     return &reply("tmpput:$items",$server);
                   6789: }
                   6790: 
                   6791: # ------------------------------------------------------------ tmpget interface
                   6792: sub tmpget {
1.688     albertel 6793:     my ($token,$server)=@_;
                   6794:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6795:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6796:     my %returnhash;
1.1328    raeburn  6797:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6798:         return %returnhash;
                   6799:     }
1.667     albertel 6800:     foreach my $item (split(/\&/,$rep)) {
                   6801: 	my ($key,$value)=split(/=/,$item);
                   6802: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6803:     }
                   6804:     return %returnhash;
                   6805: }
                   6806: 
1.1113    raeburn  6807: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6808: sub tmpdel {
                   6809:     my ($token,$server)=@_;
                   6810:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6811:     return &reply("tmpdel:$token",$server);
                   6812: }
                   6813: 
1.1198    raeburn  6814: # ------------------------------------------------------------ get_timebased_id 
                   6815: 
                   6816: sub get_timebased_id {
                   6817:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6818:         $maxtries) = @_;
                   6819:     my ($newid,$error,$dellock);
                   6820:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6821:         return ('','ok','invalid call to get suffix');
                   6822:     }
                   6823: 
                   6824: # set defaults for any optional args for which values were not supplied
                   6825:     if ($who eq '') {
                   6826:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6827:     }
                   6828:     if (!$locktries) {
                   6829:         $locktries = 3;
                   6830:     }
                   6831:     if (!$maxtries) {
                   6832:         $maxtries = 10;
                   6833:     }
                   6834:     
                   6835:     if (($cdom eq '') || ($cnum eq '')) {
                   6836:         if ($env{'request.course.id'}) {
                   6837:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6838:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6839:         }
                   6840:         if (($cdom eq '') || ($cnum eq '')) {
                   6841:             return ('','ok','call to get suffix not in course context');
                   6842:         }
                   6843:     }
                   6844: 
                   6845: # construct locking item
                   6846:     my $lockhash = {
                   6847:                       $prefix."\0".'locked_'.$keyid => $who,
                   6848:                    };
                   6849:     my $tries = 0;
                   6850: 
                   6851: # attempt to get lock on nohist_$namespace file
                   6852:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6853:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6854:         $tries ++;
                   6855:         sleep 1;
                   6856:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6857:     }
                   6858: 
                   6859: # attempt to get unique identifier, based on current timestamp
                   6860:     if ($gotlock eq 'ok') {
                   6861:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6862:         my $id = time;
                   6863:         $newid = $id;
1.1268    raeburn  6864:         if ($idtype eq 'addcode') {
                   6865:             $newid .= &sixnum_code();
                   6866:         }
1.1198    raeburn  6867:         my $idtries = 0;
                   6868:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6869:             if ($idtype eq 'concat') {
                   6870:                 $newid = $id.$idtries;
1.1268    raeburn  6871:             } elsif ($idtype eq 'addcode') {
                   6872:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6873:             } else {
                   6874:                 $newid ++;
                   6875:             }
                   6876:             $idtries ++;
                   6877:         }
                   6878:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6879:             my %new_item =  (
                   6880:                               $prefix."\0".$newid => $who,
                   6881:                             );
                   6882:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6883:                                                  $cdom,$cnum);
                   6884:             if ($putresult ne 'ok') {
                   6885:                 undef($newid);
                   6886:                 $error = 'error saving new item: '.$putresult;
                   6887:             }
                   6888:         } else {
1.1268    raeburn  6889:              undef($newid);
1.1198    raeburn  6890:              $error = ('error: no unique suffix available for the new item ');
                   6891:         }
                   6892: #  remove lock
                   6893:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6894:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6895:     } else {
                   6896:         $error = "error: could not obtain lockfile\n";
                   6897:         $dellock = 'ok';
1.1276    raeburn  6898:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6899:             $dellock = 'nolock';
                   6900:         }
1.1198    raeburn  6901:     }
                   6902:     return ($newid,$dellock,$error);
                   6903: }
                   6904: 
1.1268    raeburn  6905: sub sixnum_code {
                   6906:     my $code;
                   6907:     for (0..6) {
                   6908:         $code .= int( rand(9) );
                   6909:     }
                   6910:     return $code;
                   6911: }
                   6912: 
1.765     albertel 6913: # -------------------------------------------------- portfolio access checking
                   6914: 
                   6915: sub portfolio_access {
1.1270    raeburn  6916:     my ($requrl,$clientip) = @_;
1.765     albertel 6917:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6918:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6919:     if ($result) {
                   6920:         my %setters;
                   6921:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6922:             my ($startblock,$endblock) =
                   6923:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6924:             if ($startblock && $endblock) {
                   6925:                 return 'B';
                   6926:             }
                   6927:         } else {
                   6928:             my ($startblock,$endblock) =
                   6929:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6930:             if ($startblock && $endblock) {
                   6931:                 return 'B';
                   6932:             }
                   6933:         }
                   6934:     }
1.765     albertel 6935:     if ($result eq 'ok') {
1.766     albertel 6936:        return 'F';
1.765     albertel 6937:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6938:        return 'A';
1.765     albertel 6939:     }
1.766     albertel 6940:     return '';
1.765     albertel 6941: }
                   6942: 
                   6943: sub get_portfolio_access {
1.1270    raeburn  6944:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6945: 
                   6946:     if (!ref($access_hash)) {
                   6947: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6948: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6949: 						   $file_name);
                   6950: 	$access_hash = $access_controls{$file_name};
                   6951:     }
                   6952: 
1.1270    raeburn  6953:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6954:     my $now = time;
                   6955:     if (ref($access_hash) eq 'HASH') {
                   6956:         foreach my $key (keys(%{$access_hash})) {
                   6957:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6958:             if ($start > $now) {
                   6959:                 next;
                   6960:             }
                   6961:             if ($end && $end<$now) {
                   6962:                 next;
                   6963:             }
                   6964:             if ($scope eq 'public') {
                   6965:                 $public = $key;
                   6966:                 last;
                   6967:             } elsif ($scope eq 'guest') {
                   6968:                 $guest = $key;
                   6969:             } elsif ($scope eq 'domains') {
                   6970:                 push(@domains,$key);
                   6971:             } elsif ($scope eq 'users') {
                   6972:                 push(@users,$key);
                   6973:             } elsif ($scope eq 'course') {
                   6974:                 push(@courses,$key);
                   6975:             } elsif ($scope eq 'group') {
                   6976:                 push(@groups,$key);
1.1270    raeburn  6977:             } elsif ($scope eq 'ip') {
                   6978:                 push(@ips,$key);
1.765     albertel 6979:             }
                   6980:         }
                   6981:         if ($public) {
                   6982:             return 'ok';
1.1270    raeburn  6983:         } elsif (@ips > 0) {
                   6984:             my $allowed;
                   6985:             foreach my $ipkey (@ips) {
                   6986:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6987:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6988:                         $allowed = 1;
                   6989:                         last; 
                   6990:                     }
                   6991:                 }
                   6992:             }
                   6993:             if ($allowed) {
                   6994:                 return 'ok';
                   6995:             }
1.765     albertel 6996:         }
                   6997:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6998:             if ($guest) {
                   6999:                 return $guest;
                   7000:             }
                   7001:         } else {
                   7002:             if (@domains > 0) {
                   7003:                 foreach my $domkey (@domains) {
                   7004:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7005:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7006:                             return 'ok';
                   7007:                         }
                   7008:                     }
                   7009:                 }
                   7010:             }
                   7011:             if (@users > 0) {
                   7012:                 foreach my $userkey (@users) {
1.865     raeburn  7013:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7014:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7015:                             if (ref($item) eq 'HASH') {
                   7016:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7017:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7018:                                     return 'ok';
                   7019:                                 }
                   7020:                             }
                   7021:                         }
                   7022:                     } 
1.765     albertel 7023:                 }
                   7024:             }
                   7025:             my %roleshash;
                   7026:             my @courses_and_groups = @courses;
                   7027:             push(@courses_and_groups,@groups); 
                   7028:             if (@courses_and_groups > 0) {
                   7029:                 my (%allgroups,%allroles); 
                   7030:                 my ($start,$end,$role,$sec,$group);
                   7031:                 foreach my $envkey (%env) {
1.1060    raeburn  7032:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7033:                         my $cid = $2.'_'.$3; 
                   7034:                         if ($1 eq 'gr') {
                   7035:                             $group = $4;
                   7036:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7037:                         } else {
                   7038:                             if ($4 eq '') {
                   7039:                                 $sec = 'none';
                   7040:                             } else {
                   7041:                                 $sec = $4;
                   7042:                             }
                   7043:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7044:                         }
1.811     albertel 7045:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7046:                         my $cid = $2.'_'.$3;
                   7047:                         if ($4 eq '') {
                   7048:                             $sec = 'none';
                   7049:                         } else {
                   7050:                             $sec = $4;
                   7051:                         }
                   7052:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7053:                     }
                   7054:                 }
                   7055:                 if (keys(%allroles) == 0) {
                   7056:                     return;
                   7057:                 }
                   7058:                 foreach my $key (@courses_and_groups) {
                   7059:                     my %content = %{$$access_hash{$key}};
                   7060:                     my $cnum = $content{'number'};
                   7061:                     my $cdom = $content{'domain'};
                   7062:                     my $cid = $cdom.'_'.$cnum;
                   7063:                     if (!exists($allroles{$cid})) {
                   7064:                         next;
                   7065:                     }    
                   7066:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7067:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7068:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7069:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7070:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7071:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7072:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7073:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7074:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7075:                                         if (grep/^all$/,@sections) {
                   7076:                                             return 'ok';
                   7077:                                         } else {
                   7078:                                             if (grep/^$sec$/,@sections) {
                   7079:                                                 return 'ok';
                   7080:                                             }
                   7081:                                         }
                   7082:                                     }
                   7083:                                 }
                   7084:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7085:                                     if (grep/^none$/,@groups) {
                   7086:                                         return 'ok';
                   7087:                                     }
                   7088:                                 } else {
                   7089:                                     if (grep/^all$/,@groups) {
                   7090:                                         return 'ok';
                   7091:                                     } 
                   7092:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7093:                                         if (grep/^$group$/,@groups) {
                   7094:                                             return 'ok';
                   7095:                                         }
                   7096:                                     }
                   7097:                                 } 
                   7098:                             }
                   7099:                         }
                   7100:                     }
                   7101:                 }
                   7102:             }
                   7103:             if ($guest) {
                   7104:                 return $guest;
                   7105:             }
                   7106:         }
                   7107:     }
                   7108:     return;
                   7109: }
                   7110: 
                   7111: sub course_group_datechecker {
                   7112:     my ($dates,$now,$status) = @_;
                   7113:     my ($start,$end) = split(/\./,$dates);
                   7114:     if (!$start && !$end) {
                   7115:         return 'ok';
                   7116:     }
                   7117:     if (grep/^active$/,@{$status}) {
                   7118:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7119:             return 'ok';
                   7120:         }
                   7121:     }
                   7122:     if (grep/^previous$/,@{$status}) {
                   7123:         if ($end > $now ) {
                   7124:             return 'ok';
                   7125:         }
                   7126:     }
                   7127:     if (grep/^future$/,@{$status}) {
                   7128:         if ($start > $now) {
                   7129:             return 'ok';
                   7130:         }
                   7131:     }
                   7132:     return; 
                   7133: }
                   7134: 
                   7135: sub parse_portfolio_url {
                   7136:     my ($url) = @_;
                   7137: 
                   7138:     my ($type,$udom,$unum,$group,$file_name);
                   7139:     
1.823     albertel 7140:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7141: 	$type = 1;
                   7142:         $udom = $1;
                   7143:         $unum = $2;
                   7144:         $file_name = $3;
1.823     albertel 7145:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7146: 	$type = 2;
                   7147:         $udom = $1;
                   7148:         $unum = $2;
                   7149:         $group = $3;
                   7150:         $file_name = $3.'/'.$4;
                   7151:     }
                   7152:     if (wantarray) {
                   7153: 	return ($type,$udom,$unum,$file_name,$group);
                   7154:     }
                   7155:     return $type;
                   7156: }
                   7157: 
                   7158: sub is_portfolio_url {
                   7159:     my ($url) = @_;
                   7160:     return scalar(&parse_portfolio_url($url));
                   7161: }
                   7162: 
1.798     raeburn  7163: sub is_portfolio_file {
                   7164:     my ($file) = @_;
1.820     raeburn  7165:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7166:         return 1;
                   7167:     }
                   7168:     return;
                   7169: }
                   7170: 
1.976     raeburn  7171: sub usertools_access {
1.1084    raeburn  7172:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7173:     my ($access,%tools);
                   7174:     if ($context eq '') {
                   7175:         $context = 'tools';
                   7176:     }
                   7177:     if ($context eq 'requestcourses') {
                   7178:         %tools = (
                   7179:                       official   => 1,
                   7180:                       unofficial => 1,
1.1006    raeburn  7181:                       community  => 1,
1.1246    raeburn  7182:                       textbook   => 1,
1.1305    raeburn  7183:                       placement  => 1,
1.1368    raeburn  7184:                       lti        => 1,
1.985     raeburn  7185:                  );
1.1183    raeburn  7186:     } elsif ($context eq 'requestauthor') {
                   7187:         %tools = (
                   7188:                       requestauthor => 1,
                   7189:                  );
1.985     raeburn  7190:     } else {
                   7191:         %tools = (
                   7192:                       aboutme   => 1,
                   7193:                       blog      => 1,
1.1177    raeburn  7194:                       webdav    => 1,
1.985     raeburn  7195:                       portfolio => 1,
                   7196:                  );
                   7197:     }
1.976     raeburn  7198:     return if (!defined($tools{$tool}));
                   7199: 
1.1242    raeburn  7200:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7201:         $udom = $env{'user.domain'};
                   7202:         $uname = $env{'user.name'};
                   7203:     }
                   7204: 
1.978     raeburn  7205:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7206:         if ($action ne 'reload') {
1.985     raeburn  7207:             if ($context eq 'requestcourses') {
                   7208:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7209:             } elsif ($context eq 'requestauthor') {
                   7210:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7211:             } else {
                   7212:                 return $env{'environment.availabletools.'.$tool};
                   7213:             }
                   7214:         }
1.976     raeburn  7215:     }
                   7216: 
1.1183    raeburn  7217:     my ($toolstatus,$inststatus,$envkey);
                   7218:     if ($context eq 'requestauthor') {
                   7219:         $envkey = $context; 
                   7220:     } else {
                   7221:         $envkey = $context.'.'.$tool;
                   7222:     }
1.976     raeburn  7223: 
1.985     raeburn  7224:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7225:          ($action ne 'reload')) {
1.1183    raeburn  7226:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7227:         $inststatus = $env{'environment.inststatus'};
                   7228:     } else {
1.1084    raeburn  7229:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7230:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7231:             $inststatus = $userenvref->{'inststatus'};
                   7232:         } else {
1.1183    raeburn  7233:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7234:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7235:             $inststatus = $userenv{'inststatus'};
                   7236:         }
1.976     raeburn  7237:     }
                   7238: 
                   7239:     if ($toolstatus ne '') {
                   7240:         if ($toolstatus) {
                   7241:             $access = 1;
                   7242:         } else {
                   7243:             $access = 0;
                   7244:         }
                   7245:         return $access;
                   7246:     }
                   7247: 
1.1084    raeburn  7248:     my ($is_adv,%domdef);
                   7249:     if (ref($is_advref) eq 'HASH') {
                   7250:         $is_adv = $is_advref->{'is_adv'};
                   7251:     } else {
                   7252:         $is_adv = &is_advanced_user($udom,$uname);
                   7253:     }
                   7254:     if (ref($domdefref) eq 'HASH') {
                   7255:         %domdef = %{$domdefref};
                   7256:     } else {
                   7257:         %domdef = &get_domain_defaults($udom);
                   7258:     }
1.976     raeburn  7259:     if (ref($domdef{$tool}) eq 'HASH') {
                   7260:         if ($is_adv) {
                   7261:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7262:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7263:                     $access = 1;
                   7264:                 } else {
                   7265:                     $access = 0;
                   7266:                 }
                   7267:                 return $access;
                   7268:             }
                   7269:         }
                   7270:         if ($inststatus ne '') {
                   7271:             my ($hasaccess,$hasnoaccess);
                   7272:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7273:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7274:                     if ($domdef{$tool}{$affiliation}) {
                   7275:                         $hasaccess = 1;
                   7276:                     } else {
                   7277:                         $hasnoaccess = 1;
                   7278:                     }
                   7279:                 }
                   7280:             }
                   7281:             if ($hasaccess || $hasnoaccess) {
                   7282:                 if ($hasaccess) {
                   7283:                     $access = 1;
                   7284:                 } elsif ($hasnoaccess) {
                   7285:                     $access = 0; 
                   7286:                 }
                   7287:                 return $access;
                   7288:             }
                   7289:         } else {
                   7290:             if ($domdef{$tool}{'default'} ne '') {
                   7291:                 if ($domdef{$tool}{'default'}) {
                   7292:                     $access = 1;
                   7293:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7294:                     $access = 0;
                   7295:                 }
                   7296:                 return $access;
                   7297:             }
                   7298:         }
                   7299:     } else {
1.1177    raeburn  7300:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7301:             $access = 1;
                   7302:         } else {
                   7303:             $access = 0;
                   7304:         }
1.976     raeburn  7305:         return $access;
                   7306:     }
                   7307: }
                   7308: 
1.1050    raeburn  7309: sub is_course_owner {
                   7310:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7311:     if (($udom eq '') || ($uname eq '')) {
                   7312:         $udom = $env{'user.domain'};
                   7313:         $uname = $env{'user.name'};
                   7314:     }
                   7315:     unless (($udom eq '') || ($uname eq '')) {
                   7316:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7317:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7318:                 return 1;
                   7319:             } else {
                   7320:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7321:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7322:                     return 1;
                   7323:                 }
                   7324:             }
                   7325:         }
                   7326:     }
                   7327:     return;
                   7328: }
                   7329: 
1.976     raeburn  7330: sub is_advanced_user {
                   7331:     my ($udom,$uname) = @_;
1.1085    raeburn  7332:     if ($udom ne '' && $uname ne '') {
                   7333:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7334:             if (wantarray) {
                   7335:                 return ($env{'user.adv'},$env{'user.author'});
                   7336:             } else {
                   7337:                 return $env{'user.adv'};
                   7338:             }
1.1085    raeburn  7339:         }
                   7340:     }
1.976     raeburn  7341:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7342:     my %allroles;
1.1128    raeburn  7343:     my ($is_adv,$is_author);
1.976     raeburn  7344:     foreach my $role (keys(%roleshash)) {
                   7345:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7346:         my $area = '/'.$tdomain.'/'.$trest;
                   7347:         if ($sec ne '') {
                   7348:             $area .= '/'.$sec;
                   7349:         }
                   7350:         if (($area ne '') && ($trole ne '')) {
                   7351:             my $spec=$trole.'.'.$area;
                   7352:             if ($trole =~ /^cr\//) {
                   7353:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7354:             } elsif ($trole ne 'gr') {
                   7355:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7356:             }
1.1128    raeburn  7357:             if ($trole eq 'au') {
                   7358:                 $is_author = 1;
                   7359:             }
1.976     raeburn  7360:         }
                   7361:     }
                   7362:     foreach my $role (keys(%allroles)) {
                   7363:         last if ($is_adv);
                   7364:         foreach my $item (split(/:/,$allroles{$role})) {
                   7365:             if ($item ne '') {
                   7366:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7367:                 if ($privilege eq 'adv') {
                   7368:                     $is_adv = 1;
                   7369:                     last;
                   7370:                 }
                   7371:             }
                   7372:         }
                   7373:     }
1.1128    raeburn  7374:     if (wantarray) {
                   7375:         return ($is_adv,$is_author);
                   7376:     }
1.976     raeburn  7377:     return $is_adv;
                   7378: }
1.798     raeburn  7379: 
1.1035    raeburn  7380: sub check_can_request {
1.1368    raeburn  7381:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7382:     my $canreq = 0;
1.1368    raeburn  7383:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7384:         $uname = $env{'user.name'};
                   7385:         $udom = $env{'user.domain'};
                   7386:     }
1.1035    raeburn  7387:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7388:     my @options = ('approval','validate','autolimit');
                   7389:     my $optregex = join('|',@options);
                   7390:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7391:         foreach my $type (@{$types}) {
1.1368    raeburn  7392:             if (&usertools_access($uname,$udom,$type,undef,
                   7393:                                   'requestcourses')) {
1.1035    raeburn  7394:                 $canreq ++;
1.1036    raeburn  7395:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7396:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7397:                 }
1.1368    raeburn  7398:                 if ($dom eq $udom) {
1.1035    raeburn  7399:                     $can_request->{$type} = 1;
                   7400:                 }
                   7401:             }
1.1368    raeburn  7402:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7403:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7404:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7405:                 if (@curr > 0) {
1.1036    raeburn  7406:                     foreach my $item (@curr) {
                   7407:                         if (ref($request_domains) eq 'HASH') {
                   7408:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7409:                             if ($otherdom ne '') {
                   7410:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7411:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7412:                                         push(@{$request_domains->{$type}},$otherdom);
                   7413:                                     }
                   7414:                                 } else {
                   7415:                                     push(@{$request_domains->{$type}},$otherdom);
                   7416:                                 }
                   7417:                             }
                   7418:                         }
                   7419:                     }
1.1368    raeburn  7420:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7421:                         $canreq ++;
1.1035    raeburn  7422:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7423:                             $can_request->{$type} = 1;
                   7424:                         }
                   7425:                     }
                   7426:                 }
                   7427:             }
                   7428:         }
                   7429:     }
                   7430:     return $canreq;
                   7431: }
                   7432: 
1.341     www      7433: # ---------------------------------------------- Custom access rule evaluation
                   7434: 
                   7435: sub customaccess {
                   7436:     my ($priv,$uri)=@_;
1.807     albertel 7437:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7438:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7439:     $udom = &LONCAPA::clean_domain($udom);
                   7440:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7441:     my $access=0;
1.800     albertel 7442:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7443: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7444: 	if ($type eq 'user') {
                   7445: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7446: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7447: 		if ($tdom) {
                   7448: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7449: 		}
1.896     albertel 7450: 		if ($tuname) {
                   7451: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7452: 		}
                   7453: 		$access=($effect eq 'allow');
                   7454: 		last;
                   7455: 	    }
                   7456: 	} else {
                   7457: 	    if ($role) {
                   7458: 		if ($role ne $urole) { next; }
                   7459: 	    }
                   7460: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7461: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7462: 		if ($tdom) {
                   7463: 		    if ($tdom ne $udom) { next; }
                   7464: 		}
                   7465: 		if ($tcrs) {
                   7466: 		    if ($tcrs ne $ucrs) { next; }
                   7467: 		}
                   7468: 		if ($tsec) {
                   7469: 		    if ($tsec ne $usec) { next; }
                   7470: 		}
                   7471: 		$access=($effect eq 'allow');
                   7472: 		last;
                   7473: 	    }
                   7474: 	    if ($realm eq '' && $role eq '') {
                   7475: 		$access=($effect eq 'allow');
                   7476: 	    }
1.402     bowersj2 7477: 	}
1.341     www      7478:     }
                   7479:     return $access;
                   7480: }
                   7481: 
1.103     harris41 7482: # ------------------------------------------------- Check for a user privilege
1.12      www      7483: 
                   7484: sub allowed {
1.1281    raeburn  7485:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7486:     my $ver_orguri=$uri;
1.439     www      7487:     $uri=&deversion($uri);
1.152     www      7488:     my $orguri=$uri;
1.52      www      7489:     $uri=&declutter($uri);
1.809     raeburn  7490: 
1.810     raeburn  7491:     if ($priv eq 'evb') {
                   7492: # Evade communication block restrictions for specified role in a course
                   7493:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7494:             return $1;
                   7495:         } else {
                   7496:             return;
                   7497:         }
                   7498:     }
                   7499: 
1.620     albertel 7500:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7501: # Free bre access to adm and meta resources
1.1343    raeburn  7502:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7503: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7504: 	&& ($priv eq 'bre')) {
1.14      www      7505: 	return 'F';
1.159     www      7506:     }
                   7507: 
1.545     banghart 7508: # Free bre access to user's own portfolio contents
1.714     raeburn  7509:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7510:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7511: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7512:         my %setters;
                   7513:         my ($startblock,$endblock) = 
                   7514:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7515:         if ($startblock && $endblock) {
                   7516:             return 'B';
                   7517:         } else {
                   7518:             return 'F';
                   7519:         }
1.545     banghart 7520:     }
                   7521: 
1.762     raeburn  7522: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7523:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7524:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7525:         if (exists($env{'request.course.id'})) {
                   7526:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7527:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7528:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7529:                 my $courseprivid=$env{'request.course.id'};
                   7530:                 $courseprivid=~s/\_/\//;
                   7531:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7532:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7533:                     return $1; 
1.762     raeburn  7534:                 } else {
                   7535:                     if ($env{'request.course.sec'}) {
                   7536:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7537:                     }
                   7538:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7539:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7540:                         return $2;
                   7541:                     }
1.714     raeburn  7542:                 }
                   7543:             }
                   7544:         }
                   7545:     }
                   7546: 
1.159     www      7547: # Free bre to public access
                   7548: 
                   7549:     if ($priv eq 'bre') {
1.1362    raeburn  7550:         my $copyright;
                   7551:         unless ($uri =~ /ext\.tool/) {
                   7552:             $copyright=&metadata($uri,'copyright');
                   7553:         }
1.620     albertel 7554: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7555:            return 'F'; 
                   7556:         }
1.238     www      7557:         if ($copyright eq 'priv') {
                   7558:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7559: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7560: 		return '';
                   7561:             }
                   7562:         }
                   7563:         if ($copyright eq 'domain') {
                   7564:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7565: 	    unless (($env{'user.domain'} eq $1) ||
                   7566:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7567: 		return '';
                   7568:             }
1.262     matthew  7569:         }
1.620     albertel 7570:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7571:             # Library role, so allow browsing of resources in this domain.
                   7572:             return 'F';
1.238     www      7573:         }
1.341     www      7574:         if ($copyright eq 'custom') {
                   7575: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7576:         }
1.14      www      7577:     }
1.264     matthew  7578:     # Domain coordinator is trying to create a course
1.620     albertel 7579:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7580:         # uri is the requested domain in this case.
                   7581:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7582:         # a role of dc for the domain in question.
1.620     albertel 7583:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7584:     }
1.29      www      7585: 
1.52      www      7586:     my $thisallowed='';
                   7587:     my $statecond=0;
                   7588:     my $courseprivid='';
                   7589: 
1.1039    raeburn  7590:     my $ownaccess;
1.1043    raeburn  7591:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7592:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7593:         if ($uri eq '') {
                   7594:             $ownaccess = 1;
                   7595:         } else {
                   7596:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7597:                 my $udom = $env{'user.domain'};
                   7598:                 my $uname = $env{'user.name'};
                   7599:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7600:                     $ownaccess = 1;
1.1040    raeburn  7601:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7602:                     unless ($uri =~ m{\.\./}) {
                   7603:                         $ownaccess = 1;
                   7604:                     }
                   7605:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7606:                     my $now = time;
                   7607:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7608:                         my $adom = $1;
                   7609:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7610:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7611:                                 my ($start,$end) = split('.',$env{$key});
                   7612:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7613:                                     $ownaccess = 1;
                   7614:                                     last;
                   7615:                                 }
                   7616:                             }
                   7617:                         }
                   7618:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7619:                         my $adom = $1;
                   7620:                         my $aname = $2;
1.1042    raeburn  7621:                         foreach my $role ('ca','aa') { 
                   7622:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7623:                                 my ($start,$end) =
                   7624:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7625:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7626:                                     $ownaccess = 1;
                   7627:                                     last;
                   7628:                                 }
1.1039    raeburn  7629:                             }
                   7630:                         }
                   7631:                     }
                   7632:                 }
                   7633:             }
                   7634:         }
                   7635:     }
                   7636: 
1.52      www      7637: # Course
                   7638: 
1.620     albertel 7639:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7640:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7641:             $thisallowed.=$1;
                   7642:         }
1.52      www      7643:     }
1.29      www      7644: 
1.52      www      7645: # Domain
                   7646: 
1.620     albertel 7647:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7648:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7649:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7650:             $thisallowed.=$1;
                   7651:         }
1.12      www      7652:     }
1.52      www      7653: 
1.1141    raeburn  7654: # User who is not author or co-author might still be able to edit
                   7655: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7656:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7657:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7658:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7659:             $thisallowed.=$1;
                   7660:         }
                   7661:     }
                   7662: 
1.52      www      7663: # Course: uri itself is a course
1.66      www      7664:     my $courseuri=$uri;
                   7665:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7666:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7667: 
1.620     albertel 7668:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7669:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7670:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7671:             $thisallowed.=$1;
                   7672:         }
1.12      www      7673:     }
1.29      www      7674: 
1.665     albertel 7675: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7676: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7677:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7678: 	$thisallowed='';
1.671     raeburn  7679:         my ($match)=&is_on_map($uri);
                   7680:         if ($match) {
                   7681:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7682:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7683:                 my $value = $1;
                   7684:                 if ($noblockcheck) {
                   7685:                     $thisallowed.=$value;
1.1162    raeburn  7686:                 } else {
1.1281    raeburn  7687:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7688:                     if (@blockers > 0) {
                   7689:                         $thisallowed = 'B';
                   7690:                     } else {
                   7691:                         $thisallowed.=$value;
                   7692:                     }
1.1162    raeburn  7693:                 }
1.671     raeburn  7694:             }
                   7695:         } else {
1.705     albertel 7696:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7697:             if ($refuri) {
                   7698:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7699:                     $thisallowed='F';
1.671     raeburn  7700:                 } else {
                   7701:                     $refuri=&declutter($refuri);
                   7702:                     my ($match) = &is_on_map($refuri);
                   7703:                     if ($match) {
1.1281    raeburn  7704:                         if ($noblockcheck) {
                   7705:                             $thisallowed='F';
1.1162    raeburn  7706:                         } else {
1.1281    raeburn  7707:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7708:                             if (@blockers > 0) {
                   7709:                                 $thisallowed = 'B';
                   7710:                             } else {
                   7711:                                 $thisallowed='F';
                   7712:                             }
1.1162    raeburn  7713:                         }
1.671     raeburn  7714:                     }
1.669     raeburn  7715:                 }
1.671     raeburn  7716:             }
                   7717:         }
1.314     www      7718:     }
1.492     albertel 7719: 
1.766     albertel 7720:     if ($priv eq 'bre'
                   7721: 	&& $thisallowed ne 'F' 
                   7722: 	&& $thisallowed ne '2'
                   7723: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7724: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7725:     }
1.1250    raeburn  7726: 
1.52      www      7727: # Full access at system, domain or course-wide level? Exit.
1.29      www      7728:     if ($thisallowed=~/F/) {
                   7729: 	return 'F';
                   7730:     }
                   7731: 
1.52      www      7732: # If this is generating or modifying users, exit with special codes
1.29      www      7733: 
1.643     www      7734:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7735: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7736: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7737: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7738: 	    unless ($auname) { return $thisallowed; }
                   7739: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7740: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7741: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7742: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7743: 	}
1.52      www      7744: 	return $thisallowed;
                   7745:     }
                   7746: #
1.103     harris41 7747: # Gathered so far: system, domain and course wide privileges
1.52      www      7748: #
                   7749: # Course: See if uri or referer is an individual resource that is part of 
                   7750: # the course
                   7751: 
1.620     albertel 7752:     if ($env{'request.course.id'}) {
1.232     www      7753: 
1.620     albertel 7754:        $courseprivid=$env{'request.course.id'};
                   7755:        if ($env{'request.course.sec'}) {
                   7756:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7757:        }
                   7758:        $courseprivid=~s/\_/\//;
                   7759:        my $checkreferer=1;
1.232     www      7760:        my ($match,$cond)=&is_on_map($uri);
                   7761:        if ($match) {
                   7762:            $statecond=$cond;
1.620     albertel 7763:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7764:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7765:                my $value = $1;
                   7766:                if ($priv eq 'bre') {
1.1281    raeburn  7767:                    if ($noblockcheck) {
                   7768:                        $thisallowed.=$value;
1.1162    raeburn  7769:                    } else {
1.1281    raeburn  7770:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7771:                        if (@blockers > 0) {
                   7772:                            $thisallowed = 'B';
                   7773:                        } else {
                   7774:                            $thisallowed.=$value;
                   7775:                        }
1.1162    raeburn  7776:                    }
                   7777:                } else {
                   7778:                    $thisallowed.=$value;
                   7779:                }
1.52      www      7780:                $checkreferer=0;
                   7781:            }
1.29      www      7782:        }
1.83      www      7783:        
1.148     www      7784:        if ($checkreferer) {
1.620     albertel 7785: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7786:             unless ($refuri) {
1.800     albertel 7787:                 foreach my $key (keys(%env)) {
                   7788: 		    if ($key=~/^httpref\..*\*/) {
                   7789: 			my $pattern=$key;
1.156     www      7790:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7791:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7792:                         $pattern=~s/\//\\\//g;
1.152     www      7793:                         if ($orguri=~/$pattern/) {
1.800     albertel 7794: 			    $refuri=$env{$key};
1.148     www      7795:                         }
                   7796:                     }
1.191     harris41 7797:                 }
1.148     www      7798:             }
1.232     www      7799: 
1.148     www      7800:          if ($refuri) { 
1.152     www      7801: 	  $refuri=&declutter($refuri);
1.232     www      7802:           my ($match,$cond)=&is_on_map($refuri);
                   7803:             if ($match) {
                   7804:               my $refstatecond=$cond;
1.620     albertel 7805:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7806:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7807:                   my $value = $1;
                   7808:                   if ($priv eq 'bre') {
1.1281    raeburn  7809:                       if ($noblockcheck) {
                   7810:                           $thisallowed.=$value;
1.1162    raeburn  7811:                       } else {
1.1281    raeburn  7812:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7813:                           if (@blockers > 0) {
                   7814:                               $thisallowed = 'B';
                   7815:                           } else {
                   7816:                               $thisallowed.=$value;
                   7817:                           }
1.1162    raeburn  7818:                       }
                   7819:                   } else {
                   7820:                       $thisallowed.=$value;
                   7821:                   }
1.53      www      7822:                   $uri=$refuri;
                   7823:                   $statecond=$refstatecond;
1.52      www      7824:               }
                   7825:           }
1.148     www      7826:         }
1.29      www      7827:        }
1.52      www      7828:    }
1.29      www      7829: 
1.52      www      7830: #
1.103     harris41 7831: # Gathered now: all privileges that could apply, and condition number
1.52      www      7832: # 
                   7833: #
                   7834: # Full or no access?
                   7835: #
1.29      www      7836: 
1.52      www      7837:     if ($thisallowed=~/F/) {
                   7838: 	return 'F';
                   7839:     }
1.29      www      7840: 
1.52      www      7841:     unless ($thisallowed) {
                   7842:         return '';
                   7843:     }
1.29      www      7844: 
1.52      www      7845: # Restrictions exist, deal with them
                   7846: #
                   7847: #   C:according to course preferences
                   7848: #   R:according to resource settings
                   7849: #   L:unless locked
                   7850: #   X:according to user session state
                   7851: #
                   7852: 
                   7853: # Possibly locked functionality, check all courses
1.54      www      7854: # Locks might take effect only after 10 minutes cache expiration for other
                   7855: # courses, and 2 minutes for current course
1.52      www      7856: 
                   7857:     my $envkey;
                   7858:     if ($thisallowed=~/L/) {
1.1000    raeburn  7859:         foreach $envkey (keys(%env)) {
1.54      www      7860:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7861:                my $courseid=$2;
                   7862:                my $roleid=$1.'.'.$2;
1.92      www      7863:                $courseid=~s/^\///;
1.54      www      7864:                my $expiretime=600;
1.620     albertel 7865:                if ($env{'request.role'} eq $roleid) {
1.54      www      7866: 		  $expiretime=120;
                   7867:                }
                   7868: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7869:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7870:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7871: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7872:                }
1.620     albertel 7873:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7874:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7875: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7876:                        &log($env{'user.domain'},$env{'user.name'},
                   7877:                             $env{'user.home'},
1.57      www      7878:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7879:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7880:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7881: 		       return '';
                   7882:                    }
                   7883:                }
1.620     albertel 7884:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7885:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7886: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7887:                        &log($env{'user.domain'},$env{'user.name'},
                   7888:                             $env{'user.home'},
1.57      www      7889:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7890:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7891:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7892: 		       return '';
                   7893:                    }
                   7894:                }
                   7895: 	   }
1.29      www      7896:        }
1.52      www      7897:     }
                   7898:    
                   7899: #
                   7900: # Rest of the restrictions depend on selected course
                   7901: #
                   7902: 
1.620     albertel 7903:     unless ($env{'request.course.id'}) {
1.766     albertel 7904: 	if ($thisallowed eq 'A') {
                   7905: 	    return 'A';
1.814     raeburn  7906:         } elsif ($thisallowed eq 'B') {
                   7907:             return 'B';
1.766     albertel 7908: 	} else {
                   7909: 	    return '1';
                   7910: 	}
1.52      www      7911:     }
1.29      www      7912: 
1.52      www      7913: #
                   7914: # Now user is definitely in a course
                   7915: #
1.53      www      7916: 
                   7917: 
                   7918: # Course preferences
                   7919: 
                   7920:    if ($thisallowed=~/C/) {
1.620     albertel 7921:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7922:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7923:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7924: 	   =~/\Q$rolecode\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 role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7928: 			$env{'request.course.id'});
                   7929: 	   }
1.237     www      7930:            return '';
                   7931:        }
                   7932: 
1.620     albertel 7933:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7934: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7935: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7936: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7937: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7938: 			$env{'request.course.id'});
                   7939: 	   }
1.54      www      7940:            return '';
                   7941:        }
1.53      www      7942:    }
                   7943: 
                   7944: # Resource preferences
                   7945: 
                   7946:    if ($thisallowed=~/R/) {
1.620     albertel 7947:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7948:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7949: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7950: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7951: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7952: 	   }
                   7953: 	   return '';
1.54      www      7954:        }
1.53      www      7955:    }
1.30      www      7956: 
1.246     www      7957: # Restricted by state or randomout?
1.30      www      7958: 
1.52      www      7959:    if ($thisallowed=~/X/) {
1.620     albertel 7960:       if ($env{'acc.randomout'}) {
1.579     albertel 7961: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7962:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7963:             return ''; 
                   7964:          }
1.247     www      7965:       }
                   7966:       if (&condval($statecond)) {
1.52      www      7967: 	 return '2';
                   7968:       } else {
                   7969:          return '';
                   7970:       }
                   7971:    }
1.30      www      7972: 
1.766     albertel 7973:     if ($thisallowed eq 'A') {
                   7974: 	return 'A';
1.814     raeburn  7975:     } elsif ($thisallowed eq 'B') {
                   7976:         return 'B';
1.766     albertel 7977:     }
1.52      www      7978:    return 'F';
1.232     www      7979: }
1.1162    raeburn  7980: 
1.1192    raeburn  7981: # ------------------------------------------- Check construction space access
                   7982: 
                   7983: sub constructaccess {
                   7984:     my ($url,$setpriv)=@_;
                   7985: 
                   7986: # We do not allow editing of previous versions of files
                   7987:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7988: 
                   7989: # Get username and domain from URL
                   7990:     my ($ownername,$ownerdomain,$ownerhome);
                   7991: 
                   7992:     ($ownerdomain,$ownername) =
1.1325    raeburn  7993:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7994: 
                   7995: # The URL does not really point to any authorspace, forget it
                   7996:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7997: 
                   7998: # Now we need to see if the user has access to the authorspace of
                   7999: # $ownername at $ownerdomain
                   8000: 
                   8001:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8002: # Real author for this?
                   8003:        $ownerhome = $env{'user.home'};
                   8004:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8005:           return ($ownername,$ownerdomain,$ownerhome);
                   8006:        }
                   8007:     } else {
                   8008: # Co-author for this?
                   8009:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8010:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8011:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8012:             return ($ownername,$ownerdomain,$ownerhome);
                   8013:         }
1.1312    raeburn  8014:         if ($env{'request.course.id'}) {
                   8015:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8016:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8017:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8018:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8019:                     return ($ownername,$ownerdomain,$ownerhome);
                   8020:                 }
                   8021:             }
                   8022:         }
1.1192    raeburn  8023:     }
                   8024: 
                   8025: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8026: # we might as well leave
                   8027:    unless ($setpriv) { return ''; }
                   8028: 
                   8029: # Backdoor access?
                   8030:     my $allowed=&allowed('eco',$ownerdomain);
                   8031: # Nope
                   8032:     unless ($allowed) { return ''; }
                   8033: # Looks like we may have access, but could be locked by the owner of the construction space
                   8034:     if ($allowed eq 'U') {
                   8035:         my %blocked=&get('environment',['domcoord.author'],
                   8036:                          $ownerdomain,$ownername);
                   8037: # Is blocked by owner
                   8038:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8039:     }
                   8040:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8041: # Grant temporary access
                   8042:         my $then=$env{'user.login.time'};
1.1209    raeburn  8043:         my $update=$env{'user.update.time'};
1.1192    raeburn  8044:         if (!$update) { $update = $then; }
                   8045:         my $refresh=$env{'user.refresh.time'};
                   8046:         if (!$refresh) { $refresh = $update; }
                   8047:         my $now = time;
                   8048:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8049:                            $now,'ca','constructaccess');
                   8050:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8051:         return($ownername,$ownerdomain,$ownerhome);
                   8052:     }
                   8053: # No business here
                   8054:     return '';
                   8055: }
                   8056: 
1.1282    raeburn  8057: # ----------------------------------------------------------- Content Blocking
                   8058: 
                   8059: {
                   8060: # Caches for faster Course Contents display where content blocking
                   8061: # is in operation (i.e., interval param set) for timed quiz.
                   8062: #
                   8063: # User for whom data are being temporarily cached.
                   8064: my $cacheduser='';
                   8065: # Cached blockers for this user (a hash of blocking items). 
                   8066: my %cachedblockers=();
                   8067: # When the data were last cached.
                   8068: my $cachedlast='';
                   8069: 
                   8070: sub load_all_blockers {
                   8071:     my ($uname,$udom,$blocks)=@_;
                   8072:     if (($uname ne '') && ($udom ne '')) { 
                   8073:         if (($cacheduser eq $uname.':'.$udom) &&
                   8074:             (abs($cachedlast-time)<5)) {
                   8075:             return;
                   8076:         }
                   8077:     }
                   8078:     $cachedlast=time;
                   8079:     $cacheduser=$uname.':'.$udom;
                   8080:     %cachedblockers = &get_commblock_resources($blocks);
                   8081: }
                   8082: 
1.1162    raeburn  8083: sub get_comm_blocks {
                   8084:     my ($cdom,$cnum) = @_;
                   8085:     if ($cdom eq '' || $cnum eq '') {
                   8086:         return unless ($env{'request.course.id'});
                   8087:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8088:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8089:     }
                   8090:     my %commblocks;
                   8091:     my $hashid=$cdom.'_'.$cnum;
                   8092:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8093:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8094:         %commblocks = %{$blocksref};
                   8095:     } else {
                   8096:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8097:         my $cachetime = 600;
                   8098:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8099:     }
                   8100:     return %commblocks;
                   8101: }
                   8102: 
1.1282    raeburn  8103: sub get_commblock_resources {
                   8104:     my ($blocks) = @_;
                   8105:     my %blockers = ();
                   8106:     return %blockers unless ($env{'request.course.id'});
                   8107:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8108:     my %commblocks;
                   8109:     if (ref($blocks) eq 'HASH') {
                   8110:         %commblocks = %{$blocks};
                   8111:     } else {
                   8112:         %commblocks = &get_comm_blocks();
                   8113:     }
1.1282    raeburn  8114:     return %blockers unless (keys(%commblocks) > 0); 
                   8115:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8116:     return %blockers unless (ref($navmap));
1.1162    raeburn  8117:     my $now = time;
                   8118:     foreach my $block (keys(%commblocks)) {
                   8119:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8120:             my ($start,$end) = ($1,$2);
                   8121:             if ($start <= $now && $end >= $now) {
                   8122:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8123:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8124:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8125:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8126:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8127:                             }
                   8128:                         }
                   8129:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8130:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8131:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8132:                             }
                   8133:                         }
                   8134:                     }
                   8135:                 }
                   8136:             }
                   8137:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8138:             my $item = $1;
1.1163    raeburn  8139:             my @to_test;
1.1162    raeburn  8140:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8141:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8142:                     my @interval;
                   8143:                     my $type = 'map';
                   8144:                     if ($item eq 'course') {
                   8145:                         $type = 'course';
                   8146:                         @interval=&EXT("resource.0.interval");
                   8147:                     } else {
                   8148:                         if ($item =~ /___\d+___/) {
                   8149:                             $type = 'resource';
                   8150:                             @interval=&EXT("resource.0.interval",$item);
                   8151:                             if (ref($navmap)) {                        
                   8152:                                 my $res = $navmap->getBySymb($item); 
                   8153:                                 push(@to_test,$res);
                   8154:                             }
1.1162    raeburn  8155:                         } else {
1.1282    raeburn  8156:                             my $mapsymb = &symbread($item,1);
                   8157:                             if ($mapsymb) {
                   8158:                                 if (ref($navmap)) {
                   8159:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8160:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8161:                                     foreach my $res (@to_test) {
                   8162:                                         my $symb = $res->symb();
                   8163:                                         next if ($symb eq $mapsymb);
                   8164:                                         if ($symb ne '') {
                   8165:                                             @interval=&EXT("resource.0.interval",$symb);
                   8166:                                             if ($interval[1] eq 'map') {
                   8167:                                                 last;
1.1162    raeburn  8168:                                             }
                   8169:                                         }
                   8170:                                     }
                   8171:                                 }
                   8172:                             }
                   8173:                         }
1.1282    raeburn  8174:                     }
1.1310    raeburn  8175:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8176:                         my $timelimit = $1; 
1.1282    raeburn  8177:                         my $first_access;
                   8178:                         if ($type eq 'resource') {
                   8179:                             $first_access=&get_first_access($interval[1],$item);
                   8180:                         } elsif ($type eq 'map') {
                   8181:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8182:                         } else {
                   8183:                             $first_access=&get_first_access($interval[1]);
                   8184:                         }
                   8185:                         if ($first_access) {
1.1292    raeburn  8186:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8187:                             if ($timesup > $now) {
                   8188:                                 my $activeblock;
                   8189:                                 foreach my $res (@to_test) {
1.1283    raeburn  8190:                                     if ($res->answerable()) {
1.1282    raeburn  8191:                                         $activeblock = 1;
                   8192:                                         last;
                   8193:                                     }
                   8194:                                 }
                   8195:                                 if ($activeblock) {
                   8196:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8197:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8198:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8199:                                          }
                   8200:                                     }
                   8201:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8202:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8203:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8204:                                         }
1.1162    raeburn  8205:                                     }
                   8206:                                 }
                   8207:                             }
                   8208:                         }
                   8209:                     }
                   8210:                 }
                   8211:             }
                   8212:         }
                   8213:     }
1.1282    raeburn  8214:     return %blockers;
1.1162    raeburn  8215: }
                   8216: 
1.1282    raeburn  8217: sub has_comm_blocking {
                   8218:     my ($priv,$symb,$uri,$blocks) = @_;
                   8219:     my @blockers;
                   8220:     return unless ($env{'request.course.id'});
                   8221:     return unless ($priv eq 'bre');
                   8222:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8223:     return if ($env{'request.state'} eq 'construct');
                   8224:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8225:     return unless (keys(%cachedblockers) > 0);
                   8226:     my (%possibles,@symbs);
                   8227:     if (!$symb) {
                   8228:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8229:     }
1.1282    raeburn  8230:     if ($symb) {
                   8231:         @symbs = ($symb);
                   8232:     } elsif (keys(%possibles)) { 
                   8233:         @symbs = keys(%possibles);
                   8234:     }
                   8235:     my $noblock;
                   8236:     foreach my $symb (@symbs) {
                   8237:         last if ($noblock);
                   8238:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8239:         foreach my $block (keys(%cachedblockers)) {
                   8240:             if ($block =~ /^firstaccess____(.+)$/) {
                   8241:                 my $item = $1;
                   8242:                 if (($item eq $map) || ($item eq $symb)) {
                   8243:                     $noblock = 1;
                   8244:                     last;
                   8245:                 }
                   8246:             }
                   8247:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8248:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8249:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8250:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8251:                             push(@blockers,$block);
                   8252:                         }
                   8253:                     }
                   8254:                 }
1.1162    raeburn  8255:             }
1.1282    raeburn  8256:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8257:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8258:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8259:                         push(@blockers,$block);
                   8260:                     }
                   8261:                 }
1.1162    raeburn  8262:             }
                   8263:         }
                   8264:     }
1.1282    raeburn  8265:     return if ($noblock);
                   8266:     return @blockers;
                   8267: }
1.1162    raeburn  8268: }
                   8269: 
1.1282    raeburn  8270: # -------------------------------- Deversion and split uri into path an filename   
                   8271: 
1.1133    foxr     8272: #
1.1282    raeburn  8273: #   Removes the version from a URI and
1.1133    foxr     8274: #   splits it in to its filename and path to the filename.
                   8275: #   Seems like File::Basename could have done this more clearly.
                   8276: #   Parameters:
                   8277: #      $uri   - input URI
                   8278: #   Returns:
                   8279: #     Two element list consisting of 
                   8280: #     $pathname  - the URI up to and excluding the trailing /
                   8281: #     $filename  - The part of the URI following the last /
                   8282: #  NOTE:
                   8283: #    Another realization of this is simply:
                   8284: #    use File::Basename;
                   8285: #    ...
                   8286: #    $uri = shift;
                   8287: #    $filename = basename($uri);
                   8288: #    $path     = dirname($uri);
                   8289: #    return ($filename, $path);
                   8290: #
                   8291: #     The implementation below is probably faster however.
                   8292: #
1.710     albertel 8293: sub split_uri_for_cond {
                   8294:     my $uri=&deversion(&declutter(shift));
                   8295:     my @uriparts=split(/\//,$uri);
                   8296:     my $filename=pop(@uriparts);
                   8297:     my $pathname=join('/',@uriparts);
                   8298:     return ($pathname,$filename);
                   8299: }
1.232     www      8300: # --------------------------------------------------- Is a resource on the map?
                   8301: 
                   8302: sub is_on_map {
1.710     albertel 8303:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8304:     #Trying to find the conditional for the file
1.620     albertel 8305:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8306: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8307:     if ($match) {
1.289     bowersj2 8308: 	return (1,$1);
                   8309:     } else {
1.434     www      8310: 	return (0,0);
1.289     bowersj2 8311:     }
1.12      www      8312: }
                   8313: 
1.427     www      8314: # --------------------------------------------------------- Get symb from alias
                   8315: 
                   8316: sub get_symb_from_alias {
                   8317:     my $symb=shift;
                   8318:     my ($map,$resid,$url)=&decode_symb($symb);
                   8319: # Already is a symb
                   8320:     if ($url) { return $symb; }
                   8321: # Must be an alias
                   8322:     my $aliassymb='';
                   8323:     my %bighash;
1.620     albertel 8324:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8325:                             &GDBM_READER(),0640)) {
                   8326:         my $rid=$bighash{'mapalias_'.$symb};
                   8327: 	if ($rid) {
                   8328: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8329: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8330: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8331: 	}
                   8332:         untie %bighash;
                   8333:     }
                   8334:     return $aliassymb;
                   8335: }
                   8336: 
1.12      www      8337: # ----------------------------------------------------------------- Define Role
                   8338: 
                   8339: sub definerole {
                   8340:   if (allowed('mcr','/')) {
1.1326    raeburn  8341:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8342:     foreach my $role (split(':',$sysrole)) {
                   8343: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8344:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8345:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8346: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8347:                return "refused:s:$crole&$cqual"; 
                   8348:             }
                   8349:         }
1.191     harris41 8350:     }
1.800     albertel 8351:     foreach my $role (split(':',$domrole)) {
                   8352: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8353:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8354:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8355: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8356:                return "refused:d:$crole&$cqual"; 
                   8357:             }
                   8358:         }
1.191     harris41 8359:     }
1.800     albertel 8360:     foreach my $role (split(':',$courole)) {
                   8361: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8362:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8363:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8364: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8365:                return "refused:c:$crole&$cqual"; 
                   8366:             }
                   8367:         }
1.191     harris41 8368:     }
1.1326    raeburn  8369:     my $uhome;
                   8370:     if (($uname ne '') && ($udom ne '')) {
                   8371:         $uhome = &homeserver($uname,$udom);
                   8372:         return $uhome if ($uhome eq 'no_host');
                   8373:     } else {
                   8374:         $uname = $env{'user.name'};
                   8375:         $udom = $env{'user.domain'};
                   8376:         $uhome = $env{'user.home'};
                   8377:     }
1.620     albertel 8378:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8379:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8380:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8381:     return reply($command,$uhome);
1.12      www      8382:   } else {
                   8383:     return 'refused';
                   8384:   }
1.105     harris41 8385: }
                   8386: 
                   8387: # ---------------- Make a metadata query against the network of library servers
                   8388: 
                   8389: sub metadata_query {
1.1237    raeburn  8390:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8391:     my %rhash;
1.845     albertel 8392:     my %libserv = &all_library();
1.244     matthew  8393:     my @server_list = (defined($server_array) ? @$server_array
                   8394:                                               : keys(%libserv) );
                   8395:     for my $server (@server_list) {
1.1237    raeburn  8396:         my $domains = ''; 
                   8397:         if (ref($domains_hash) eq 'HASH') {
                   8398:             $domains = $domains_hash->{$server}; 
                   8399:         }
1.118     harris41 8400: 	unless ($custom or $customshow) {
1.1237    raeburn  8401: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8402: 	    $rhash{$server}=$reply;
                   8403: 	}
                   8404: 	else {
                   8405: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8406: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8407: 			     $server);
                   8408: 	    $rhash{$server}=$reply;
                   8409: 	}
1.112     harris41 8410:     }
1.118     harris41 8411:     return \%rhash;
1.240     www      8412: }
                   8413: 
                   8414: # ----------------------------------------- Send log queries and wait for reply
                   8415: 
                   8416: sub log_query {
                   8417:     my ($uname,$udom,$query,%filters)=@_;
                   8418:     my $uhome=&homeserver($uname,$udom);
                   8419:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8420:     my $uhost=&hostname($uhome);
1.800     albertel 8421:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8422:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8423:                        $uhome);
1.479     albertel 8424:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8425:     return get_query_reply($queryid);
                   8426: }
                   8427: 
1.818     raeburn  8428: # -------------------------- Update MySQL table for portfolio file
                   8429: 
                   8430: sub update_portfolio_table {
1.821     raeburn  8431:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8432:     if ($group ne '') {
                   8433:         $file_name =~s /^\Q$group\E//;
                   8434:     }
1.818     raeburn  8435:     my $homeserver = &homeserver($uname,$udom);
                   8436:     my $queryid=
1.821     raeburn  8437:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8438:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8439:     my $reply = &get_query_reply($queryid);
                   8440:     return $reply;
                   8441: }
                   8442: 
1.899     raeburn  8443: # -------------------------- Update MySQL allusers table
                   8444: 
                   8445: sub update_allusers_table {
                   8446:     my ($uname,$udom,$names) = @_;
                   8447:     my $homeserver = &homeserver($uname,$udom);
                   8448:     my $queryid=
                   8449:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8450:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8451:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8452:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8453:                'generation='.&escape($names->{'generation'}).'%%'.
                   8454:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8455:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8456:     return;
1.899     raeburn  8457: }
                   8458: 
1.508     raeburn  8459: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8460: 
                   8461: sub fetch_enrollment_query {
1.511     raeburn  8462:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8463:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8464:     my $maxtries = 1;
1.508     raeburn  8465:     if ($context eq 'automated') {
                   8466:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8467:         $sleep = 2;
                   8468:         $loopmax = 100;
1.547     raeburn  8469:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8470:     } else {
                   8471:         $homeserver = &homeserver($cnum,$dom);
                   8472:     }
1.838     albertel 8473:     my $host=&hostname($homeserver);
1.506     raeburn  8474:     my $cmd = '';
1.1000    raeburn  8475:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8476:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8477:     }
                   8478:     $cmd =~ s/%%$//;
                   8479:     $cmd = &escape($cmd);
                   8480:     my $query = 'fetchenrollment';
1.620     albertel 8481:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8482:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8483:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8484:         return 'error: '.$queryid;
                   8485:     }
1.1317    raeburn  8486:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8487:     my $tries = 1;
                   8488:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8489:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8490:         $tries ++;
                   8491:     }
1.526     raeburn  8492:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8493:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8494:     } else {
1.901     albertel 8495:         my @responses = split(/:/,$reply);
1.1322    raeburn  8496:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8497:             foreach my $line (@responses) {
                   8498:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8499:                 $$replyref{$key} = $value;
                   8500:             }
                   8501:         } else {
1.1117    foxr     8502:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8503:             foreach my $line (@responses) {
                   8504:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8505:                 $$replyref{$key} = $value;
                   8506:                 if ($value > 0) {
1.800     albertel 8507:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8508:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8509:                         my $destname = $pathname.'/'.$filename;
                   8510:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8511:                         if ($xml_classlist =~ /^error/) {
                   8512:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8513:                         } else {
1.1359    raeburn  8514:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8515:                                 print FILE &unescape($xml_classlist);
                   8516:                                 close(FILE);
1.526     raeburn  8517:                             } else {
                   8518:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8519:                             }
                   8520:                         }
                   8521:                     }
                   8522:                 }
                   8523:             }
                   8524:         }
                   8525:         return 'ok';
                   8526:     }
                   8527:     return 'error';
                   8528: }
                   8529: 
1.242     www      8530: sub get_query_reply {
1.1317    raeburn  8531:     my ($queryid,$sleep,$loopmax) = @_;;
                   8532:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8533:         $sleep = 0.2;
                   8534:     }
                   8535:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8536:         $loopmax = 100;
                   8537:     }
1.1117    foxr     8538:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8539:     my $reply='';
1.1317    raeburn  8540:     for (1..$loopmax) {
                   8541: 	sleep($sleep);
1.240     www      8542:         if (-e $replyfile.'.end') {
1.1359    raeburn  8543: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8544: 		$reply = join('',<$fh>);
                   8545: 		close($fh);
1.240     www      8546: 	   } else { return 'error: reply_file_error'; }
1.242     www      8547:            return &unescape($reply);
                   8548: 	}
1.240     www      8549:     }
1.242     www      8550:     return 'timeout:'.$queryid;
1.240     www      8551: }
                   8552: 
                   8553: sub courselog_query {
1.241     www      8554: #
                   8555: # possible filters:
                   8556: # url: url or symb
                   8557: # username
                   8558: # domain
                   8559: # action: view, submit, grade
                   8560: # start: timestamp
                   8561: # end: timestamp
                   8562: #
1.240     www      8563:     my (%filters)=@_;
1.620     albertel 8564:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8565:     if ($filters{'url'}) {
                   8566: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8567:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8568:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8569:     }
1.620     albertel 8570:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8571:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8572:     return &log_query($cname,$cdom,'courselog',%filters);
                   8573: }
                   8574: 
                   8575: sub userlog_query {
1.858     raeburn  8576: #
                   8577: # possible filters:
                   8578: # action: log check role
                   8579: # start: timestamp
                   8580: # end: timestamp
                   8581: #
1.240     www      8582:     my ($uname,$udom,%filters)=@_;
                   8583:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8584: }
                   8585: 
1.506     raeburn  8586: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8587: 
                   8588: sub auto_run {
1.508     raeburn  8589:     my ($cnum,$cdom) = @_;
1.876     raeburn  8590:     my $response = 0;
                   8591:     my $settings;
                   8592:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8593:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8594:         $settings = $domconfig{'autoenroll'};
                   8595:         if ($settings->{'run'} eq '1') {
                   8596:             $response = 1;
                   8597:         }
                   8598:     } else {
1.934     raeburn  8599:         my $homeserver;
                   8600:         if (&is_course($cdom,$cnum)) {
                   8601:             $homeserver = &homeserver($cnum,$cdom);
                   8602:         } else {
                   8603:             $homeserver = &domain($cdom,'primary');
                   8604:         }
                   8605:         if ($homeserver ne 'no_host') {
                   8606:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8607:         }
1.876     raeburn  8608:     }
1.506     raeburn  8609:     return $response;
                   8610: }
1.776     albertel 8611: 
1.506     raeburn  8612: sub auto_get_sections {
1.508     raeburn  8613:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8614:     my $homeserver;
                   8615:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8616:         $homeserver = &homeserver($cnum,$cdom);
                   8617:     }
                   8618:     if (!defined($homeserver)) { 
                   8619:         if ($cdom =~ /^$match_domain$/) {
                   8620:             $homeserver = &domain($cdom,'primary');
                   8621:         }
                   8622:     }
                   8623:     my @secs;
                   8624:     if (defined($homeserver)) {
                   8625:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8626:         unless ($response eq 'refused') {
                   8627:             @secs = split(/:/,$response);
                   8628:         }
1.506     raeburn  8629:     }
                   8630:     return @secs;
                   8631: }
1.776     albertel 8632: 
1.506     raeburn  8633: sub auto_new_course {
1.1099    raeburn  8634:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8635:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8636:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8637:     return $response;
                   8638: }
1.776     albertel 8639: 
1.506     raeburn  8640: sub auto_validate_courseID {
1.508     raeburn  8641:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8642:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8643:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8644:     return $response;
                   8645: }
1.776     albertel 8646: 
1.1007    raeburn  8647: sub auto_validate_instcode {
1.1020    raeburn  8648:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8649:     my ($homeserver,$response);
                   8650:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8651:         $homeserver = &homeserver($cnum,$cdom);
                   8652:     }
                   8653:     if (!defined($homeserver)) {
                   8654:         if ($cdom =~ /^$match_domain$/) {
                   8655:             $homeserver = &domain($cdom,'primary');
                   8656:         }
                   8657:     }
1.1065    raeburn  8658:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8659:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8660:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8661:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8662: }
                   8663: 
1.506     raeburn  8664: sub auto_create_password {
1.873     raeburn  8665:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8666:     my ($homeserver,$response);
1.506     raeburn  8667:     my $create_passwd = 0;
                   8668:     my $authchk = '';
1.873     raeburn  8669:     if ($udom =~ /^$match_domain$/) {
                   8670:         $homeserver = &domain($udom,'primary');
                   8671:     }
                   8672:     if ($homeserver eq '') {
                   8673:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8674:             $homeserver = &homeserver($cnum,$cdom);
                   8675:         }
                   8676:     }
                   8677:     if ($homeserver eq '') {
                   8678:         $authchk = 'nodomain';
1.506     raeburn  8679:     } else {
1.873     raeburn  8680:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8681:         if ($response eq 'refused') {
                   8682:             $authchk = 'refused';
                   8683:         } else {
1.901     albertel 8684:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8685:         }
1.506     raeburn  8686:     }
                   8687:     return ($authparam,$create_passwd,$authchk);
                   8688: }
                   8689: 
1.706     raeburn  8690: sub auto_photo_permission {
                   8691:     my ($cnum,$cdom,$students) = @_;
                   8692:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8693:     my ($outcome,$perm_reqd,$conditions) = 
                   8694: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8695:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8696: 	return (undef,undef);
                   8697:     }
1.706     raeburn  8698:     return ($outcome,$perm_reqd,$conditions);
                   8699: }
                   8700: 
                   8701: sub auto_checkphotos {
                   8702:     my ($uname,$udom,$pid) = @_;
                   8703:     my $homeserver = &homeserver($uname,$udom);
                   8704:     my ($result,$resulttype);
                   8705:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8706: 				   &escape($uname).':'.&escape($pid),
                   8707: 				   $homeserver));
1.709     albertel 8708:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8709: 	return (undef,undef);
                   8710:     }
1.706     raeburn  8711:     if ($outcome) {
                   8712:         ($result,$resulttype) = split(/:/,$outcome);
                   8713:     } 
                   8714:     return ($result,$resulttype);
                   8715: }
                   8716: 
                   8717: sub auto_photochoice {
                   8718:     my ($cnum,$cdom) = @_;
                   8719:     my $homeserver = &homeserver($cnum,$cdom);
                   8720:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8721: 						       &escape($cdom),
                   8722: 						       $homeserver)));
1.709     albertel 8723:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8724: 	return (undef,undef);
                   8725:     }
1.706     raeburn  8726:     return ($update,$comment);
                   8727: }
                   8728: 
                   8729: sub auto_photoupdate {
                   8730:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8731:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8732:     my $host=&hostname($homeserver);
1.706     raeburn  8733:     my $cmd = '';
                   8734:     my $maxtries = 1;
1.800     albertel 8735:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8736:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8737:     }
                   8738:     $cmd =~ s/%%$//;
                   8739:     $cmd = &escape($cmd);
                   8740:     my $query = 'institutionalphotos';
                   8741:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8742:     unless ($queryid=~/^\Q$host\E\_/) {
                   8743:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8744:         return 'error: '.$queryid;
                   8745:     }
                   8746:     my $reply = &get_query_reply($queryid);
                   8747:     my $tries = 1;
                   8748:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8749:         $reply = &get_query_reply($queryid);
                   8750:         $tries ++;
                   8751:     }
                   8752:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8753:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8754:     } else {
                   8755:         my @responses = split(/:/,$reply);
                   8756:         my $outcome = shift(@responses); 
                   8757:         foreach my $item (@responses) {
                   8758:             my ($key,$value) = split(/=/,$item);
                   8759:             $$photo{$key} = $value;
                   8760:         }
                   8761:         return $outcome;
                   8762:     }
                   8763:     return 'error';
                   8764: }
                   8765: 
1.521     raeburn  8766: sub auto_instcode_format {
1.793     albertel 8767:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8768: 	$cat_order) = @_;
1.521     raeburn  8769:     my $courses = '';
1.772     raeburn  8770:     my @homeservers;
1.521     raeburn  8771:     if ($caller eq 'global') {
1.841     albertel 8772: 	my %servers = &get_servers($codedom,'library');
                   8773: 	foreach my $tryserver (keys(%servers)) {
                   8774: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8775: 		push(@homeservers,$tryserver);
                   8776: 	    }
1.584     raeburn  8777:         }
1.1022    raeburn  8778:     } elsif ($caller eq 'requests') {
                   8779:         if ($codedom =~ /^$match_domain$/) {
                   8780:             my $chome = &domain($codedom,'primary');
                   8781:             unless ($chome eq 'no_host') {
                   8782:                 push(@homeservers,$chome);
                   8783:             }
                   8784:         }
1.521     raeburn  8785:     } else {
1.772     raeburn  8786:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8787:     }
1.793     albertel 8788:     foreach my $code (keys(%{$instcodes})) {
                   8789:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8790:     }
                   8791:     chop($courses);
1.772     raeburn  8792:     my $ok_response = 0;
                   8793:     my $response;
                   8794:     while (@homeservers > 0 && $ok_response == 0) {
                   8795:         my $server = shift(@homeservers); 
                   8796:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8797:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8798:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8799: 		split(/:/,$response);
1.772     raeburn  8800:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8801:             push(@{$codetitles},&str2array($codetitles_str));
                   8802:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8803:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8804:             $ok_response = 1;
                   8805:         }
                   8806:     }
                   8807:     if ($ok_response) {
1.521     raeburn  8808:         return 'ok';
1.772     raeburn  8809:     } else {
                   8810:         return $response;
1.521     raeburn  8811:     }
                   8812: }
                   8813: 
1.792     raeburn  8814: sub auto_instcode_defaults {
                   8815:     my ($domain,$returnhash,$code_order) = @_;
                   8816:     my @homeservers;
1.841     albertel 8817: 
                   8818:     my %servers = &get_servers($domain,'library');
                   8819:     foreach my $tryserver (keys(%servers)) {
                   8820: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8821: 	    push(@homeservers,$tryserver);
                   8822: 	}
1.792     raeburn  8823:     }
1.841     albertel 8824: 
1.792     raeburn  8825:     my $response;
1.841     albertel 8826:     foreach my $server (@homeservers) {
1.792     raeburn  8827:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8828:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8829: 	
                   8830: 	foreach my $pair (split(/\&/,$response)) {
                   8831: 	    my ($name,$value)=split(/\=/,$pair);
                   8832: 	    if ($name eq 'code_order') {
                   8833: 		@{$code_order} = split(/\&/,&unescape($value));
                   8834: 	    } else {
                   8835: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8836: 	    }
                   8837: 	}
                   8838: 	return 'ok';
1.792     raeburn  8839:     }
1.841     albertel 8840: 
                   8841:     return $response;
1.1003    raeburn  8842: }
                   8843: 
                   8844: sub auto_possible_instcodes {
1.1007    raeburn  8845:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8846:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8847:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8848:         return;
                   8849:     }
1.1003    raeburn  8850:     my (@homeservers,$uhome);
                   8851:     if (defined(&domain($domain,'primary'))) {
                   8852:         $uhome=&domain($domain,'primary');
                   8853:         push(@homeservers,&domain($domain,'primary'));
                   8854:     } else {
                   8855:         my %servers = &get_servers($domain,'library');
                   8856:         foreach my $tryserver (keys(%servers)) {
                   8857:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8858:                 push(@homeservers,$tryserver);
                   8859:             }
                   8860:         }
                   8861:     }
                   8862:     my $response;
                   8863:     foreach my $server (@homeservers) {
                   8864:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8865:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8866:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8867:             split(':',$response);
                   8868:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8869:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8870:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8871:             my ($name,$value)=split('=',$item);
                   8872:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8873:         }
                   8874:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8875:             my ($name,$value)=split('=',$item);
                   8876:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8877:         }
                   8878:         return 'ok';
                   8879:     }
                   8880:     return $response;
                   8881: }
1.792     raeburn  8882: 
1.1010    raeburn  8883: sub auto_courserequest_checks {
                   8884:     my ($dom) = @_;
1.1020    raeburn  8885:     my ($homeserver,%validations);
                   8886:     if ($dom =~ /^$match_domain$/) {
                   8887:         $homeserver = &domain($dom,'primary');
                   8888:     }
                   8889:     unless ($homeserver eq 'no_host') {
                   8890:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8891:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8892:             my @items = split(/&/,$response);
                   8893:             foreach my $item (@items) {
                   8894:                 my ($key,$value) = split('=',$item);
                   8895:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8896:             }
                   8897:         }
                   8898:     }
1.1010    raeburn  8899:     return %validations; 
                   8900: }
                   8901: 
1.1020    raeburn  8902: sub auto_courserequest_validation {
1.1255    raeburn  8903:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8904:     my ($homeserver,$response);
                   8905:     if ($dom =~ /^$match_domain$/) {
                   8906:         $homeserver = &domain($dom,'primary');
                   8907:     }
1.1255    raeburn  8908:     unless ($homeserver eq 'no_host') {
                   8909:         my $customdata;
                   8910:         if (ref($custominfo) eq 'HASH') {
                   8911:             $customdata = &freeze_escape($custominfo);
                   8912:         }
1.1020    raeburn  8913:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8914:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8915:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8916:                                     $customdata,$homeserver));
1.1020    raeburn  8917:     }
                   8918:     return $response;
                   8919: }
                   8920: 
1.777     albertel 8921: sub auto_validate_class_sec {
1.918     raeburn  8922:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8923:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8924:     my $ownerlist;
                   8925:     if (ref($owners) eq 'ARRAY') {
                   8926:         $ownerlist = join(',',@{$owners});
                   8927:     } else {
                   8928:         $ownerlist = $owners;
                   8929:     }
1.773     raeburn  8930:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8931:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8932:     return $response;
                   8933: }
                   8934: 
1.1367    raeburn  8935: sub auto_validate_instclasses {
                   8936:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8937:     my ($homeserver,%validations);
                   8938:     $homeserver = &homeserver($cnum,$cdom);
                   8939:     unless ($homeserver eq 'no_host') {
                   8940:         my $ownerlist;
                   8941:         if (ref($owners) eq 'ARRAY') {
                   8942:             $ownerlist = join(',',@{$owners});
                   8943:         } else {
                   8944:             $ownerlist = $owners;
                   8945:         }
                   8946:         if (ref($classesref) eq 'HASH') {
                   8947:             my $classes = &freeze_escape($classesref);
                   8948:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8949:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8950:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8951:                 my @items = split(/&/,$response);
                   8952:                 foreach my $item (@items) {
                   8953:                     my ($key,$value) = split('=',$item);
                   8954:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8955:                 }
                   8956:             }
                   8957:         }
                   8958:     }
                   8959:     return %validations;
                   8960: }
                   8961: 
1.1248    raeburn  8962: sub auto_crsreq_update {
                   8963:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8964:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8965:     my ($homeserver,%crsreqresponse);
                   8966:     if ($cdom =~ /^$match_domain$/) {
                   8967:         $homeserver = &domain($cdom,'primary');
                   8968:     }
                   8969:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8970:         my $info;
                   8971:         if (ref($inbound) eq 'HASH') {
                   8972:             $info = &freeze_escape($inbound);
                   8973:         }
                   8974:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8975:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8976:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8977:                             &escape($title).':'.&escape($code).':'.
                   8978:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8979:                             $homeserver);
1.1248    raeburn  8980:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8981:             my @items = split(/&/,$response);
                   8982:             foreach my $item (@items) {
                   8983:                 my ($key,$value) = split('=',$item);
                   8984:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8985:             }
                   8986:         }
                   8987:     }
                   8988:     return \%crsreqresponse;
                   8989: }
                   8990: 
1.1305    raeburn  8991: sub auto_export_grades {
1.1309    raeburn  8992:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8993:     my ($homeserver,%exportresponse);
                   8994:     if ($cdom =~ /^$match_domain$/) {
                   8995:         $homeserver = &domain($cdom,'primary');
                   8996:     }
                   8997:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8998:         my $info;
                   8999:         if (ref($inforef) eq 'HASH') {
                   9000:             $info = &freeze_escape($inforef);
                   9001:         }
                   9002:         if (ref($gradesref) eq 'HASH') {
                   9003:             my $grades = &freeze_escape($gradesref);
                   9004:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9005:                                 $info.':'.$grades,$homeserver);
                   9006:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9007:                 my @items = split(/&/,$response);
                   9008:                 foreach my $item (@items) {
                   9009:                     my ($key,$value) = split('=',$item);
                   9010:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9011:                 }
                   9012:             }
                   9013:         }
                   9014:     }
                   9015:     return \%exportresponse;
1.1305    raeburn  9016: }
                   9017: 
1.1287    raeburn  9018: sub check_instcode_cloning {
                   9019:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9020:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9021:         return;
                   9022:     }
                   9023:     my $canclone;
                   9024:     if (@{$code_order} > 0) {
                   9025:         my $instcoderegexp ='^';
                   9026:         my @clonecodes = split(/\&/,$cloner);
                   9027:         foreach my $item (@{$code_order}) {
                   9028:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9029:                 foreach my $pair (@clonecodes) {
                   9030:                     my ($key,$val) = split(/\=/,$pair,2);
                   9031:                     $val = &unescape($val);
                   9032:                     if ($key eq $item) {
                   9033:                         $instcoderegexp .= '('.$val.')';
                   9034:                         last;
                   9035:                     }
                   9036:                 }
                   9037:             } else {
                   9038:                 $instcoderegexp .= $codedefaults->{$item};
                   9039:             }
                   9040:         }
                   9041:         $instcoderegexp .= '$';
                   9042:         my (@from,@to);
                   9043:         eval {
                   9044:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9045:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9046:         };
                   9047:         if ((@from > 0) && (@to > 0)) {
                   9048:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9049:             if (!@diffs) {
                   9050:                 $canclone = 1;
                   9051:             }
                   9052:         }
                   9053:     }
                   9054:     return $canclone;
                   9055: }
                   9056: 
                   9057: sub default_instcode_cloning {
                   9058:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9059:     my (%codedefaults,@code_order,$canclone);
                   9060:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9061:         %codedefaults = %{$codedefaultsref};
                   9062:         @code_order = @{$codeorderref};
                   9063:     } elsif ($clonedom) {
                   9064:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9065:     }
                   9066:     if (($domdefclone) && (@code_order)) {
                   9067:         my @clonecodes = split(/\+/,$domdefclone);
                   9068:         my $instcoderegexp ='^';
                   9069:         foreach my $item (@code_order) {
                   9070:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9071:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9072:             } else {
                   9073:                 $instcoderegexp .= $codedefaults{$item};
                   9074:             }
                   9075:         }
                   9076:         $instcoderegexp .= '$';
                   9077:         my (@from,@to);
                   9078:         eval {
                   9079:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9080:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9081:         };
                   9082:         if ((@from > 0) && (@to > 0)) {
                   9083:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9084:             if (!@diffs) {
                   9085:                 $canclone = 1;
                   9086:             }
                   9087:         }
                   9088:     }
                   9089:     return $canclone;
                   9090: }
                   9091: 
1.679     raeburn  9092: # ------------------------------------------------------- Course Group routines
                   9093: 
                   9094: sub get_coursegroups {
1.809     raeburn  9095:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9096:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9097: }
                   9098: 
1.679     raeburn  9099: sub modify_coursegroup {
                   9100:     my ($cdom,$cnum,$groupsettings) = @_;
                   9101:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9102: }
                   9103: 
1.809     raeburn  9104: sub toggle_coursegroup_status {
                   9105:     my ($cdom,$cnum,$group,$action) = @_;
                   9106:     my ($from_namespace,$to_namespace);
                   9107:     if ($action eq 'delete') {
                   9108:         $from_namespace = 'coursegroups';
                   9109:         $to_namespace = 'deleted_groups';
                   9110:     } else {
                   9111:         $from_namespace = 'deleted_groups';
                   9112:         $to_namespace = 'coursegroups';
                   9113:     }
                   9114:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9115:     if (my $tmp = &error(%curr_group)) {
                   9116:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9117:         return ('read error',$tmp);
                   9118:     } else {
                   9119:         my %savedsettings = %curr_group; 
1.809     raeburn  9120:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9121:         my $deloutcome;
                   9122:         if ($result eq 'ok') {
1.809     raeburn  9123:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9124:         } else {
                   9125:             return ('write error',$result);
                   9126:         }
                   9127:         if ($deloutcome eq 'ok') {
                   9128:             return 'ok';
                   9129:         } else {
                   9130:             return ('delete error',$deloutcome);
                   9131:         }
                   9132:     }
                   9133: }
                   9134: 
1.679     raeburn  9135: sub modify_group_roles {
1.957     raeburn  9136:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9137:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9138:     my $role = 'gr/'.&escape($userprivs);
                   9139:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9140:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9141:     if ($result eq 'ok') {
                   9142:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9143:     }
1.679     raeburn  9144:     return $result;
                   9145: }
                   9146: 
                   9147: sub modify_coursegroup_membership {
                   9148:     my ($cdom,$cnum,$membership) = @_;
                   9149:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9150:     return $result;
                   9151: }
                   9152: 
1.682     raeburn  9153: sub get_active_groups {
                   9154:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9155:     my $now = time;
                   9156:     my %groups = ();
                   9157:     foreach my $key (keys(%env)) {
1.811     albertel 9158:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9159:             my ($start,$end) = split(/\./,$env{$key});
                   9160:             if (($end!=0) && ($end<$now)) { next; }
                   9161:             if (($start!=0) && ($start>$now)) { next; }
                   9162:             if ($1 eq $cdom && $2 eq $cnum) {
                   9163:                 $groups{$3} = $env{$key} ;
                   9164:             }
                   9165:         }
                   9166:     }
                   9167:     return %groups;
                   9168: }
                   9169: 
1.683     raeburn  9170: sub get_group_membership {
                   9171:     my ($cdom,$cnum,$group) = @_;
                   9172:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9173: }
                   9174: 
                   9175: sub get_users_groups {
                   9176:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9177:     my @usersgroups;
1.683     raeburn  9178:     my $cachetime=1800;
                   9179: 
                   9180:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9181:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9182:     if (defined($cached)) {
1.734     albertel 9183:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9184:     } else {  
                   9185:         $grouplist = '';
1.816     raeburn  9186:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9187:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9188:         my $access_end = $env{'course.'.$courseid.
                   9189:                               '.default_enrollment_end_date'};
                   9190:         my $now = time;
                   9191:         foreach my $key (keys(%roleshash)) {
                   9192:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9193:                 my $group = $1;
                   9194:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9195:                     my $start = $2;
                   9196:                     my $end = $1;
                   9197:                     if ($start == -1) { next; } # deleted from group
                   9198:                     if (($start!=0) && ($start>$now)) { next; }
                   9199:                     if (($end!=0) && ($end<$now)) {
                   9200:                         if ($access_end && $access_end < $now) {
                   9201:                             if ($access_end - $end < 86400) {
                   9202:                                 push(@usersgroups,$group);
1.733     raeburn  9203:                             }
                   9204:                         }
1.817     raeburn  9205:                         next;
1.733     raeburn  9206:                     }
1.817     raeburn  9207:                     push(@usersgroups,$group);
1.683     raeburn  9208:                 }
                   9209:             }
                   9210:         }
1.817     raeburn  9211:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9212:         $grouplist = join(':',@usersgroups);
                   9213:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9214:     }
1.733     raeburn  9215:     return @usersgroups;
1.683     raeburn  9216: }
                   9217: 
                   9218: sub devalidate_getgroups_cache {
                   9219:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9220:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9221: 
1.683     raeburn  9222:     my $hashid="$udom:$uname:$courseid";
                   9223:     &devalidate_cache_new('getgroups',$hashid);
                   9224: }
                   9225: 
1.12      www      9226: # ------------------------------------------------------------------ Plain Text
                   9227: 
                   9228: sub plaintext {
1.988     raeburn  9229:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9230:     if ($short =~ m{^cr/}) {
1.758     albertel 9231: 	return (split('/',$short))[-1];
                   9232:     }
1.742     raeburn  9233:     if (!defined($cid)) {
                   9234:         $cid = $env{'request.course.id'};
                   9235:     }
                   9236:     my %rolenames = (
1.1008    raeburn  9237:                       Course    => 'std',
                   9238:                       Community => 'alt1',
1.1305    raeburn  9239:                       Placement => 'std',
1.742     raeburn  9240:                     );
1.1037    raeburn  9241:     if ($cid ne '') {
                   9242:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9243:             unless ($forcedefault) {
                   9244:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9245:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9246:                 return &Apache::lonlocal::mt($roletext);
                   9247:             }
                   9248:         }
                   9249:     }
                   9250:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9251:         (defined($rolenames{$type})) && 
                   9252:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9253:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9254:     } elsif ($cid ne '') {
                   9255:         my $crstype = $env{'course.'.$cid.'.type'};
                   9256:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9257:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9258:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9259:         }
1.742     raeburn  9260:     }
1.1037    raeburn  9261:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9262: }
                   9263: 
                   9264: # ----------------------------------------------------------------- Assign Role
                   9265: 
                   9266: sub assignrole {
1.957     raeburn  9267:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9268:         $context)=@_;
1.21      www      9269:     my $mrole;
                   9270:     if ($role =~ /^cr\//) {
1.393     www      9271:         my $cwosec=$url;
1.811     albertel 9272:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9273: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9274:            my $refused = 1;
                   9275:            if ($context eq 'requestcourses') {
                   9276:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9277:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9278:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9279:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9280:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9281:                            if ($crsenv{'internal.courseowner'} eq
                   9282:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9283:                                $refused = '';
                   9284:                            }
                   9285:                        }
                   9286:                    }
                   9287:                }
                   9288:            }
                   9289:            if ($refused) {
                   9290:                &logthis('Refused custom assignrole: '.
                   9291:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9292:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9293:                return 'refused';
                   9294:            }
1.104     www      9295:         }
1.21      www      9296:         $mrole='cr';
1.678     raeburn  9297:     } elsif ($role =~ /^gr\//) {
                   9298:         my $cwogrp=$url;
1.811     albertel 9299:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9300:         unless (&allowed('mdg',$cwogrp)) {
                   9301:             &logthis('Refused group assignrole: '.
                   9302:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9303:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9304:             return 'refused';
                   9305:         }
                   9306:         $mrole='gr';
1.21      www      9307:     } else {
1.82      www      9308:         my $cwosec=$url;
1.811     albertel 9309:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9310:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9311:             my $refused;
                   9312:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9313:                 if (!(&allowed('c'.$role,$url))) {
                   9314:                     $refused = 1;
                   9315:                 }
                   9316:             } else {
                   9317:                 $refused = 1;
                   9318:             }
1.947     raeburn  9319:             if ($refused) {
1.1045    raeburn  9320:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9321:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9322:                     my %crsenv;
                   9323:                     if ($role eq 'cc' || $role eq 'co') {
                   9324:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9325:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9326:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9327:                                 if ($crsenv{'internal.courseowner'} eq 
                   9328:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9329:                                     $refused = '';
                   9330:                                 }
                   9331:                             }
                   9332:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9333:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9334:                                 if ($crsenv{'internal.courseowner'} eq 
                   9335:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9336:                                     $refused = '';
                   9337:                                 }
                   9338:                             }
                   9339:                         }
                   9340:                     }
1.1368    raeburn  9341:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9342:                     if ($role eq 'st') {
                   9343:                         $refused = '';
1.1377    raeburn  9344:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9345:                         $refused = '';
                   9346:                     }
1.1017    raeburn  9347:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9348:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9349:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9350:                         my $wrongcc;
                   9351:                         if ($cnum =~ /^$match_community$/) {
                   9352:                             $wrongcc = 1 if ($role eq 'cc');
                   9353:                         } else {
                   9354:                             $wrongcc = 1 if ($role eq 'co');
                   9355:                         }
                   9356:                         unless ($wrongcc) {
                   9357:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9358:                             if ($crsenv{'internal.courseowner'} eq 
                   9359:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9360:                                 $refused = '';
                   9361:                             }
1.1017    raeburn  9362:                         }
                   9363:                     }
1.1183    raeburn  9364:                 } elsif ($context eq 'requestauthor') {
                   9365:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9366:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9367:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9368:                             $refused = '';
                   9369:                         } else {
                   9370:                             my %domdefaults = &get_domain_defaults($udom);
                   9371:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9372:                                 my $checkbystatus;
                   9373:                                 if ($env{'user.adv'}) { 
                   9374:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9375:                                     if ($disposition eq 'automatic') {
                   9376:                                         $refused = '';
                   9377:                                     } elsif ($disposition eq '') {
                   9378:                                         $checkbystatus = 1;
                   9379:                                     } 
                   9380:                                 } else {
                   9381:                                     $checkbystatus = 1;
                   9382:                                 }
                   9383:                                 if ($checkbystatus) {
                   9384:                                     if ($env{'environment.inststatus'}) {
                   9385:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9386:                                         foreach my $type (@inststatuses) {
                   9387:                                             if (($type ne '') &&
                   9388:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9389:                                                 $refused = '';
                   9390:                                             }
                   9391:                                         }
                   9392:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9393:                                         $refused = '';
                   9394:                                     }
                   9395:                                 }
                   9396:                             }
                   9397:                         }
                   9398:                     }
1.1017    raeburn  9399:                 }
                   9400:                 if ($refused) {
1.947     raeburn  9401:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9402:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9403: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9404:                     return 'refused';
                   9405:                 }
1.932     raeburn  9406:             }
1.1131    raeburn  9407:         } elsif ($role eq 'au') {
                   9408:             if ($url ne '/'.$udom.'/') {
                   9409:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9410:                          ' to assign author role for '.$uname.':'.$udom.
                   9411:                          ' in domain: '.$url.' refused (wrong domain).');
                   9412:                 return 'refused';
                   9413:             }
1.104     www      9414:         }
1.21      www      9415:         $mrole=$role;
                   9416:     }
1.620     albertel 9417:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9418:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9419:     if ($end) { $command.='_'.$end; }
1.21      www      9420:     if ($start) {
                   9421: 	if ($end) { 
1.81      www      9422:            $command.='_'.$start; 
1.21      www      9423:         } else {
1.81      www      9424:            $command.='_0_'.$start;
1.21      www      9425:         }
                   9426:     }
1.739     raeburn  9427:     my $origstart = $start;
                   9428:     my $origend = $end;
1.957     raeburn  9429:     my $delflag;
1.357     www      9430: # actually delete
                   9431:     if ($deleteflag) {
1.373     www      9432: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9433: # modify command to delete the role
1.620     albertel 9434:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9435:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9436: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9437: # set start and finish to negative values for userrolelog
                   9438:            $start=-1;
                   9439:            $end=-1;
1.957     raeburn  9440:            $delflag = 1;
1.357     www      9441:         }
                   9442:     }
                   9443: # send command
1.349     www      9444:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9445: # log new user role if status is ok
1.349     www      9446:     if ($answer eq 'ok') {
1.663     raeburn  9447: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9448:         if (($role eq 'cc') || ($role eq 'in') ||
                   9449:             ($role eq 'ep') || ($role eq 'ad') ||
                   9450:             ($role eq 'ta') || ($role eq 'st') ||
                   9451:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9452:             ($role eq 'co')) {
1.1200    raeburn  9453: # for course roles, perform group memberships changes triggered by role change.
                   9454:             unless ($role =~ /^gr/) {
                   9455:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9456:                                                  $origstart,$selfenroll,$context);
                   9457:             }
1.1184    raeburn  9458:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9459:                            $selfenroll,$context);
                   9460:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9461:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9462:                  ($role eq 'da')) {
1.1184    raeburn  9463:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9464:                            $context);
                   9465:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9466:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9467:                              $context); 
                   9468:         }
1.1053    raeburn  9469:         if ($role eq 'cc') {
                   9470:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9471:         }
1.349     www      9472:     }
                   9473:     return $answer;
1.169     harris41 9474: }
                   9475: 
1.1053    raeburn  9476: sub autoupdate_coowners {
                   9477:     my ($url,$end,$start,$uname,$udom) = @_;
                   9478:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9479:     if (($cdom ne '') && ($cnum ne '')) {
                   9480:         my $now = time;
                   9481:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9482:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9483:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9484:             my $instcode = $coursehash{'internal.coursecode'};
                   9485:             if ($instcode ne '') {
1.1056    raeburn  9486:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9487:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9488:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9489:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9490:                         if ($result eq 'valid') {
                   9491:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9492:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9493:                                     push(@newcoowners,$coowner);
                   9494:                                 }
                   9495:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9496:                                     push(@newcoowners,$uname.':'.$udom);
                   9497:                                 }
                   9498:                                 @newcoowners = sort(@newcoowners);
                   9499:                             } else {
                   9500:                                 push(@newcoowners,$uname.':'.$udom);
                   9501:                             }
                   9502:                         } else {
                   9503:                             if ($coursehash{'internal.co-owners'}) {
                   9504:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9505:                                     unless ($coowner eq $uname.':'.$udom) {
                   9506:                                         push(@newcoowners,$coowner);
                   9507:                                     }
                   9508:                                 }
                   9509:                                 unless (@newcoowners > 0) {
                   9510:                                     $delcoowners = 1;
                   9511:                                     $coowners = '';
                   9512:                                 }
                   9513:                             }
                   9514:                         }
                   9515:                         if (@newcoowners || $delcoowners) {
                   9516:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9517:                                             $delcoowners,@newcoowners);
                   9518:                         }
                   9519:                     }
                   9520:                 }
                   9521:             }
                   9522:         }
                   9523:     }
                   9524: }
                   9525: 
                   9526: sub store_coowners {
                   9527:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9528:     my $cid = $cdom.'_'.$cnum;
                   9529:     my ($coowners,$delresult,$putresult);
                   9530:     if (@newcoowners) {
                   9531:         $coowners = join(',',@newcoowners);
                   9532:         my %coownershash = (
                   9533:                             'internal.co-owners' => $coowners,
                   9534:                            );
                   9535:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9536:         if ($putresult eq 'ok') {
                   9537:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9538:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9539:             }
                   9540:         }
                   9541:     }
                   9542:     if ($delcoowners) {
                   9543:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9544:         if ($delresult eq 'ok') {
                   9545:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9546:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9547:             }
                   9548:         }
                   9549:     }
                   9550:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9551:         my %crsinfo =
                   9552:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9553:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9554:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9555:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9556:         }
                   9557:     }
                   9558: }
                   9559: 
1.169     harris41 9560: # -------------------------------------------------- Modify user authentication
1.197     www      9561: # Overrides without validation
                   9562: 
1.169     harris41 9563: sub modifyuserauth {
                   9564:     my ($udom,$uname,$umode,$upass)=@_;
                   9565:     my $uhome=&homeserver($uname,$udom);
1.197     www      9566:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9567:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9568:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9569:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9570:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9571: 		     &escape($upass),$uhome);
1.620     albertel 9572:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9573:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9574:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9575:     &log($udom,,$uname,$uhome,
1.620     albertel 9576:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9577:                                      $env{'user.name'}.', '.$umode.
1.197     www      9578:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9579:     unless ($reply eq 'ok') {
1.197     www      9580:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9581: 	return 'error: '.$reply;
                   9582:     }   
1.170     harris41 9583:     return 'ok';
1.80      www      9584: }
                   9585: 
1.81      www      9586: # --------------------------------------------------------------- Modify a user
1.80      www      9587: 
1.81      www      9588: sub modifyuser {
1.206     matthew  9589:     my ($udom,    $uname, $uid,
                   9590:         $umode,   $upass, $first,
                   9591:         $middle,  $last,  $gene,
1.1058    raeburn  9592:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9593:     $udom= &LONCAPA::clean_domain($udom);
                   9594:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9595:     my $showcandelete = 'none';
                   9596:     if (ref($candelete) eq 'ARRAY') {
                   9597:         if (@{$candelete} > 0) {
                   9598:             $showcandelete = join(', ',@{$candelete});
                   9599:         }
                   9600:     }
1.81      www      9601:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9602:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9603: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9604:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9605:                                      ' desiredhome not specified'). 
1.620     albertel 9606:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9607:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9608:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9609:     my $newuser;
                   9610:     if ($uhome eq 'no_host') {
                   9611:         $newuser = 1;
1.1368    raeburn  9612:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9613:                 ($umode eq 'lti')) {
                   9614:             return 'error: more information needed to create new user';
                   9615:         }
1.1075    raeburn  9616:     }
1.80      www      9617: # ----------------------------------------------------------------- Create User
1.406     albertel 9618:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9619: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9620:         my $unhome='';
1.844     albertel 9621:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9622:             $unhome = $desiredhome;
1.620     albertel 9623: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9624: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9625:         } else { # load balancing routine for determining $unhome
1.81      www      9626:             my $loadm=10000000;
1.841     albertel 9627: 	    my %servers = &get_servers($udom,'library');
                   9628: 	    foreach my $tryserver (keys(%servers)) {
                   9629: 		my $answer=reply('load',$tryserver);
                   9630: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9631: 		    $loadm=$answer;
                   9632: 		    $unhome=$tryserver;
                   9633: 		}
1.80      www      9634: 	    }
                   9635:         }
                   9636:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9637: 	    return 'error: unable to find a home server for '.$uname.
                   9638:                    ' in domain '.$udom;
1.80      www      9639:         }
                   9640:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9641:                          &escape($upass),$unhome);
                   9642: 	unless ($reply eq 'ok') {
                   9643:             return 'error: '.$reply;
                   9644:         }   
1.230     stredwic 9645:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9646:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9647: 	    return 'error: unable verify users home machine.';
1.80      www      9648:         }
1.209     matthew  9649:     }   # End of creation of new user
1.80      www      9650: # ---------------------------------------------------------------------- Add ID
                   9651:     if ($uid) {
                   9652:        $uid=~tr/A-Z/a-z/;
                   9653:        my %uidhash=&idrget($udom,$uname);
1.196     www      9654:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9655:          && (!$forceid)) {
1.80      www      9656: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9657: 	      return 'error: user id "'.$uid.'" does not match '.
                   9658:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9659:           }
                   9660:        } else {
1.1300    raeburn  9661: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9662:        }
                   9663:     }
                   9664: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9665:     my @tmp=&get('environment',
1.899     raeburn  9666: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9667:                     'permanentemail','inststatus'],
1.134     albertel 9668: 		   $udom,$uname);
1.1075    raeburn  9669:     my (%names,%oldnames);
1.313     matthew  9670:     if ($tmp[0] =~ m/^error:.*/) { 
                   9671:         %names=(); 
                   9672:     } else {
                   9673:         %names = @tmp;
1.1075    raeburn  9674:         %oldnames = %names;
1.313     matthew  9675:     }
1.388     www      9676: #
1.1058    raeburn  9677: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9678: # of users did not contain them), do not overwrite existing values
                   9679: # unless field is in $candelete array ref.  
                   9680: #
                   9681: 
                   9682:     my @fields = ('firstname','middlename','lastname','generation',
                   9683:                   'permanentemail','id');
                   9684:     my %newvalues;
                   9685:     if (ref($candelete) eq 'ARRAY') {
                   9686:         foreach my $field (@fields) {
                   9687:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9688:                 if ($field eq 'firstname') {
                   9689:                     $names{$field} = $first;
                   9690:                 } elsif ($field eq 'middlename') {
                   9691:                     $names{$field} = $middle;
                   9692:                 } elsif ($field eq 'lastname') {
                   9693:                     $names{$field} = $last;
                   9694:                 } elsif ($field eq 'generation') { 
                   9695:                     $names{$field} = $gene;
                   9696:                 } elsif ($field eq 'permanentemail') {
                   9697:                     $names{$field} = $email;
                   9698:                 } elsif ($field eq 'id') {
                   9699:                     $names{$field}  = $uid;
                   9700:                 }
                   9701:             }
                   9702:         }
                   9703:     }
1.388     www      9704:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9705:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9706:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9707:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9708:     if ($email) {
                   9709:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9710:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9711:     }
1.899     raeburn  9712:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9713:     if (defined($inststatus)) {
                   9714:         $names{'inststatus'} = '';
                   9715:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9716:         if (ref($usertypes) eq 'HASH') {
                   9717:             my @okstatuses; 
                   9718:             foreach my $item (split(/:/,$inststatus)) {
                   9719:                 if (defined($usertypes->{$item})) {
                   9720:                     push(@okstatuses,$item);  
                   9721:                 }
                   9722:             }
                   9723:             if (@okstatuses) {
                   9724:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9725:             }
                   9726:         }
                   9727:     }
1.1075    raeburn  9728:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9729:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9730:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9731:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9732:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9733:     } else {
                   9734:         $logmsg .= ' during self creation';
                   9735:     }
1.1075    raeburn  9736:     my $changed;
                   9737:     if ($newuser) {
                   9738:         $changed = 1;
                   9739:     } else {
                   9740:         foreach my $field (@fields) {
                   9741:             if ($names{$field} ne $oldnames{$field}) {
                   9742:                 $changed = 1;
                   9743:                 last;
                   9744:             }
                   9745:         }
                   9746:     }
                   9747:     unless ($changed) {
                   9748:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9749:         &logthis($logmsg);
                   9750:         return 'ok';
                   9751:     }
                   9752:     my $reply = &put('environment', \%names, $udom,$uname);
                   9753:     if ($reply ne 'ok') { 
                   9754:         return 'error: '.$reply;
                   9755:     }
1.1087    raeburn  9756:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9757:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9758:     }
1.1075    raeburn  9759:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9760:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9761:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9762:     &logthis($logmsg);
1.134     albertel 9763:     return 'ok';
1.80      www      9764: }
                   9765: 
1.81      www      9766: # -------------------------------------------------------------- Modify student
1.80      www      9767: 
1.81      www      9768: sub modifystudent {
                   9769:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9770:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9771:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9772:     if (!$cid) {
1.620     albertel 9773: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9774: 	    return 'not_in_class';
                   9775: 	}
1.80      www      9776:     }
                   9777: # --------------------------------------------------------------- Make the user
1.81      www      9778:     my $reply=&modifyuser
1.209     matthew  9779: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9780:          $desiredhome,$email,$inststatus);
1.80      www      9781:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9782:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9783:     # student's environment
1.297     matthew  9784:     $uid = undef if (!$forceid);
1.455     albertel 9785:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9786:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9787:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9788:     return $reply;
                   9789: }
                   9790: 
                   9791: sub modify_student_enrollment {
1.1216    raeburn  9792:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9793:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9794:     my ($cdom,$cnum,$chome);
                   9795:     if (!$cid) {
1.620     albertel 9796: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9797: 	    return 'not_in_class';
                   9798: 	}
1.620     albertel 9799: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9800: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9801:     } else {
                   9802: 	($cdom,$cnum)=split(/_/,$cid);
                   9803:     }
1.620     albertel 9804:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9805:     if (!$chome) {
1.457     raeburn  9806: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9807:     }
1.455     albertel 9808:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9809:     # Make sure the user exists
1.81      www      9810:     my $uhome=&homeserver($uname,$udom);
                   9811:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9812: 	return 'error: no such user';
                   9813:     }
1.297     matthew  9814:     # Get student data if we were not given enough information
                   9815:     if (!defined($first)  || $first  eq '' || 
                   9816:         !defined($last)   || $last   eq '' || 
                   9817:         !defined($uid)    || $uid    eq '' || 
                   9818:         !defined($middle) || $middle eq '' || 
                   9819:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9820:         # They did not supply us with enough data to enroll the student, so
                   9821:         # we need to pick up more information.
1.297     matthew  9822:         my %tmp = &get('environment',
1.294     matthew  9823:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9824:                        ,$udom,$uname);
                   9825: 
1.800     albertel 9826:         #foreach my $key (keys(%tmp)) {
                   9827:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9828:         #}
1.294     matthew  9829:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9830:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9831:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9832:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9833:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9834:     }
1.556     albertel 9835:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9836:     my $user = "$uname:$udom";
                   9837:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9838:     my $reply=cput('classlist',
1.1148    raeburn  9839: 		   {$user => 
1.1314    raeburn  9840: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9841: 		   $cdom,$cnum);
1.1148    raeburn  9842:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9843:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9844:     } else { 
1.81      www      9845: 	return 'error: '.$reply;
                   9846:     }
1.297     matthew  9847:     # Add student role to user
1.83      www      9848:     my $uurl='/'.$cid;
1.81      www      9849:     $uurl=~s/\_/\//g;
                   9850:     if ($usec) {
                   9851: 	$uurl.='/'.$usec;
                   9852:     }
1.1148    raeburn  9853:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9854:                              $selfenroll,$context);
                   9855:     if ($result ne 'ok') {
                   9856:         if ($old_entry{$user} ne '') {
                   9857:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9858:         } else {
                   9859:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9860:         }
                   9861:     }
                   9862:     return $result; 
1.21      www      9863: }
                   9864: 
1.556     albertel 9865: sub format_name {
                   9866:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9867:     my $name;
                   9868:     if ($first ne 'lastname') {
                   9869: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9870:     } else {
                   9871: 	if ($lastname=~/\S/) {
                   9872: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9873: 	    $name=~s/\s+,/,/;
                   9874: 	} else {
                   9875: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9876: 	}
                   9877:     }
                   9878:     $name=~s/^\s+//;
                   9879:     $name=~s/\s+$//;
                   9880:     $name=~s/\s+/ /g;
                   9881:     return $name;
                   9882: }
                   9883: 
1.84      www      9884: # ------------------------------------------------- Write to course preferences
                   9885: 
                   9886: sub writecoursepref {
                   9887:     my ($courseid,%prefs)=@_;
                   9888:     $courseid=~s/^\///;
                   9889:     $courseid=~s/\_/\//g;
                   9890:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9891:     my $chome=homeserver($cnum,$cdomain);
                   9892:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9893: 	return 'error: no such course';
                   9894:     }
                   9895:     my $cstring='';
1.800     albertel 9896:     foreach my $pref (keys(%prefs)) {
                   9897: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9898:     }
1.84      www      9899:     $cstring=~s/\&$//;
                   9900:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9901: }
                   9902: 
                   9903: # ---------------------------------------------------------- Make/modify course
                   9904: 
                   9905: sub createcourse {
1.741     raeburn  9906:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9907:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9908:     $url=&declutter($url);
                   9909:     my $cid='';
1.1028    raeburn  9910:     if ($context eq 'requestcourses') {
                   9911:         my $can_create = 0;
                   9912:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9913:         if ($udom eq $ownerdom) {
                   9914:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9915:                                   $context)) {
                   9916:                 $can_create = 1;
                   9917:             }
                   9918:         } else {
                   9919:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9920:                                            $category);
                   9921:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9922:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9923:                 if (@curr > 0) {
                   9924:                     my @options = qw(approval validate autolimit);
                   9925:                     my $optregex = join('|',@options);
                   9926:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9927:                         $can_create = 1;
                   9928:                     }
                   9929:                 }
                   9930:             }
                   9931:         }
                   9932:         if ($can_create) {
                   9933:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9934:                 unless (&allowed('ccc',$udom)) {
                   9935:                     return 'refused'; 
                   9936:                 }
1.1017    raeburn  9937:             }
                   9938:         } else {
                   9939:             return 'refused';
                   9940:         }
1.1028    raeburn  9941:     } elsif (!&allowed('ccc',$udom)) {
                   9942:         return 'refused';
1.84      www      9943:     }
1.1011    raeburn  9944: # --------------------------------------------------------------- Get Unique ID
                   9945:     my $uname;
                   9946:     if ($cnum =~ /^$match_courseid$/) {
                   9947:         my $chome=&homeserver($cnum,$udom,'true');
                   9948:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9949:             $uname = $cnum;
                   9950:         } else {
1.1038    raeburn  9951:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9952:         }
                   9953:     } else {
1.1038    raeburn  9954:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9955:     }
                   9956:     return $uname if ($uname =~ /^error/);
                   9957: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9958:     if (!defined($course_server)) {
                   9959:         if (defined(&domain($udom,'primary'))) {
                   9960:             $course_server = &domain($udom,'primary');
                   9961:         } else {
                   9962:             $course_server = $env{'user.home'}; 
                   9963:         }
                   9964:     }
                   9965:     my %host_servers =
                   9966:         &Apache::lonnet::get_servers($udom,'library');
                   9967:     unless ($host_servers{$course_server}) {
                   9968:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9969:     }
1.84      www      9970: # ------------------------------------------------------------- Make the course
                   9971:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9972:                       $course_server);
1.84      www      9973:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9974:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9975:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9976: 	return 'error: no such course';
                   9977:     }
1.271     www      9978: # ----------------------------------------------------------------- Course made
1.516     raeburn  9979: # log existence
1.1029    raeburn  9980:     my $now = time;
1.918     raeburn  9981:     my $newcourse = {
                   9982:                     $udom.'_'.$uname => {
1.921     raeburn  9983:                                      description => $description,
                   9984:                                      inst_code   => $inst_code,
                   9985:                                      owner       => $course_owner,
                   9986:                                      type        => $crstype,
1.1029    raeburn  9987:                                      creator     => $env{'user.name'}.':'.
                   9988:                                                     $env{'user.domain'},
                   9989:                                      created     => $now,
                   9990:                                      context     => $context,
1.918     raeburn  9991:                                                 },
                   9992:                     };
1.921     raeburn  9993:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9994: # set toplevel url
1.271     www      9995:     my $topurl=$url;
                   9996:     unless ($nonstandard) {
                   9997: # ------------------------------------------ For standard courses, make top url
                   9998:         my $mapurl=&clutter($url);
1.278     www      9999:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10000:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10001: <map>
                   10002: <resource id="1" type="start"></resource>
                   10003: <resource id="2" src="$mapurl"></resource>
                   10004: <resource id="3" type="finish"></resource>
                   10005: <link index="1" from="1" to="2"></link>
                   10006: <link index="2" from="2" to="3"></link>
                   10007: </map>
                   10008: ENDINITMAP
                   10009:         $topurl=&declutter(
1.638     albertel 10010:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10011:                           );
                   10012:     }
                   10013: # ----------------------------------------------------------- Write preferences
1.84      www      10014:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10015:                      ('description'              => $description,
                   10016:                       'url'                      => $topurl,
                   10017:                       'internal.creator'         => $env{'user.name'}.':'.
                   10018:                                                     $env{'user.domain'},
                   10019:                       'internal.created'         => $now,
                   10020:                       'internal.creationcontext' => $context)
                   10021:                     );
1.84      www      10022:     return '/'.$udom.'/'.$uname;
                   10023: }
                   10024: 
1.1011    raeburn  10025: # ------------------------------------------------------------------- Create ID
                   10026: sub generate_coursenum {
1.1038    raeburn  10027:     my ($udom,$crstype) = @_;
1.1011    raeburn  10028:     my $domdesc = &domain($udom);
                   10029:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10030:     my $first;
                   10031:     if ($crstype eq 'Community') {
                   10032:         $first = '0';
                   10033:     } else {
                   10034:         $first = int(1+rand(9)); 
                   10035:     } 
                   10036:     my $uname=$first.
1.1011    raeburn  10037:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10038:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10039:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10040: # ----------------------------------------------- Make sure that does not exist
                   10041:     my $uhome=&homeserver($uname,$udom,'true');
                   10042:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10043:         if ($crstype eq 'Community') {
                   10044:             $first = '0';
                   10045:         } else {
                   10046:             $first = int(1+rand(9));
                   10047:         }
                   10048:         $uname=$first.
1.1011    raeburn  10049:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10050:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10051:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10052:         $uhome=&homeserver($uname,$udom,'true');
                   10053:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10054:             return 'error: unable to generate unique course-ID';
                   10055:         }
                   10056:     }
                   10057:     return $uname;
                   10058: }
                   10059: 
1.813     albertel 10060: sub is_course {
1.1167    droeschl 10061:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10062:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10063: 
1.1381    raeburn  10064:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10065:     my $uhome=&homeserver($cnum,$cdom);
                   10066:     my $iscourse;
                   10067:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10068:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10069:     } else {
                   10070:         my $hashid = $cdom.':'.$cnum;
                   10071:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10072:         unless (defined($cached)) {
                   10073:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10074:                                         $cnum,undef,undef,'.');
                   10075:             $iscourse = 0;
                   10076:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10077:                 $iscourse = 1;
                   10078:             }
                   10079:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10080:         }
                   10081:     }
                   10082:     return unless ($iscourse);
1.1167    droeschl 10083:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10084: }
                   10085: 
1.1015    raeburn  10086: sub store_userdata {
                   10087:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10088:     my $result;
1.1016    raeburn  10089:     if ($datakey ne '') {
1.1013    raeburn  10090:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10091:             if ($udom eq '' || $uname eq '') {
                   10092:                 $udom = $env{'user.domain'};
                   10093:                 $uname = $env{'user.name'};
                   10094:             }
                   10095:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10096:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10097:                 $result = 'error: no_host';
                   10098:             } else {
                   10099:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10100:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10101: 
                   10102:                 my $namevalue='';
                   10103:                 foreach my $key (keys(%{$storehash})) {
                   10104:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10105:                 }
                   10106:                 $namevalue=~s/\&$//;
1.1224    raeburn  10107:                 unless ($namespace eq 'courserequests') {
                   10108:                     $datakey = &escape($datakey);
                   10109:                 }
1.1105    raeburn  10110:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10111:                                   $namevalue,$uhome);
1.1013    raeburn  10112:             }
                   10113:         } else {
                   10114:             $result = 'error: data to store was not a hash reference'; 
                   10115:         }
                   10116:     } else {
                   10117:         $result= 'error: invalid requestkey'; 
                   10118:     }
                   10119:     return $result;
                   10120: }
                   10121: 
1.21      www      10122: # ---------------------------------------------------------- Assign Custom Role
                   10123: 
                   10124: sub assigncustomrole {
1.957     raeburn  10125:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10126:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10127:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10128: }
                   10129: 
                   10130: # ----------------------------------------------------------------- Revoke Role
                   10131: 
                   10132: sub revokerole {
1.957     raeburn  10133:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10134:     my $now=time;
1.965     raeburn  10135:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10136: }
                   10137: 
                   10138: # ---------------------------------------------------------- Revoke Custom Role
                   10139: 
                   10140: sub revokecustomrole {
1.957     raeburn  10141:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10142:     my $now=time;
1.357     www      10143:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10144:            $deleteflag,$selfenroll,$context);
1.17      www      10145: }
                   10146: 
1.533     banghart 10147: # ------------------------------------------------------------ Disk usage
1.535     albertel 10148: sub diskusage {
1.955     raeburn  10149:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10150:     $directorypath =~ s/\/$//;
                   10151:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10152:                        .&escape($getpropath).':'.&escape($uname).':'
                   10153:                        .&escape($udom),homeserver($uname,$udom));
                   10154:     if ($listing eq 'unknown_cmd') {
                   10155:         if ($getpropath) {
                   10156:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10157:         }
                   10158:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10159:     }
1.514     albertel 10160:     return $listing;
1.512     banghart 10161: }
                   10162: 
1.566     banghart 10163: sub is_locked {
1.1096    raeburn  10164:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10165:     my @check;
                   10166:     my $is_locked;
1.1093    raeburn  10167:     push (@check,$file_name);
1.613     albertel 10168:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10169: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10170:     my ($tmp)=keys(%locked);
                   10171:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10172:     
1.566     banghart 10173:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10174:         $is_locked = 'false';
                   10175:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10176:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10177:                $is_locked = 'true';
1.1096    raeburn  10178:                if (ref($which) eq 'ARRAY') {
                   10179:                    push(@{$which},$entry);
                   10180:                } else {
                   10181:                    last;
                   10182:                }
1.745     raeburn  10183:            }
                   10184:        }
1.566     banghart 10185:     } else {
                   10186:         $is_locked = 'false';
                   10187:     }
1.1093    raeburn  10188:     return $is_locked;
1.566     banghart 10189: }
                   10190: 
1.759     albertel 10191: sub declutter_portfile {
                   10192:     my ($file) = @_;
1.833     albertel 10193:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10194:     return $file;
                   10195: }
                   10196: 
1.559     banghart 10197: # ------------------------------------------------------------- Mark as Read Only
                   10198: 
                   10199: sub mark_as_readonly {
                   10200:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10201:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10202:     my ($tmp)=keys(%current_permissions);
                   10203:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10204:     foreach my $file (@{$files}) {
1.759     albertel 10205: 	$file = &declutter_portfile($file);
1.561     banghart 10206:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10207:     }
1.613     albertel 10208:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10209:     return;
                   10210: }
                   10211: 
1.572     banghart 10212: # ------------------------------------------------------------Save Selected Files
                   10213: 
                   10214: sub save_selected_files {
                   10215:     my ($user, $path, @files) = @_;
                   10216:     my $filename = $user."savedfiles";
1.573     banghart 10217:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10218:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10219:     foreach my $file (@files) {
1.620     albertel 10220:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10221:     }
                   10222:     foreach my $file (@other_files) {
1.574     banghart 10223:         print (OUT $file."\n");
1.572     banghart 10224:     }
1.574     banghart 10225:     close (OUT);
1.572     banghart 10226:     return 'ok';
                   10227: }
                   10228: 
1.574     banghart 10229: sub clear_selected_files {
                   10230:     my ($user) = @_;
                   10231:     my $filename = $user."savedfiles";
1.1359    raeburn  10232:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10233:     print (OUT undef);
                   10234:     close (OUT);
                   10235:     return ("ok");    
                   10236: }
                   10237: 
1.572     banghart 10238: sub files_in_path {
                   10239:     my ($user, $path) = @_;
                   10240:     my $filename = $user."savedfiles";
                   10241:     my %return_files;
1.1359    raeburn  10242:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10243:     while (my $line_in = <IN>) {
1.574     banghart 10244:         chomp ($line_in);
                   10245:         my @paths_and_file = split (m!/!, $line_in);
                   10246:         my $file_part = pop (@paths_and_file);
                   10247:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10248:         $path_part.='/';
                   10249:         my $path_and_file = $path_part.$file_part;
                   10250:         if ($path_part eq $path) {
                   10251:             $return_files{$file_part}= 'selected';
                   10252:         }
                   10253:     }
1.574     banghart 10254:     close (IN);
                   10255:     return (\%return_files);
1.572     banghart 10256: }
                   10257: 
                   10258: # called in portfolio select mode, to show files selected NOT in current directory
                   10259: sub files_not_in_path {
                   10260:     my ($user, $path) = @_;
                   10261:     my $filename = $user."savedfiles";
                   10262:     my @return_files;
                   10263:     my $path_part;
1.1359    raeburn  10264:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10265:     while (my $line = <IN>) {
1.572     banghart 10266:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10267:         my @paths_and_file = split(m|/|, $line);
                   10268:         my $file_part = pop(@paths_and_file);
                   10269:         chomp($file_part);
                   10270:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10271:         $path_part .= '/';
                   10272:         my $path_and_file = $path_part.$file_part;
                   10273:         if ($path_part ne $path) {
1.800     albertel 10274:             push(@return_files, ($path_and_file));
1.572     banghart 10275:         }
                   10276:     }
1.800     albertel 10277:     close(OUT);
1.574     banghart 10278:     return (@return_files);
1.572     banghart 10279: }
                   10280: 
1.1273    raeburn  10281: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10282:  
                   10283: sub portfiles_versioning {
                   10284:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10285:     my $portfolio_root = '/userfiles/portfolio';
                   10286:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10287:     foreach my $file (@{$portfiles}) {
                   10288:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10289:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10290:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10291:         my $getpropath = 1;
                   10292:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10293:                                              $stu_name,$getpropath);
                   10294:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10295:         my $new_answer = 
                   10296:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10297:         if ($new_answer ne 'problem getting file') {
                   10298:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10299:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10300:                               [$symb,$env{'request.course.id'},'graded']);
                   10301:         }
                   10302:     }
                   10303: }
                   10304: 
                   10305: sub get_next_version {
                   10306:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10307:     my $version;
                   10308:     if (ref($dir_list) eq 'ARRAY') {
                   10309:         foreach my $row (@{$dir_list}) {
                   10310:             my ($file) = split(/\&/,$row,2);
                   10311:             my ($file_name,$file_version,$file_ext) =
                   10312:                 &file_name_version_ext($file);
                   10313:             if (($file_name eq $answer_name) &&
                   10314:                 ($file_ext eq $answer_ext)) {
                   10315:                      # gets here if filename and extension match,
                   10316:                      # regardless of version
                   10317:                 if ($file_version ne '') {
                   10318:                     # a versioned file is found  so save it for later
                   10319:                     if ($file_version > $version) {
                   10320:                         $version = $file_version;
                   10321:                     }
                   10322:                 }
                   10323:             }
                   10324:         }
                   10325:     }
                   10326:     $version ++;
                   10327:     return($version);
                   10328: }
                   10329: 
                   10330: sub version_selected_portfile {
                   10331:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10332:     my ($answer_name,$answer_ver,$answer_ext) =
                   10333:         &file_name_version_ext($file_name);
                   10334:     my $new_answer;
                   10335:     $env{'form.copy'} =
                   10336:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10337:     if($env{'form.copy'} eq '-1') {
                   10338:         $new_answer = 'problem getting file';
                   10339:     } else {
                   10340:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10341:         my $copy_result = 
                   10342:             &finishuserfileupload($stu_name,$domain,'copy',
                   10343:                                   '/portfolio'.$directory.$new_answer);
                   10344:     }
                   10345:     undef($env{'form.copy'});
                   10346:     return ($new_answer);
                   10347: }
                   10348: 
                   10349: sub file_name_version_ext {
                   10350:     my ($file)=@_;
                   10351:     my @file_parts = split(/\./, $file);
                   10352:     my ($name,$version,$ext);
                   10353:     if (@file_parts > 1) {
                   10354:         $ext=pop(@file_parts);
                   10355:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10356:             $version=pop(@file_parts);
                   10357:         }
                   10358:         $name=join('.',@file_parts);
                   10359:     } else {
                   10360:         $name=join('.',@file_parts);
                   10361:     }
                   10362:     return($name,$version,$ext);
                   10363: }
                   10364: 
1.745     raeburn  10365: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10366: 
1.745     raeburn  10367: sub get_portfile_permissions {
                   10368:     my ($domain,$user) = @_;
1.613     albertel 10369:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10370:     my ($tmp)=keys(%current_permissions);
                   10371:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10372:     return \%current_permissions;
                   10373: }
                   10374: 
                   10375: #---------------------------------------------Get portfolio file access controls
                   10376: 
1.749     raeburn  10377: sub get_access_controls {
1.745     raeburn  10378:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10379:     my %access;
                   10380:     my $real_file = $file;
                   10381:     $file =~ s/\.meta$//;
1.745     raeburn  10382:     if (defined($file)) {
1.749     raeburn  10383:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10384:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10385:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10386:             }
                   10387:         }
1.745     raeburn  10388:     } else {
1.749     raeburn  10389:         foreach my $key (keys(%{$current_permissions})) {
                   10390:             if ($key =~ /\0accesscontrol$/) {
                   10391:                 if (defined($group)) {
                   10392:                     if ($key !~ m-^\Q$group\E/-) {
                   10393:                         next;
                   10394:                     }
                   10395:                 }
                   10396:                 my ($fullpath) = split(/\0/,$key);
                   10397:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10398:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10399:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10400:                     }
                   10401:                 }
                   10402:             }
                   10403:         }
                   10404:     }
                   10405:     return %access;
                   10406: }
                   10407: 
                   10408: sub modify_access_controls {
                   10409:     my ($file_name,$changes,$domain,$user)=@_;
                   10410:     my ($outcome,$deloutcome);
                   10411:     my %store_permissions;
                   10412:     my %new_values;
                   10413:     my %new_control;
                   10414:     my %translation;
                   10415:     my @deletions = ();
                   10416:     my $now = time;
                   10417:     if (exists($$changes{'activate'})) {
                   10418:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10419:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10420:             my $numnew = scalar(@newitems);
                   10421:             for (my $i=0; $i<$numnew; $i++) {
                   10422:                 my $newkey = $newitems[$i];
                   10423:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10424:                 if ($newkey =~ /^\d+:/) { 
                   10425:                     $newkey =~ s/^(\d+)/$newid/;
                   10426:                     $translation{$1} = $newid;
                   10427:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10428:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10429:                     $translation{$1} = $newid;
                   10430:                 }
1.749     raeburn  10431:                 $new_values{$file_name."\0".$newkey} = 
                   10432:                                           $$changes{'activate'}{$newitems[$i]};
                   10433:                 $new_control{$newkey} = $now;
                   10434:             }
                   10435:         }
                   10436:     }
                   10437:     my %todelete;
                   10438:     my %changed_items;
                   10439:     foreach my $action ('delete','update') {
                   10440:         if (exists($$changes{$action})) {
                   10441:             if (ref($$changes{$action}) eq 'HASH') {
                   10442:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10443:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10444:                     if ($action eq 'delete') { 
                   10445:                         $todelete{$itemnum} = 1;
                   10446:                     } else {
                   10447:                         $changed_items{$itemnum} = $key;
                   10448:                     }
                   10449:                 }
1.745     raeburn  10450:             }
                   10451:         }
1.749     raeburn  10452:     }
                   10453:     # get lock on access controls for file.
                   10454:     my $lockhash = {
                   10455:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10456:                                                        ':'.$env{'user.domain'},
                   10457:                    }; 
                   10458:     my $tries = 0;
                   10459:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10460:    
1.1288    damieng  10461:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10462:         $tries ++;
1.1289    damieng  10463:         sleep(0.1);
1.749     raeburn  10464:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10465:     }
                   10466:     if ($gotlock eq 'ok') {
                   10467:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10468:         my ($tmp)=keys(%curr_permissions);
                   10469:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10470:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10471:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10472:             if (ref($curr_controls) eq 'HASH') {
                   10473:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10474:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10475:                     if (defined($todelete{$itemnum})) {
                   10476:                         push(@deletions,$file_name."\0".$control_item);
                   10477:                     } else {
                   10478:                         if (defined($changed_items{$itemnum})) {
                   10479:                             $new_control{$changed_items{$itemnum}} = $now;
                   10480:                             push(@deletions,$file_name."\0".$control_item);
                   10481:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10482:                         } else {
                   10483:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10484:                         }
                   10485:                     }
1.745     raeburn  10486:                 }
                   10487:             }
                   10488:         }
1.970     raeburn  10489:         my ($group);
                   10490:         if (&is_course($domain,$user)) {
                   10491:             ($group,my $file) = split(/\//,$file_name,2);
                   10492:         }
1.749     raeburn  10493:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10494:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10495:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10496:         #  remove lock
                   10497:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10498:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10499:         my $sqlresult =
1.970     raeburn  10500:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10501:                                     $group);
1.749     raeburn  10502:     } else {
                   10503:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10504:     }
1.749     raeburn  10505:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10506: }
                   10507: 
1.827     raeburn  10508: sub make_public_indefinitely {
1.1271    raeburn  10509:     my (@requrl) = @_;
                   10510:     return &automated_portfile_access('public',\@requrl);
                   10511: }
                   10512: 
                   10513: sub automated_portfile_access {
                   10514:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10515:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10516:         return 'invalid';
                   10517:     }
1.1271    raeburn  10518:     my %urls;
                   10519:     if (ref($addsref) eq 'ARRAY') {
                   10520:         foreach my $requrl (@{$addsref}) {
                   10521:             if (&is_portfolio_url($requrl)) {
                   10522:                 unless (exists($urls{$requrl})) {
                   10523:                     $urls{$requrl} = 'add';
                   10524:                 }
                   10525:             }
                   10526:         }
                   10527:     }
                   10528:     if (ref($delsref) eq 'ARRAY') {
                   10529:         foreach my $requrl (@{$delsref}) { 
                   10530:             if (&is_portfolio_url($requrl)) {
                   10531:                 unless (exists($urls{$requrl})) {
                   10532:                     $urls{$requrl} = 'delete'; 
                   10533:                 }
                   10534:             }
                   10535:         }
                   10536:     }
                   10537:     unless (keys(%urls)) {
                   10538:         return 'invalid';
                   10539:     }
                   10540:     my $ip;
                   10541:     if ($accesstype eq 'ip') {
                   10542:         if (ref($info) eq 'HASH') {
                   10543:             if ($info->{'ip'} ne '') {
                   10544:                 $ip = $info->{'ip'};
                   10545:             }
                   10546:         }
                   10547:         if ($ip eq '') {
                   10548:             return 'invalid';
                   10549:         }
                   10550:     }
                   10551:     my $errors;
1.827     raeburn  10552:     my $now = time;
1.1271    raeburn  10553:     my %current_perms;
                   10554:     foreach my $requrl (sort(keys(%urls))) {
                   10555:         my $action;
                   10556:         if ($urls{$requrl} eq 'add') {
                   10557:             $action = 'activate';
                   10558:         } else {
                   10559:             $action = 'none';
                   10560:         }
                   10561:         my $aclnum = 0;
1.827     raeburn  10562:         my (undef,$udom,$unum,$file_name,$group) =
                   10563:             &parse_portfolio_url($requrl);
1.1271    raeburn  10564:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10565:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10566:         }
                   10567:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10568:                                                    $group,$file_name);
                   10569:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10570:             my ($num,$scope,$end,$start) = 
                   10571:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10572:             if ($scope eq $accesstype) {
                   10573:                 if (($start <= $now) && ($end == 0)) {
                   10574:                     if ($accesstype eq 'ip') {
                   10575:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10576:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10577:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10578:                                     if ($urls{$requrl} eq 'add') {
                   10579:                                         $action = 'none';
                   10580:                                         last;
                   10581:                                     } else {
                   10582:                                         $action = 'delete';
                   10583:                                         $aclnum = $num;
                   10584:                                         last;
                   10585:                                     }
                   10586:                                 }
                   10587:                             }
                   10588:                         }
                   10589:                     } elsif ($accesstype eq 'public') {
                   10590:                         if ($urls{$requrl} eq 'add') {
                   10591:                             $action = 'none';
                   10592:                             last;
                   10593:                         } else {
                   10594:                             $action = 'delete';
                   10595:                             $aclnum = $num;
                   10596:                             last;
                   10597:                         }
                   10598:                     }
                   10599:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10600:                     $action = 'update';
                   10601:                     $aclnum = $num;
1.1271    raeburn  10602:                     last;
1.827     raeburn  10603:                 }
                   10604:             }
                   10605:         }
                   10606:         if ($action eq 'none') {
1.1271    raeburn  10607:             next;
1.827     raeburn  10608:         } else {
                   10609:             my %changes;
                   10610:             my $newend = 0;
                   10611:             my $newstart = $now;
1.1271    raeburn  10612:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10613:             $changes{$action}{$newkey} = {
1.1271    raeburn  10614:                 type => $accesstype,
1.827     raeburn  10615:                 time => {
                   10616:                     start => $newstart,
                   10617:                     end   => $newend,
                   10618:                 },
                   10619:             };
1.1271    raeburn  10620:             if ($accesstype eq 'ip') {
                   10621:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10622:             }
1.827     raeburn  10623:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10624:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10625:             unless ($outcome eq 'ok') {
                   10626:                 $errors .= $outcome.' ';
                   10627:             }
1.827     raeburn  10628:         }
1.1271    raeburn  10629:     }
                   10630:     if ($errors) {
                   10631:         $errors =~ s/\s$//;
                   10632:         return $errors;
1.827     raeburn  10633:     } else {
1.1271    raeburn  10634:         return 'ok';
1.827     raeburn  10635:     }
                   10636: }
                   10637: 
1.745     raeburn  10638: #------------------------------------------------------Get Marked as Read Only
                   10639: 
                   10640: sub get_marked_as_readonly {
                   10641:     my ($domain,$user,$what,$group) = @_;
                   10642:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10643:     my @readonly_files;
1.629     banghart 10644:     my $cmp1=$what;
                   10645:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10646:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10647:         if (defined($group)) {
                   10648:             if ($file_name !~ m-^\Q$group\E/-) {
                   10649:                 next;
                   10650:             }
                   10651:         }
1.561     banghart 10652:         if (ref($value) eq "ARRAY"){
                   10653:             foreach my $stored_what (@{$value}) {
1.629     banghart 10654:                 my $cmp2=$stored_what;
1.759     albertel 10655:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10656:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10657:                 }
1.629     banghart 10658:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10659:                     push(@readonly_files, $file_name);
1.745     raeburn  10660:                     last;
1.563     banghart 10661:                 } elsif (!defined($what)) {
                   10662:                     push(@readonly_files, $file_name);
1.745     raeburn  10663:                     last;
1.561     banghart 10664:                 }
                   10665:             }
1.745     raeburn  10666:         }
1.561     banghart 10667:     }
                   10668:     return @readonly_files;
                   10669: }
1.577     banghart 10670: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10671: 
1.577     banghart 10672: sub get_marked_as_readonly_hash {
1.745     raeburn  10673:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10674:     my %readonly_files;
1.745     raeburn  10675:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10676:         if (defined($group)) {
                   10677:             if ($file_name !~ m-^\Q$group\E/-) {
                   10678:                 next;
                   10679:             }
                   10680:         }
1.577     banghart 10681:         if (ref($value) eq "ARRAY"){
                   10682:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10683:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10684:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10685:                         if ($lock_descriptor eq 'graded') {
                   10686:                             $readonly_files{$file_name} = 'graded';
                   10687:                         } elsif ($lock_descriptor eq 'handback') {
                   10688:                             $readonly_files{$file_name} = 'handback';
                   10689:                         } else {
                   10690:                             if (!exists($readonly_files{$file_name})) {
                   10691:                                 $readonly_files{$file_name} = 'locked';
                   10692:                             }
                   10693:                         }
1.745     raeburn  10694:                     }
1.750     banghart 10695:                 } 
1.577     banghart 10696:             }
                   10697:         } 
                   10698:     }
                   10699:     return %readonly_files;
                   10700: }
1.559     banghart 10701: # ------------------------------------------------------------ Unmark as Read Only
                   10702: 
                   10703: sub unmark_as_readonly {
1.629     banghart 10704:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10705:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10706:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10707:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10708:     my $symb_crs = $what;
                   10709:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10710:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10711:     my ($tmp)=keys(%current_permissions);
                   10712:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10713:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10714:     foreach my $file (@readonly_files) {
1.759     albertel 10715: 	my $clean_file = &declutter_portfile($file);
                   10716: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10717: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10718:         my @new_locks;
                   10719:         my @del_keys;
                   10720:         if (ref($current_locks) eq "ARRAY"){
                   10721:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10722:                 my $compare=$locker;
1.749     raeburn  10723:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10724:                     $compare=join('',@{$locker});
1.746     raeburn  10725:                     if ($compare ne $symb_crs) {
                   10726:                         push(@new_locks, $locker);
                   10727:                     }
1.563     banghart 10728:                 }
                   10729:             }
1.650     albertel 10730:             if (scalar(@new_locks) > 0) {
1.563     banghart 10731:                 $current_permissions{$file} = \@new_locks;
                   10732:             } else {
                   10733:                 push(@del_keys, $file);
1.613     albertel 10734:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10735:                 delete($current_permissions{$file});
1.563     banghart 10736:             }
                   10737:         }
1.561     banghart 10738:     }
1.613     albertel 10739:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10740:     return;
                   10741: }
1.512     banghart 10742: 
1.17      www      10743: # ------------------------------------------------------------ Directory lister
                   10744: 
                   10745: sub dirlist {
1.955     raeburn  10746:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10747:     $uri=~s/^\///;
                   10748:     $uri=~s/\/$//;
1.253     stredwic 10749:     my ($udom, $uname);
1.955     raeburn  10750:     if ($getuserdir) {
1.253     stredwic 10751:         $udom = $userdomain;
                   10752:         $uname = $username;
1.955     raeburn  10753:     } else {
                   10754:         (undef,$udom,$uname)=split(/\//,$uri);
                   10755:         if(defined($userdomain)) {
                   10756:             $udom = $userdomain;
                   10757:         }
                   10758:         if(defined($username)) {
                   10759:             $uname = $username;
                   10760:         }
1.253     stredwic 10761:     }
1.955     raeburn  10762:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10763: 
1.955     raeburn  10764:     $dirRoot = $perlvar{'lonDocRoot'};
                   10765:     if (defined($getpropath)) {
                   10766:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10767:         $dirRoot =~ s/\/$//;
1.955     raeburn  10768:     } elsif (defined($getuserdir)) {
                   10769:         my $subdir=$uname.'__';
                   10770:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10771:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10772:                    ."/$udom/$subdir/$uname";
                   10773:     } elsif (defined($alternateRoot)) {
                   10774:         $dirRoot = $alternateRoot;
1.751     banghart 10775:     }
1.253     stredwic 10776: 
                   10777:     if($udom) {
                   10778:         if($uname) {
1.1135    raeburn  10779:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10780:             if ($uhome eq 'no_host') {
                   10781:                 return ([],'no_host');
                   10782:             }
1.955     raeburn  10783:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10784:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10785:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10786:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10787:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10788:             } else {
                   10789:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10790:             }
1.605     matthew  10791:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10792:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10793:                 @listing_results = split(/:/,$listing);
                   10794:             } else {
                   10795:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10796:             }
1.1135    raeburn  10797:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10798:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10799:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10800:                 return ([],$listing);
                   10801:             } else {
                   10802:                 return (\@listing_results);
1.1135    raeburn  10803:             }
1.955     raeburn  10804:         } elsif(!$alternateRoot) {
1.1136    raeburn  10805:             my (%allusers,%listerror);
1.841     albertel 10806: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10807:  	    foreach my $tryserver (keys(%servers)) {
                   10808:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10809:                                   &escape($udom),$tryserver);
                   10810:                 if ($listing eq 'unknown_cmd') {
                   10811: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10812: 				      $udom, $tryserver);
                   10813:                 } else {
                   10814:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10815:                 }
1.841     albertel 10816: 		if ($listing eq 'unknown_cmd') {
                   10817: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10818: 				      $udom, $tryserver);
                   10819: 		    @listing_results = split(/:/,$listing);
                   10820: 		} else {
                   10821: 		    @listing_results =
                   10822: 			map { &unescape($_); } split(/:/,$listing);
                   10823: 		}
1.1136    raeburn  10824:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10825:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10826:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10827:                     $listerror{$tryserver} = $listing;
                   10828:                 } else {
1.841     albertel 10829: 		    foreach my $line (@listing_results) {
                   10830: 			my ($entry) = split(/&/,$line,2);
                   10831: 			$allusers{$entry} = 1;
                   10832: 		    }
                   10833: 		}
1.253     stredwic 10834:             }
1.1136    raeburn  10835:             my @alluserslist=();
1.800     albertel 10836:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10837:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10838:             }
1.1318    droeschl 10839: 
                   10840:             if (!%listerror) {
                   10841:                 # no errors
                   10842:                 return (\@alluserslist);
                   10843:             } elsif (scalar(keys(%servers)) == 1) {
                   10844:                 # one library server, one error 
                   10845:                 my ($key) = keys(%listerror);
                   10846:                 return (\@alluserslist, $listerror{$key});
                   10847:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10848:                 # con_lost indicates that we might miss data from at least one
                   10849:                 # library server
                   10850:                 return (\@alluserslist, 'con_lost');
                   10851:             } else {
                   10852:                 # multiple library servers and no con_lost -> data should be
                   10853:                 # complete. 
                   10854:                 return (\@alluserslist);
                   10855:             }
                   10856: 
1.253     stredwic 10857:         } else {
1.1136    raeburn  10858:             return ([],'missing username');
1.253     stredwic 10859:         }
1.955     raeburn  10860:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10861:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10862:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10863:         return (\@all_domains);
1.955     raeburn  10864:     } else {
1.1136    raeburn  10865:         return ([],'missing domain');
1.275     stredwic 10866:     }
                   10867: }
                   10868: 
                   10869: # --------------------------------------------- GetFileTimestamp
                   10870: # This function utilizes dirlist and returns the date stamp for
                   10871: # when it was last modified.  It will also return an error of -1
                   10872: # if an error occurs
                   10873: 
                   10874: sub GetFileTimestamp {
1.955     raeburn  10875:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10876:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10877:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10878:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10879:                                     undef,$getuserdir);
                   10880:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10881:         return -1;
                   10882:     }
                   10883:     if (ref($fileref) eq 'ARRAY') {
                   10884:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10885:         # @stats contains first the filename, then the stat output
                   10886:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10887:     } else {
                   10888:         return -1;
1.253     stredwic 10889:     }
1.26      www      10890: }
                   10891: 
1.712     albertel 10892: sub stat_file {
                   10893:     my ($uri) = @_;
1.787     albertel 10894:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10895: 
1.955     raeburn  10896:     my ($udom,$uname,$file);
1.712     albertel 10897:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10898: 	($udom,$uname,$file) =
1.811     albertel 10899: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10900: 	$file = 'userfiles/'.$file;
                   10901:     }
                   10902:     if ($uri =~ m-^/res/-) {
                   10903: 	($udom,$uname) = 
1.807     albertel 10904: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10905: 	$file = $uri;
                   10906:     }
                   10907: 
                   10908:     if (!$udom || !$uname || !$file) {
                   10909: 	# unable to handle the uri
                   10910: 	return ();
                   10911:     }
1.956     raeburn  10912:     my $getpropath;
                   10913:     if ($file =~ /^userfiles\//) {
                   10914:         $getpropath = 1;
                   10915:     }
1.1136    raeburn  10916:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10917:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10918:         return ();
                   10919:     } else {
                   10920:         if (ref($listref) eq 'ARRAY') {
                   10921:             my @stats = split('&',$listref->[0]);
                   10922: 	    shift(@stats); #filename is first
                   10923: 	    return @stats;
                   10924:         }
1.712     albertel 10925:     }
                   10926:     return ();
                   10927: }
                   10928: 
1.1313    raeburn  10929: # --------------------------------------------------------- recursedirs
                   10930: # Recursive function to traverse either a specific user's Authoring Space
                   10931: # or corresponding Published Resource Space, and populate the hash ref:
                   10932: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10933: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10934: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10935: # files in Authoring Space.
                   10936: #
                   10937: # Inputs:
                   10938: #
                   10939: # $is_home - true if current server is home server for user's space
                   10940: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10941: # $docroot - Document root (i.e., /home/httpd/html
                   10942: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10943: # $relpath - Current path (relative to top level).
                   10944: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10945: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10946: #
                   10947: # Returns: nothing
                   10948: #
                   10949: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10950: #
                   10951: # Currently used by interface/londocs.pm to create linked select boxes for
                   10952: # directory and filename to import a Course "Author" resource into a course, and
                   10953: # also to create linked select boxes for Authoring Space and Directory to choose
                   10954: # save location for creation of a new "standard" problem from the Course Editor.
                   10955: #
                   10956: 
                   10957: sub recursedirs {
                   10958:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10959:     return unless (ref($dirhashref) eq 'HASH');
                   10960:     my $currpath = $docroot.$toppath;
                   10961:     if ($relpath) {
                   10962:         $currpath .= "/$relpath";
                   10963:     }
                   10964:     my $savefile;
                   10965:     if (ref($filehashref)) {
                   10966:         $savefile = 1;
                   10967:     }
                   10968:     if ($is_home) {
                   10969:         if (opendir(my $dirh,$currpath)) {
                   10970:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10971:                 next if ($item eq '');
                   10972:                 if (-d "$currpath/$item") {
                   10973:                     my $newpath;
                   10974:                     if ($relpath) {
                   10975:                         $newpath = "$relpath/$item";
                   10976:                     } else {
                   10977:                         $newpath = $item;
                   10978:                     }
                   10979:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10980:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10981:                 } elsif ($savefile) {
                   10982:                     if ($context eq 'priv') {
                   10983:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10984:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10985:                         }
                   10986:                     } else {
                   10987:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10988:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10989:                         }
                   10990:                     }
                   10991:                 }
                   10992:             }
                   10993:             closedir($dirh);
                   10994:         }
                   10995:     } else {
                   10996:         my ($dirlistref,$listerror) =
                   10997:             &dirlist($toppath.$relpath);
                   10998:         my @dir_lines;
                   10999:         my $dirptr=16384;
                   11000:         if (ref($dirlistref) eq 'ARRAY') {
                   11001:             foreach my $dir_line (sort
                   11002:                               {
                   11003:                                   my ($afile)=split('&',$a,2);
                   11004:                                   my ($bfile)=split('&',$b,2);
                   11005:                                   return (lc($afile) cmp lc($bfile));
                   11006:                               } (@{$dirlistref})) {
                   11007:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11008:                     split(/\&/,$dir_line,16);
                   11009:                 $item =~ s/\s+$//;
                   11010:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11011:                 if ($dirptr&$testdir) {
                   11012:                     my $newpath;
                   11013:                     if ($relpath) {
                   11014:                         $newpath = "$relpath/$item";
                   11015:                     } else {
                   11016:                         $relpath = '/';
                   11017:                         $newpath = $item;
                   11018:                     }
                   11019:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11020:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11021:                 } elsif ($savefile) {
                   11022:                     if ($context eq 'priv') {
                   11023:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11024:                             $filehashref->{$relpath}{$item} = 1;
                   11025:                         }
                   11026:                     } else {
                   11027:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11028:                             $filehashref->{$relpath}{$item} = 1;
                   11029:                         }
                   11030:                     }
                   11031:                 }
                   11032:             }
                   11033:         }
                   11034:     }
                   11035:     return;
                   11036: }
                   11037: 
1.26      www      11038: # -------------------------------------------------------- Value of a Condition
                   11039: 
1.713     albertel 11040: # gets the value of a specific preevaluated condition
                   11041: #    stored in the string  $env{user.state.<cid>}
                   11042: # or looks up a condition reference in the bighash and if if hasn't
                   11043: # already been evaluated recurses into docondval to get the value of
                   11044: # the condition, then memoizing it to 
                   11045: #   $env{user.state.<cid>.<condition>}
1.40      www      11046: sub directcondval {
                   11047:     my $number=shift;
1.620     albertel 11048:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11049: 	&Apache::lonuserstate::evalstate();
                   11050:     }
1.713     albertel 11051:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11052: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11053:     } elsif ($number =~ /^_/) {
                   11054: 	my $sub_condition;
                   11055: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11056: 		&GDBM_READER(),0640)) {
                   11057: 	    $sub_condition=$bighash{'conditions'.$number};
                   11058: 	    untie(%bighash);
                   11059: 	}
                   11060: 	my $value = &docondval($sub_condition);
1.949     raeburn  11061: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11062: 	return $value;
                   11063:     }
1.620     albertel 11064:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11065:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11066:     } else {
                   11067:        return 2;
                   11068:     }
                   11069: }
                   11070: 
1.713     albertel 11071: # get the collection of conditions for this resource
1.26      www      11072: sub condval {
                   11073:     my $condidx=shift;
1.54      www      11074:     my $allpathcond='';
1.713     albertel 11075:     foreach my $cond (split(/\|/,$condidx)) {
                   11076: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11077: 	    $allpathcond.=
                   11078: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11079: 	}
1.191     harris41 11080:     }
1.54      www      11081:     $allpathcond=~s/\|$//;
1.713     albertel 11082:     return &docondval($allpathcond);
                   11083: }
                   11084: 
                   11085: #evaluates an expression of conditions
                   11086: sub docondval {
                   11087:     my ($allpathcond) = @_;
                   11088:     my $result=0;
                   11089:     if ($env{'request.course.id'}
                   11090: 	&& defined($allpathcond)) {
                   11091: 	my $operand='|';
                   11092: 	my @stack;
                   11093: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11094: 	    if ($chunk eq '(') {
                   11095: 		push @stack,($operand,$result);
                   11096: 	    } elsif ($chunk eq ')') {
                   11097: 		my $before=pop @stack;
                   11098: 		if (pop @stack eq '&') {
                   11099: 		    $result=$result>$before?$before:$result;
                   11100: 		} else {
                   11101: 		    $result=$result>$before?$result:$before;
                   11102: 		}
                   11103: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11104: 		$operand=$chunk;
                   11105: 	    } else {
                   11106: 		my $new=directcondval($chunk);
                   11107: 		if ($operand eq '&') {
                   11108: 		    $result=$result>$new?$new:$result;
                   11109: 		} else {
                   11110: 		    $result=$result>$new?$result:$new;
                   11111: 		}
                   11112: 	    }
                   11113: 	}
1.26      www      11114:     }
                   11115:     return $result;
1.421     albertel 11116: }
                   11117: 
                   11118: # ---------------------------------------------------- Devalidate courseresdata
                   11119: 
                   11120: sub devalidatecourseresdata {
                   11121:     my ($coursenum,$coursedomain)=@_;
                   11122:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11123:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11124: }
                   11125: 
1.763     www      11126: 
1.200     www      11127: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11128: #
                   11129: #  Parameters:
                   11130: #      $coursenum    - Number of the course.
                   11131: #      $coursedomain - Domain at which the course was created.
                   11132: #  Returns:
                   11133: #     A hash of the course parameters along (I think) with timestamps
                   11134: #     and version info.
1.877     foxr     11135: 
1.624     albertel 11136: sub get_courseresdata {
                   11137:     my ($coursenum,$coursedomain)=@_;
1.200     www      11138:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11139:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11140:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11141:     my %dumpreply;
1.417     albertel 11142:     unless (defined($cached)) {
1.624     albertel 11143: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11144: 	$result=\%dumpreply;
1.251     albertel 11145: 	my ($tmp) = keys(%dumpreply);
                   11146: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11147: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11148: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11149: 	    return $tmp;
1.416     albertel 11150: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11151: 	    $result=undef;
1.599     albertel 11152: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11153: 	}
                   11154:     }
1.624     albertel 11155:     return $result;
                   11156: }
                   11157: 
1.633     albertel 11158: sub devalidateuserresdata {
                   11159:     my ($uname,$udom)=@_;
                   11160:     my $hashid="$udom:$uname";
                   11161:     &devalidate_cache_new('userres',$hashid);
                   11162: }
                   11163: 
1.624     albertel 11164: sub get_userresdata {
                   11165:     my ($uname,$udom)=@_;
                   11166:     #most student don\'t have any data set, check if there is some data
                   11167:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11168: 
                   11169:     my $hashid="$udom:$uname";
                   11170:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11171:     if (!defined($cached)) {
                   11172: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11173: 	$result=\%resourcedata;
                   11174: 	&do_cache_new('userres',$hashid,$result,600);
                   11175:     }
                   11176:     my ($tmp)=keys(%$result);
                   11177:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11178: 	return $result;
                   11179:     }
                   11180:     #error 2 occurs when the .db doesn't exist
                   11181:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11182:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11183: 	    &logthis("<font color=\"blue\">WARNING:".
                   11184: 		     " Trying to get resource data for ".
                   11185: 		     $uname." at ".$udom.": ".
                   11186: 		     $tmp."</font>");
                   11187:         }
1.624     albertel 11188:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11189: 	#&EXT_cache_set($udom,$uname);
                   11190: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11191: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11192:     }
                   11193:     return $tmp;
                   11194: }
1.879     foxr     11195: #----------------------------------------------- resdata - return resource data
                   11196: #  Purpose:
                   11197: #    Return resource data for either users or for a course.
                   11198: #  Parameters:
                   11199: #     $name      - Course/user name.
                   11200: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11201: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11202: #     $mapp      - decluttered URL of enclosing map  
                   11203: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11204: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11205: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11206: #     $courseid  - CourseID (first part of param identifier).
                   11207: #     $modifier  - Middle part of param identifier.
                   11208: #     $what      - Last part of param identifier.
1.879     foxr     11209: #     @which     - Array of names of resources desired.
                   11210: #  Returns:
                   11211: #     The value of the first reasource in @which that is found in the
                   11212: #     resource hash.
                   11213: #  Exceptional Conditions:
                   11214: #     If the $type passed in is not valid (not the string 'course' or 
                   11215: #     'user', an undefined  reference is returned.
                   11216: #     If none of the resources are found, an undef is returned
1.624     albertel 11217: sub resdata {
1.1301    raeburn  11218:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11219:         $modifier,$what,@which)=@_;
1.624     albertel 11220:     my $result;
                   11221:     if ($type eq 'course') {
                   11222: 	$result=&get_courseresdata($name,$domain);
                   11223:     } elsif ($type eq 'user') {
                   11224: 	$result=&get_userresdata($name,$domain);
                   11225:     }
                   11226:     if (!ref($result)) { return $result; }    
1.251     albertel 11227:     foreach my $item (@which) {
1.1301    raeburn  11228:         if ($item->[1] eq 'course') {
                   11229:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11230:                 unless ($$recursed) {
1.1302    raeburn  11231:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11232:                     $$recursed = 1;
                   11233:                 }
                   11234:                 foreach my $item (@${recurseup}) {
                   11235:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11236:                     last if (defined($result->{$norecursechk}));
                   11237:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11238:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11239:                 }
                   11240:             }
                   11241:         }
                   11242:         if (defined($result->{$item->[0]})) {
1.927     albertel 11243: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11244: 	}
1.250     albertel 11245:     }
1.291     albertel 11246:     return undef;
1.200     www      11247: }
                   11248: 
1.1360    raeburn  11249: sub get_domain_lti {
                   11250:     my ($cdom,$context) = @_;
                   11251:     my ($name,%lti);
                   11252:     if ($context eq 'consumer') {
                   11253:         $name = 'ltitools';
                   11254:     } elsif ($context eq 'provider') {
                   11255:         $name = 'lti';
                   11256:     } else {
                   11257:         return %lti;
                   11258:     }
                   11259:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11260:     if (defined($cached)) {
                   11261:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11262:             %lti = %{$result};
1.1298    raeburn  11263:         }
                   11264:     } else {
1.1360    raeburn  11265:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11266:         if (ref($domconfig{$name}) eq 'HASH') {
                   11267:             %lti = %{$domconfig{$name}};
                   11268:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11269:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11270:                 foreach my $id (keys(%lti)) {
                   11271:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11272:                         foreach my $item ('key','secret') {
1.1360    raeburn  11273:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11274:                         }
                   11275:                     }
                   11276:                 }
                   11277:             }
1.1298    raeburn  11278:         }
                   11279:         my $cachetime = 24*60*60;
1.1360    raeburn  11280:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11281:     }
1.1360    raeburn  11282:     return %lti;
1.1298    raeburn  11283: }
                   11284: 
1.1236    raeburn  11285: sub get_numsuppfiles {
                   11286:     my ($cnum,$cdom,$ignorecache)=@_;
                   11287:     my $hashid=$cnum.':'.$cdom;
                   11288:     my ($suppcount,$cached);
                   11289:     unless ($ignorecache) {
                   11290:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11291:     }
                   11292:     unless (defined($cached)) {
                   11293:         my $chome=&homeserver($cnum,$cdom);
                   11294:         unless ($chome eq 'no_host') {
1.1366    raeburn  11295:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11296:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11297:             ($suppcount,$supptools,$errors) =
                   11298:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11299:                                                          $supptools,$errors);
1.1236    raeburn  11300:         }
                   11301:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11302:     }
                   11303:     return $suppcount;
                   11304: }
                   11305: 
1.379     matthew  11306: #
                   11307: # EXT resource caching routines
                   11308: #
                   11309: 
1.1302    raeburn  11310: {
                   11311: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11312: #
                   11313: # The course for which we cache
                   11314: my $cachedmapkey='';
                   11315: # The cached recursive maps for this course
                   11316: my %cachedmaps=();
                   11317: # When this was last done
                   11318: my $cachedmaptime='';
                   11319: 
1.379     matthew  11320: sub clear_EXT_cache_status {
1.383     albertel 11321:     &delenv('cache.EXT.');
1.379     matthew  11322: }
                   11323: 
                   11324: sub EXT_cache_status {
                   11325:     my ($target_domain,$target_user) = @_;
1.383     albertel 11326:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11327:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11328:         # We know already the user has no data
                   11329:         return 1;
                   11330:     } else {
                   11331:         return 0;
                   11332:     }
                   11333: }
                   11334: 
                   11335: sub EXT_cache_set {
                   11336:     my ($target_domain,$target_user) = @_;
1.383     albertel 11337:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11338:     #&appenv({$cachename => time});
1.379     matthew  11339: }
                   11340: 
1.28      www      11341: # --------------------------------------------------------- Value of a Variable
1.58      www      11342: sub EXT {
1.715     albertel 11343: 
1.1228    raeburn  11344:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11345:     unless ($varname) { return ''; }
1.218     albertel 11346:     #get real user name/domain, courseid and symb
                   11347:     my $courseid;
1.359     albertel 11348:     my $publicuser;
1.427     www      11349:     if ($symbparm) {
                   11350: 	$symbparm=&get_symb_from_alias($symbparm);
                   11351:     }
1.218     albertel 11352:     if (!($uname && $udom)) {
1.790     albertel 11353:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11354:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11355:     } else {
1.620     albertel 11356: 	$courseid=$env{'request.course.id'};
1.218     albertel 11357:     }
1.48      www      11358:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11359:     my $rest;
1.320     albertel 11360:     if (defined($therest[0])) {
1.48      www      11361:        $rest=join('.',@therest);
                   11362:     } else {
                   11363:        $rest='';
                   11364:     }
1.320     albertel 11365: 
1.57      www      11366:     my $qualifierrest=$qualifier;
                   11367:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11368:     my $spacequalifierrest=$space;
                   11369:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11370:     if ($realm eq 'user') {
1.48      www      11371: # --------------------------------------------------------------- user.resource
                   11372: 	if ($space eq 'resource') {
1.651     albertel 11373: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11374: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11375: 		 &&
1.744     albertel 11376: 		 ($symbparm eq &symbread()) ) {	
                   11377: 		# if we are in the middle of processing the resource the
                   11378: 		# get the value we are planning on committing
                   11379:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11380:                     return $Apache::lonhomework::results{$qualifierrest};
                   11381:                 } else {
                   11382:                     return $Apache::lonhomework::history{$qualifierrest};
                   11383:                 }
1.335     albertel 11384: 	    } else {
1.359     albertel 11385: 		my %restored;
1.620     albertel 11386: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11387: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11388: 		} else {
                   11389: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11390: 		}
1.335     albertel 11391: 		return $restored{$qualifierrest};
                   11392: 	    }
1.48      www      11393: # ----------------------------------------------------------------- user.access
                   11394:         } elsif ($space eq 'access') {
1.218     albertel 11395: 	    # FIXME - not supporting calls for a specific user
1.48      www      11396:             return &allowed($qualifier,$rest);
                   11397: # ------------------------------------------ user.preferences, user.environment
                   11398:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11399: 	    if (($uname eq $env{'user.name'}) &&
                   11400: 		($udom eq $env{'user.domain'})) {
                   11401: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11402: 	    } else {
1.359     albertel 11403: 		my %returnhash;
                   11404: 		if (!$publicuser) {
                   11405: 		    %returnhash=&userenvironment($udom,$uname,
                   11406: 						 $qualifierrest);
                   11407: 		}
1.218     albertel 11408: 		return $returnhash{$qualifierrest};
                   11409: 	    }
1.48      www      11410: # ----------------------------------------------------------------- user.course
                   11411:         } elsif ($space eq 'course') {
1.218     albertel 11412: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11413:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11414: # ------------------------------------------------------------------- user.role
                   11415:         } elsif ($space eq 'role') {
1.218     albertel 11416: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11417:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11418:             if ($qualifier eq 'value') {
                   11419: 		return $role;
                   11420:             } elsif ($qualifier eq 'extent') {
                   11421:                 return $where;
                   11422:             }
                   11423: # ----------------------------------------------------------------- user.domain
                   11424:         } elsif ($space eq 'domain') {
1.218     albertel 11425:             return $udom;
1.48      www      11426: # ------------------------------------------------------------------- user.name
                   11427:         } elsif ($space eq 'name') {
1.218     albertel 11428:             return $uname;
1.48      www      11429: # ---------------------------------------------------- Any other user namespace
1.29      www      11430:         } else {
1.359     albertel 11431: 	    my %reply;
                   11432: 	    if (!$publicuser) {
                   11433: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11434: 	    }
                   11435: 	    return $reply{$qualifierrest};
1.48      www      11436:         }
1.236     www      11437:     } elsif ($realm eq 'query') {
                   11438: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11439:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11440: 						[$spacequalifierrest]);
1.620     albertel 11441: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11442:    } elsif ($realm eq 'request') {
1.48      www      11443: # ------------------------------------------------------------- request.browser
                   11444:         if ($space eq 'browser') {
1.1145    bisitz   11445:             return $env{'browser.'.$qualifier};
1.57      www      11446: # ------------------------------------------------------------ request.filename
                   11447:         } else {
1.620     albertel 11448:             return $env{'request.'.$spacequalifierrest};
1.29      www      11449:         }
1.28      www      11450:     } elsif ($realm eq 'course') {
1.48      www      11451: # ---------------------------------------------------------- course.description
1.620     albertel 11452:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11453:     } elsif ($realm eq 'resource') {
1.165     www      11454: 
1.620     albertel 11455: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11456: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11457: 	}
1.693     albertel 11458: 
1.1232    raeburn  11459:         if ($qualifier eq '') {
                   11460: 	    if ($space eq 'title') {
                   11461: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11462: 	        return &gettitle($symbparm);
                   11463: 	    }
1.693     albertel 11464: 	
1.1232    raeburn  11465: 	    if ($space eq 'map') {
                   11466: 	        my ($map) = &decode_symb($symbparm);
                   11467: 	        return &symbread($map);
                   11468: 	    }
                   11469:             if ($space eq 'maptitle') {
                   11470:                 my ($map) = &decode_symb($symbparm);
                   11471:                 return &gettitle($map);
                   11472:             }
                   11473: 	    if ($space eq 'filename') {
                   11474: 	        if ($symbparm) {
                   11475: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11476: 	        }
                   11477: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11478: 	    }
1.1232    raeburn  11479: 
1.1233    raeburn  11480:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11481:                 if ($space eq 'visibleparts') {
                   11482:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11483:                     my $item;
                   11484:                     if (ref($navmap)) {
                   11485:                         my $res = $navmap->getBySymb($symbparm);
                   11486:                         my $parts = $res->parts();
                   11487:                         if (ref($parts) eq 'ARRAY') {
                   11488:                             $item = join(',',@{$parts});
                   11489:                         }
                   11490:                         undef($navmap);
1.1232    raeburn  11491:                     }
1.1233    raeburn  11492:                     return $item;
1.1232    raeburn  11493:                 }
                   11494:             }
                   11495:         }
1.693     albertel 11496: 
1.1301    raeburn  11497: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11498: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11499:         if (($courseid eq '') && ($cid)) {
                   11500:             $courseid = $cid;
                   11501:         }
                   11502: 	if (($symbparm && $courseid) && 
                   11503: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11504: 
1.218     albertel 11505: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11506: 
1.60      www      11507: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11508: 	    my $symbp=$symbparm;
1.1301    raeburn  11509: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11510: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11511:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11512: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11513: 	    if (($env{'user.name'} eq $uname) &&
                   11514: 		($env{'user.domain'} eq $udom)) {
                   11515: 		$section=$env{'request.course.sec'};
1.733     raeburn  11516:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11517:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11518: 	    } else {
1.539     albertel 11519: 		if (! defined($usection)) {
1.551     albertel 11520: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11521: 		} else {
                   11522: 		    $section = $usection;
                   11523: 		}
1.733     raeburn  11524:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11525: 	    }
                   11526: 
                   11527: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11528: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11529:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11530: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11531: 
1.593     albertel 11532: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11533: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11534:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11535: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11536: 
1.60      www      11537: # ----------------------------------------------------------- first, check user
1.624     albertel 11538: 
1.1301    raeburn  11539: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11540:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11541: 				       ([$courselevelr,'resource'],
                   11542: 					[$courselevelm,'map'     ],
1.1301    raeburn  11543:                                         [$courseleveli,'map'     ],
1.927     albertel 11544: 					[$courselevel, 'course'  ]));
1.931     albertel 11545: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11546: 
1.594     albertel 11547: # ------------------------------------------------ second, check some of course
1.684     raeburn  11548:             my $coursereply;
1.691     raeburn  11549:             if (@groups > 0) {
                   11550:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11551:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11552:                                        $mapp,\$recursed,\@recurseup);
                   11553:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11554:             }
1.96      www      11555: 
1.684     raeburn  11556: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11557: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11558: 				  'course',$mapp,\$recursed,\@recurseup,
                   11559:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11560: 				  ([$seclevelr,   'resource'],
                   11561: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11562:                                    [$secleveli,   'map'     ],
1.927     albertel 11563: 				   [$seclevel,    'course'  ],
                   11564: 				   [$courselevelr,'resource']));
                   11565: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11566: 
1.60      www      11567: # ------------------------------------------------------ third, check map parms
1.218     albertel 11568: 	    my %parmhash=();
                   11569: 	    my $thisparm='';
                   11570: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11571: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11572: 		    &GDBM_READER(),0640)) {
1.218     albertel 11573: 		$thisparm=$parmhash{$symbparm};
                   11574: 		untie(%parmhash);
                   11575: 	    }
1.927     albertel 11576: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11577: 	}
1.594     albertel 11578: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11579:  
                   11580:         my $what = $spacequalifierrest;
                   11581: 	$what=~s/\./\_/;
1.282     albertel 11582: 	my $filename;
                   11583: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11584: 	if ($symbparm) {
1.409     www      11585: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11586: 	} else {
1.620     albertel 11587: 	    $filename=$env{'request.filename'};
1.282     albertel 11588: 	}
1.1362    raeburn  11589:         my $toolsymb;
                   11590:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11591:             $toolsymb = $symbparm;
                   11592:         }
                   11593: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11594: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11595: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11596: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11597: 
1.1301    raeburn  11598: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11599: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11600: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11601: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11602: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11603: 				     'course',$mapp,\$recursed,\@recurseup,
                   11604:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11605: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11606:                                       [$courseleveli,'map'   ],
1.927     albertel 11607: 				      [$courselevel, 'course']));
                   11608: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11609: 	}
1.145     www      11610: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11611: 	unless ($space eq '0') {
1.336     albertel 11612: 	    my @parts=split(/_/,$space);
                   11613: 	    my $id=pop(@parts);
                   11614: 	    my $part=join('_',@parts);
                   11615: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11616: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11617: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11618: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11619: 	}
1.395     albertel 11620: 	if ($recurse) { return undef; }
1.1362    raeburn  11621: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11622: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11623: # ---------------------------------------------------- Any other user namespace
                   11624:     } elsif ($realm eq 'environment') {
                   11625: # ----------------------------------------------------------------- environment
1.620     albertel 11626: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11627: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11628: 	} else {
1.770     albertel 11629: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11630: 		return '';
                   11631: 	    }
1.219     albertel 11632: 	    my %returnhash=&userenvironment($udom,$uname,
                   11633: 					    $spacequalifierrest);
                   11634: 	    return $returnhash{$spacequalifierrest};
                   11635: 	}
1.28      www      11636:     } elsif ($realm eq 'system') {
1.48      www      11637: # ----------------------------------------------------------------- system.time
                   11638: 	if ($space eq 'time') {
                   11639: 	    return time;
                   11640:         }
1.696     albertel 11641:     } elsif ($realm eq 'server') {
                   11642: # ----------------------------------------------------------------- system.time
                   11643: 	if ($space eq 'name') {
                   11644: 	    return $ENV{'SERVER_NAME'};
                   11645:         }
1.28      www      11646:     }
1.48      www      11647:     return '';
1.61      www      11648: }
                   11649: 
1.927     albertel 11650: sub get_reply {
                   11651:     my ($reply_value) = @_;
1.940     raeburn  11652:     if (ref($reply_value) eq 'ARRAY') {
                   11653:         if (wantarray) {
                   11654: 	    return @$reply_value;
                   11655:         }
                   11656:         return $reply_value->[0];
                   11657:     } else {
                   11658:         return $reply_value;
1.927     albertel 11659:     }
                   11660: }
                   11661: 
1.691     raeburn  11662: sub check_group_parms {
1.1301    raeburn  11663:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11664:         $recursed,$recurseupref) = @_;
                   11665:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11666:                   [$what,'course']);
                   11667:     my $coursereply;
1.691     raeburn  11668:     foreach my $group (@{$groups}) {
1.1301    raeburn  11669:         my @groupitems = ();
1.691     raeburn  11670:         foreach my $level (@levels) {
1.927     albertel 11671:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11672:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11673:         }
1.1301    raeburn  11674:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11675:                                    $env{'course.'.$courseid.'.domain'},
                   11676:                                    'course',$mapp,$recursed,$recurseupref,
                   11677:                                    $courseid,'.['.$group.'].',$what,
                   11678:                                    @groupitems);
                   11679:         last if (defined($coursereply));
1.691     raeburn  11680:     }
                   11681:     return $coursereply;
                   11682: }
                   11683: 
1.1301    raeburn  11684: sub get_map_hierarchy {
1.1302    raeburn  11685:     my ($mapname,$courseid) = @_;
                   11686:     my @recurseup = ();
1.1301    raeburn  11687:     if ($mapname) {
1.1302    raeburn  11688:         if (($cachedmapkey eq $courseid) &&
                   11689:             (abs($cachedmaptime-time)<5)) {
                   11690:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11691:                 return @{$cachedmaps{$mapname}};
                   11692:             }
                   11693:         }
1.1301    raeburn  11694:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11695:         if (ref($navmap)) {
                   11696:             @recurseup = $navmap->recurseup_maps($mapname);
                   11697:             undef($navmap);
1.1302    raeburn  11698:             $cachedmaps{$mapname} = \@recurseup;
                   11699:             $cachedmaptime=time;
                   11700:             $cachedmapkey=$courseid;
1.1301    raeburn  11701:         }
                   11702:     }
                   11703:     return @recurseup;
                   11704: }
                   11705: 
1.1302    raeburn  11706: }
                   11707: 
1.691     raeburn  11708: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11709:     my ($courseid,@groups) = @_;
                   11710:     @groups = sort(@groups);
1.691     raeburn  11711:     return @groups;
                   11712: }
                   11713: 
1.395     albertel 11714: sub packages_tab_default {
1.1362    raeburn  11715:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11716:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11717: 
                   11718:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11719:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11720: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11721: 	if ($pack_type eq 'default') {
                   11722: 	    $do_default=1;
                   11723: 	} elsif ($pack_type eq 'extension') {
                   11724: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11725: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11726: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11727: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11728: 	}
                   11729:     }
                   11730:     # first look for a package that matches the requested part id
                   11731:     foreach my $package (@specifics) {
                   11732: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11733: 	next if ($pack_part ne $part);
                   11734: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11735: 	    return $packagetab{"$pack_type&$name&default"};
                   11736: 	}
                   11737:     }
                   11738:     # look for any possible matching non extension_ package
                   11739:     foreach my $package (@specifics) {
                   11740: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11741: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11742: 	    return $packagetab{"$pack_type&$name&default"};
                   11743: 	}
1.585     albertel 11744: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11745: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11746: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11747: 	}
                   11748:     }
1.738     albertel 11749:     # look for any posible extension_ match
                   11750:     foreach my $package (@extension) {
                   11751: 	my ($package,$pack_type)=@{$package};
                   11752: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11753: 	    return $packagetab{"$pack_type&$name&default"};
                   11754: 	}
                   11755: 	if (defined($packagetab{$package."&$name&default"})) {
                   11756: 	    return $packagetab{$package."&$name&default"};
                   11757: 	}
                   11758:     }
                   11759:     # look for a global default setting
                   11760:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11761: 	return $packagetab{"default&$name&default"};
                   11762:     }
1.395     albertel 11763:     return undef;
                   11764: }
                   11765: 
1.334     albertel 11766: sub add_prefix_and_part {
                   11767:     my ($prefix,$part)=@_;
                   11768:     my $keyroot;
                   11769:     if (defined($prefix) && $prefix !~ /^__/) {
                   11770: 	# prefix that has a part already
                   11771: 	$keyroot=$prefix;
                   11772:     } elsif (defined($prefix)) {
                   11773: 	# prefix that is missing a part
                   11774: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11775:     } else {
                   11776: 	# no prefix at all
                   11777: 	if (defined($part)) { $keyroot='_'.$part; }
                   11778:     }
                   11779:     return $keyroot;
                   11780: }
                   11781: 
1.71      www      11782: # ---------------------------------------------------------------- Get metadata
                   11783: 
1.599     albertel 11784: my %metaentry;
1.1070    www      11785: my %importedpartids;
1.1369    raeburn  11786: my %importedrespids;
1.71      www      11787: sub metadata {
1.1362    raeburn  11788:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11789:     $uri=&declutter($uri);
1.288     albertel 11790:     # if it is a non metadata possible uri return quickly
1.529     albertel 11791:     if (($uri eq '') || 
                   11792: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11793: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11794:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11795: 	return undef;
                   11796:     }
1.1261    raeburn  11797:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11798: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11799: 	return undef;
1.288     albertel 11800:     }
1.73      www      11801:     my $filename=$uri;
                   11802:     $uri=~s/\.meta$//;
1.172     www      11803: #
                   11804: # Is the metadata already cached?
1.177     www      11805: # Look at timestamp of caching
1.172     www      11806: # Everything is cached by the main uri, libraries are never directly cached
                   11807: #
1.428     albertel 11808:     if (!defined($liburi)) {
1.599     albertel 11809: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11810: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11811:     }
1.1362    raeburn  11812: 
                   11813: #
                   11814: # If the uri is for an external tool the file from
                   11815: # which metadata should be retrieved depends on whether
                   11816: # the tool had been configured to be gradable (set in the Course
                   11817: # Editor or Resource Editor).
                   11818: #
                   11819: # If a valid symb has been included as the third arg in the call
                   11820: # to &metadata() that can be used to retrieve the value of
                   11821: # parameter_0_gradable set for the resource, and included in the
                   11822: # uploaded map containing the tool. The value is retrieved via
                   11823: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11824: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11825: # is retrieved via &get().
                   11826: #
                   11827: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11828: # hiddenresource and encrypturl (during course initialization)
                   11829: # the map-level parameter for resource.0.gradable included in the 
                   11830: # uploaded map containing the tool will not yet have been stored
                   11831: # in the user_course_parms.db file for the user's session, so in 
                   11832: # this case fall back to retrieving gradable status from the
                   11833: # exttool_$marker.db file.
1.1362    raeburn  11834: #
                   11835: # In order to avoid an infinite loop, &metadata() will return
                   11836: # before a call to &EXT(), if the uri is for an external tool
                   11837: # and the $what for which metadata is being requested is
                   11838: # parameter_0_gradable or 0_gradable.
                   11839: #
                   11840: 
                   11841:     if ($uri =~ /ext\.tool$/) {
                   11842:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11843:             return;
                   11844:         } else {
                   11845:             my ($checked,$use_passback);
                   11846:             if ($toolsymb ne '') {
                   11847:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11848:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11849:                     $checked = 1;
                   11850:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11851:                         $use_passback = 1;
                   11852:                     }
                   11853:                 }
                   11854:             }
                   11855:             unless ($checked) {
                   11856:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11857:                 $marker=~s/\D//g;
1.1363    raeburn  11858:                 if ($marker) {
1.1362    raeburn  11859:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11860:                     $use_passback = $toolsettings{'gradable'};
                   11861:                 }
                   11862:             }
                   11863:             if ($use_passback) {
                   11864:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11865:             } else {
                   11866:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11867:             }
                   11868:         }
                   11869:     }
                   11870: 
1.428     albertel 11871:     {
1.1069    www      11872: # Imported parts would go here
1.1369    raeburn  11873:         my @origfiletagids=();
1.1069    www      11874:         my $importedparts=0;
1.1369    raeburn  11875: 
                   11876: # Imported responseids would go here
                   11877:         my $importedresponses=0;
1.172     www      11878: #
                   11879: # Is this a recursive call for a library?
                   11880: #
1.599     albertel 11881: #	if (! exists($metacache{$uri})) {
                   11882: #	    $metacache{$uri}={};
                   11883: #	}
1.924     albertel 11884: 	my $cachetime = 60*60;
1.171     www      11885:         if ($liburi) {
                   11886: 	    $liburi=&declutter($liburi);
                   11887:             $filename=$liburi;
1.401     bowersj2 11888:         } else {
1.599     albertel 11889: 	    &devalidate_cache_new('meta',$uri);
                   11890: 	    undef(%metaentry);
1.401     bowersj2 11891: 	}
1.140     www      11892:         my %metathesekeys=();
1.73      www      11893:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11894: 	my $metastring;
1.1140    www      11895: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11896: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11897: 	    $metastring = 
1.929     albertel 11898: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11899: 					  ('grade_target' => 'meta'));
                   11900: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11901: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11902:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11903: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11904: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11905: 	    $metastring=&getfile($file);
1.489     albertel 11906: 	}
1.208     albertel 11907:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11908:         my $token;
1.140     www      11909:         undef %metathesekeys;
1.71      www      11910:         while ($token=$parser->get_token) {
1.339     albertel 11911: 	    if ($token->[0] eq 'S') {
                   11912: 		if (defined($token->[2]->{'package'})) {
1.172     www      11913: #
                   11914: # This is a package - get package info
                   11915: #
1.339     albertel 11916: 		    my $package=$token->[2]->{'package'};
                   11917: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11918: 		    if (defined($token->[2]->{'id'})) { 
                   11919: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11920: 		    }
1.599     albertel 11921: 		    if ($metaentry{':packages'}) {
                   11922: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11923: 		    } else {
1.599     albertel 11924: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11925: 		    }
1.736     albertel 11926: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11927: 			my $part=$keyroot;
                   11928: 			$part=~s/^\_//;
1.736     albertel 11929: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11930: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11931: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11932: 			    # ignore package.tab specified default values
                   11933:                             # here &package_tab_default() will fetch those
                   11934: 			    if ($subp eq 'default') { next; }
1.736     albertel 11935: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11936: 			    my $unikey;
                   11937: 			    if ($pack =~ /_0$/) {
                   11938: 				$unikey='parameter_0_'.$name;
                   11939: 				$part=0;
                   11940: 			    } else {
                   11941: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11942: 			    }
1.339     albertel 11943: 			    if ($subp eq 'display') {
                   11944: 				$value.=' [Part: '.$part.']';
                   11945: 			    }
1.599     albertel 11946: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11947: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11948: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11949: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11950: 			    }
1.599     albertel 11951: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11952: 				$metaentry{':'.$unikey}=
                   11953: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11954: 			    }
1.339     albertel 11955: 			}
                   11956: 		    }
                   11957: 		} else {
1.172     www      11958: #
                   11959: # This is not a package - some other kind of start tag
1.339     albertel 11960: #
                   11961: 		    my $entry=$token->[1];
1.1068    www      11962: 		    my $unikey='';
1.175     www      11963: 
1.339     albertel 11964: 		    if ($entry eq 'import') {
1.175     www      11965: #
                   11966: # Importing a library here
1.339     albertel 11967: #
1.1067    www      11968:                         my $location=$parser->get_text('/import');
                   11969:                         my $dir=$filename;
                   11970:                         $dir=~s|[^/]*$||;
                   11971:                         $location=&filelocation($dir,$location);
1.1369    raeburn  11972: 
                   11973:                         my $importid=$token->[2]->{'id'};
1.1068    www      11974:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  11975: #
                   11976: # Check metadata for imported file to
                   11977: # see if it contained response items
                   11978: #
1.1372    raeburn  11979:                         my ($origfile,@libfilekeys);
1.1370    raeburn  11980:                         my %currmetaentry = %metaentry;
1.1372    raeburn  11981:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   11982:                                                            $depthcount+1));
                   11983:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   11984:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   11985:                                                              undef,$depthcount+1);
                   11986:                             if ($libresponseorder ne '') {
                   11987:                                 if ($#origfiletagids<0) {
                   11988:                                     undef(%importedrespids);
                   11989:                                     undef(%importedpartids);
                   11990:                                 }
1.1373    raeburn  11991:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   11992:                                 if (@respids) {
                   11993:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   11994:                                 }
                   11995:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  11996:                                     $importedresponses = 1;
1.1369    raeburn  11997: # We need to get the original file and the imported file to get the response order correct
                   11998: # Load and inspect original file
1.1372    raeburn  11999:                                     if ($#origfiletagids<0) {
                   12000:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12001:                                         $origfile=&getfile($origfilelocation);
                   12002:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12003:                                     }
1.1369    raeburn  12004:                                 }
                   12005:                             }
                   12006:                         }
1.1370    raeburn  12007: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12008: # hash populated for imported library file
                   12009:                         %metaentry = %currmetaentry;
                   12010:                         undef(%currmetaentry);
1.1374    raeburn  12011:                         if ($importmode eq 'part') {
1.1068    www      12012: # Import as part(s)
1.1069    www      12013:                            $importedparts=1;
                   12014: # We need to get the original file and the imported file to get the part order correct
                   12015: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12016: # Load and inspect original file if we didn't do that already
                   12017:                            if ($#origfiletagids<0) {
                   12018:                                undef(%importedrespids);
                   12019:                                undef(%importedpartids);
                   12020:                                if ($origfile eq '') {
                   12021:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12022:                                    $origfile=&getfile($origfilelocation);
                   12023:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12024:                                }
1.1070    www      12025:                            }
1.1372    raeburn  12026:                            my @impfilepartids;
                   12027: # If <partorder> tag is included in metadata for the imported file
                   12028: # get the parts in the imported file from that.
                   12029:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12030:                                %currmetaentry = %metaentry;
                   12031:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12032:                                                             $depthcount+1);
                   12033:                                %metaentry = %currmetaentry;
                   12034:                                undef(%currmetaentry);
                   12035:                                if ($libpartorder ne '') {
                   12036:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12037:                                }
                   12038:                            } else {
                   12039: # If no <partorder> tag available, load and inspect imported file
                   12040:                                my $impfile=&getfile($location);
                   12041:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12042:                            }
1.1069    www      12043:                            if ($#impfilepartids>=0) {
                   12044: # This problem had parts
1.1070    www      12045:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12046:                            } else {
                   12047: # Importing by turning a single problem into a problem part
                   12048: # It gets the import-tags ID as part-ID
                   12049:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12050:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12051:                            }
1.1068    www      12052:                         } else {
1.1374    raeburn  12053: # Import as problem or as normal import
                   12054:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12055:                             unless ($importmode eq 'problem') {
1.1068    www      12056: # Normal import
1.1374    raeburn  12057:                                 if (defined($token->[2]->{'id'})) {
                   12058:                                     $unikey.='_'.$token->[2]->{'id'};
                   12059:                                 }
                   12060:                             }
                   12061: # Check metadata for imported file to
                   12062: # see if it contained parts
                   12063:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12064:                                 %currmetaentry = %metaentry;
                   12065:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12066:                                                              $depthcount+1);
                   12067:                                 %metaentry = %currmetaentry;
                   12068:                                 undef(%currmetaentry);
                   12069:                                 if ($libpartorder ne '') {
                   12070:                                     $importedparts = 1;
                   12071:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12072:                                 }
                   12073:                             }
1.1067    www      12074:                         }
1.339     albertel 12075: 			if ($depthcount<20) {
1.736     albertel 12076: 			    my $metadata = 
1.1362    raeburn  12077: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12078: 					  $depthcount+1);
                   12079: 			    foreach my $meta (split(',',$metadata)) {
                   12080: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12081: 				$metathesekeys{$meta}=1;
1.339     albertel 12082: 			    }
1.1068    www      12083:                         }
1.1067    www      12084: 		    } else {
                   12085: #
                   12086: # Not importing, some other kind of non-package, non-library start tag
                   12087: # 
                   12088:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12089:                         if (defined($token->[2]->{'id'})) {
                   12090:                             $unikey.='_'.$token->[2]->{'id'};
                   12091:                         }
1.339     albertel 12092: 			if (defined($token->[2]->{'name'})) { 
                   12093: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12094: 			}
                   12095: 			$metathesekeys{$unikey}=1;
1.736     albertel 12096: 			foreach my $param (@{$token->[3]}) {
                   12097: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12098: 				$token->[2]->{$param};
1.339     albertel 12099: 			}
                   12100: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12101: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12102: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12103: 		 # only ws inside the tag, and not in default, so use default
                   12104: 		 # as value
1.599     albertel 12105: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12106: 			} elsif ( $internaltext =~ /\S/ ) {
                   12107: 		  # something interesting inside the tag
                   12108: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12109: 			} else {
1.908     albertel 12110: 		  # no interesting values, don't set a default
1.339     albertel 12111: 			}
1.172     www      12112: # end of not-a-package not-a-library import
1.339     albertel 12113: 		    }
1.172     www      12114: # end of not-a-package start tag
1.339     albertel 12115: 		}
1.172     www      12116: # the next is the end of "start tag"
1.339     albertel 12117: 	    }
                   12118: 	}
1.483     albertel 12119: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12120: 	$extension = lc($extension);
                   12121: 	if ($extension eq 'htm') { $extension='html'; }
                   12122: 
1.737     albertel 12123: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12124: 	    #no specific packages #how's our extension
                   12125: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12126: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12127: 					 \%metathesekeys);
                   12128: 	}
1.883     albertel 12129: 
                   12130: 	if (!exists($metaentry{':packages'})
                   12131: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12132: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12133: 		#no specific packages well let's get default then
                   12134: 		if ($key!~/^default&/) { next; }
1.488     albertel 12135: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12136: 					     \%metathesekeys);
                   12137: 	    }
                   12138: 	}
1.338     www      12139: # are there custom rights to evaluate
1.599     albertel 12140: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12141: 
1.338     www      12142:     #
                   12143:     # Importing a rights file here
1.339     albertel 12144:     #
                   12145: 	    unless ($depthcount) {
1.599     albertel 12146: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12147: 		my $dir=$filename;
                   12148: 		$dir=~s|[^/]*$||;
                   12149: 		$location=&filelocation($dir,$location);
1.736     albertel 12150: 		my $rights_metadata =
1.1362    raeburn  12151: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12152: 			      $depthcount+1);
                   12153: 		foreach my $rights (split(',',$rights_metadata)) {
                   12154: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12155: 		    $metathesekeys{$rights}=1;
1.339     albertel 12156: 		}
                   12157: 	    }
                   12158: 	}
1.737     albertel 12159: 	# uniqifiy package listing
                   12160: 	my %seen;
                   12161: 	my @uniq_packages =
                   12162: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12163: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12164: 
1.1369    raeburn  12165:         if (($importedresponses) || ($importedparts)) {
                   12166:             if ($importedparts) {
1.1070    www      12167: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12168:                 $metaentry{':partorder'}='';
                   12169:                 $metathesekeys{'partorder'}=1;
                   12170:             }
                   12171:             if ($importedresponses) {
                   12172: # We had imported responses and need to rebuil responseorder
                   12173:                 $metaentry{':responseorder'}='';
                   12174:                 $metathesekeys{'responseorder'}=1;
                   12175:             }
                   12176:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12177:                 my $origid = $origfiletagids[$index+1];
                   12178:                 if ($origfiletagids[$index] eq 'part') {
                   12179: # Original part, part of the problem
                   12180:                     if ($importedparts) {
                   12181:                         $metaentry{':partorder'}.=','.$origid;
                   12182:                     }
                   12183:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12184:                     if ($importedparts) {
                   12185: # We have imported parts at this position
1.1373    raeburn  12186:                         if ($importedpartids{$origid} ne '') {
                   12187:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12188:                         }
1.1369    raeburn  12189:                     }
                   12190:                     if ($importedresponses) {
                   12191: # We have imported responses at this position
1.1373    raeburn  12192:                         if ($importedrespids{$origid} ne '') {
                   12193:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12194:                         }
                   12195:                     }
                   12196:                 } else {
                   12197: # Original response item, part of the problem
                   12198:                     if ($importedresponses) {
                   12199:                         $metaentry{':responseorder'}.=','.$origid;
                   12200:                     }
                   12201:                 }
                   12202:             }
                   12203:             if ($importedparts) {
                   12204:                 $metaentry{':partorder'}=~s/^\,//;
                   12205:             }
                   12206:             if ($importedresponses) {
                   12207:                 $metaentry{':responseorder'}=~s/^\,//;
                   12208:             }
1.1070    www      12209:         }
1.737     albertel 12210: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12211: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12212: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12213:         unless ($liburi) {
                   12214: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12215:         }
1.177     www      12216: # this is the end of "was not already recently cached
1.71      www      12217:     }
1.599     albertel 12218:     return $metaentry{':'.$what};
1.261     albertel 12219: }
                   12220: 
1.488     albertel 12221: sub metadata_create_package_def {
1.483     albertel 12222:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12223:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12224:     if ($subp eq 'default') { next; }
                   12225:     
1.599     albertel 12226:     if (defined($metaentry{':packages'})) {
                   12227: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12228:     } else {
1.599     albertel 12229: 	$metaentry{':packages'}=$package;
1.483     albertel 12230:     }
                   12231:     my $value=$packagetab{$key};
                   12232:     my $unikey;
                   12233:     $unikey='parameter_0_'.$name;
1.599     albertel 12234:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12235:     $$metathesekeys{$unikey}=1;
1.599     albertel 12236:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12237: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12238:     }
1.599     albertel 12239:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12240: 	$metaentry{':'.$unikey}=
                   12241: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12242:     }
                   12243: }
                   12244: 
1.261     albertel 12245: sub metadata_generate_part0 {
                   12246:     my ($metadata,$metacache,$uri) = @_;
                   12247:     my %allnames;
1.737     albertel 12248:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12249: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12250: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12251: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12252: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12253: 	    $allnames{$name}=$part;
                   12254: 	  }
                   12255: 	}
                   12256:     }
                   12257:     foreach my $name (keys(%allnames)) {
                   12258:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12259:       my $key=":parameter_0_$name";
1.261     albertel 12260:       $$metacache{"$key.part"}='0';
                   12261:       $$metacache{"$key.name"}=$name;
1.428     albertel 12262:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12263: 					   $allnames{$name}.'_'.$name.
                   12264: 					   '.type'};
1.428     albertel 12265:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12266: 			     '.display'};
1.644     www      12267:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12268:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12269:       $$metacache{"$key.display"}=$olddis;
                   12270:     }
1.71      www      12271: }
                   12272: 
1.764     albertel 12273: # ------------------------------------------------------ Devalidate title cache
                   12274: 
                   12275: sub devalidate_title_cache {
                   12276:     my ($url)=@_;
                   12277:     if (!$env{'request.course.id'}) { return; }
                   12278:     my $symb=&symbread($url);
                   12279:     if (!$symb) { return; }
                   12280:     my $key=$env{'request.course.id'}."\0".$symb;
                   12281:     &devalidate_cache_new('title',$key);
                   12282: }
                   12283: 
1.1014    droeschl 12284: # ------------------------------------------------- Get the title of a course
                   12285: 
                   12286: sub current_course_title {
                   12287:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12288: }
1.301     www      12289: # ------------------------------------------------- Get the title of a resource
                   12290: 
                   12291: sub gettitle {
                   12292:     my $urlsymb=shift;
                   12293:     my $symb=&symbread($urlsymb);
1.534     albertel 12294:     if ($symb) {
1.620     albertel 12295: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12296: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12297: 	if (defined($cached)) { 
                   12298: 	    return $result;
                   12299: 	}
1.534     albertel 12300: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12301: 	my $title='';
1.907     albertel 12302: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12303: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12304: 	} else {
                   12305: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12306: 		    &GDBM_READER(),0640)) {
                   12307: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12308: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12309: 		untie(%bighash);
                   12310: 	    }
1.534     albertel 12311: 	}
                   12312: 	$title=~s/\&colon\;/\:/gs;
                   12313: 	if ($title) {
1.1159    www      12314: # Remember both $symb and $title for dynamic metadata
                   12315:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12316:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12317: # Cache this title and then return it
1.599     albertel 12318: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12319: 	}
                   12320: 	$urlsymb=$url;
                   12321:     }
                   12322:     my $title=&metadata($urlsymb,'title');
                   12323:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12324:     return $title;
1.301     www      12325: }
1.613     albertel 12326: 
1.614     albertel 12327: sub get_slot {
                   12328:     my ($which,$cnum,$cdom)=@_;
                   12329:     if (!$cnum || !$cdom) {
1.790     albertel 12330: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12331: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12332: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12333:     }
1.703     albertel 12334:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12335:     my %slotinfo;
                   12336:     if (exists($remembered{$key})) {
                   12337: 	$slotinfo{$which} = $remembered{$key};
                   12338:     } else {
                   12339: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12340: 	&Apache::lonhomework::showhash(%slotinfo);
                   12341: 	my ($tmp)=keys(%slotinfo);
                   12342: 	if ($tmp=~/^error:/) { return (); }
                   12343: 	$remembered{$key} = $slotinfo{$which};
                   12344:     }
1.616     albertel 12345:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12346: 	return %{$slotinfo{$which}};
                   12347:     }
                   12348:     return $slotinfo{$which};
1.614     albertel 12349: }
1.1150    raeburn  12350: 
                   12351: sub get_reservable_slots {
                   12352:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12353:     my $now = time;
                   12354:     my $reservable_info;
                   12355:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12356:     if (exists($remembered{$key})) {
                   12357:         $reservable_info = $remembered{$key};
                   12358:     } else {
                   12359:         my %resv;
                   12360:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12361:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12362:         $reservable_info = \%resv;
                   12363:         $remembered{$key} = $reservable_info;
                   12364:     }
                   12365:     return $reservable_info;
                   12366: }
                   12367: 
                   12368: sub get_course_slots {
                   12369:     my ($cnum,$cdom) = @_;
                   12370:     my $hashid=$cnum.':'.$cdom;
                   12371:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12372:     if (defined($cached)) {
                   12373:         if (ref($result) eq 'HASH') {
                   12374:             return %{$result};
                   12375:         }
                   12376:     } else {
                   12377:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12378:         my ($tmp) = keys(%slots);
                   12379:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12380:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12381:             return %slots;
                   12382:         }
                   12383:     }
                   12384:     return;
                   12385: }
                   12386: 
                   12387: sub devalidate_slots_cache {
                   12388:     my ($cnum,$cdom)=@_;
                   12389:     my $hashid=$cnum.':'.$cdom;
                   12390:     &devalidate_cache_new('allslots',$hashid);
                   12391: }
                   12392: 
1.1181    raeburn  12393: sub get_coursechange {
                   12394:     my ($cdom,$cnum) = @_;
                   12395:     if ($cdom eq '' || $cnum eq '') {
                   12396:         return unless ($env{'request.course.id'});
                   12397:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12398:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12399:     }
                   12400:     my $hashid=$cdom.'_'.$cnum;
                   12401:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12402:     if ((defined($cached)) && ($change ne '')) {
                   12403:         return $change;
                   12404:     } else {
                   12405:         my %crshash;
                   12406:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12407:         if ($crshash{'internal.contentchange'} eq '') {
                   12408:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12409:             if ($change eq '') {
                   12410:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12411:                 $change = $crshash{'internal.created'};
                   12412:             }
                   12413:         } else {
                   12414:             $change = $crshash{'internal.contentchange'};
                   12415:         }
                   12416:         my $cachetime = 600;
                   12417:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12418:     }
                   12419:     return $change;
                   12420: }
                   12421: 
                   12422: sub devalidate_coursechange_cache {
                   12423:     my ($cnum,$cdom)=@_;
                   12424:     my $hashid=$cnum.':'.$cdom;
                   12425:     &devalidate_cache_new('crschange',$hashid);
                   12426: }
                   12427: 
1.31      www      12428: # ------------------------------------------------- Update symbolic store links
                   12429: 
                   12430: sub symblist {
                   12431:     my ($mapname,%newhash)=@_;
1.438     www      12432:     $mapname=&deversion(&declutter($mapname));
1.31      www      12433:     my %hash;
1.620     albertel 12434:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12435:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12436:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12437: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12438: 		next if ($url eq 'last_known'
                   12439: 			 && $env{'form.no_update_last_known'});
                   12440: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12441: 						    $newhash{$url}->[1],
                   12442: 						    $newhash{$url}->[0]);
1.191     harris41 12443:             }
1.31      www      12444:             if (untie(%hash)) {
                   12445: 		return 'ok';
                   12446:             }
                   12447:         }
                   12448:     }
                   12449:     return 'error';
1.212     www      12450: }
                   12451: 
                   12452: # --------------------------------------------------------------- Verify a symb
                   12453: 
                   12454: sub symbverify {
1.1190    raeburn  12455:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12456:     my $thisfn=$thisurl;
1.439     www      12457:     $thisfn=&declutter($thisfn);
1.215     www      12458: # direct jump to resource in page or to a sequence - will construct own symbs
                   12459:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12460: # check URL part
1.409     www      12461:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12462: 
1.431     www      12463:     unless ($url eq $thisfn) { return 0; }
1.213     www      12464: 
1.216     www      12465:     $symb=&symbclean($symb);
1.510     www      12466:     $thisurl=&deversion($thisurl);
1.439     www      12467:     $thisfn=&deversion($thisfn);
1.213     www      12468: 
                   12469:     my %bighash;
                   12470:     my $okay=0;
1.431     www      12471: 
1.620     albertel 12472:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12473:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12474:         my $noclutter;
1.1032    raeburn  12475:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12476:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12477:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12478:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12479:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12480:                 $noclutter = 1;
                   12481:             }
                   12482:         }
                   12483:         my $ids;
                   12484:         if ($noclutter) {
                   12485:             $ids=$bighash{'ids_'.$thisurl};
                   12486:         } else {
                   12487:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12488:         }
1.1102    raeburn  12489:         unless ($ids) {
                   12490:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12491:             $ids=$bighash{$idkey};
1.216     www      12492:         }
                   12493:         if ($ids) {
                   12494: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12495:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12496:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12497:             }
1.800     albertel 12498: 	    foreach my $id (split(/\,/,$ids)) {
                   12499: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12500:                if (
                   12501:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12502:    eq $symb) {
                   12503:                    if (ref($encstate)) {
                   12504:                        $$encstate = $bighash{'encrypted_'.$id};
                   12505:                    }
1.620     albertel 12506: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12507: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12508:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12509: 		       $okay=1;
1.1202    raeburn  12510:                        last;
1.582     albertel 12511: 		   }
                   12512: 	       }
1.216     www      12513: 	   }
                   12514:         }
1.213     www      12515: 	untie(%bighash);
                   12516:     }
                   12517:     return $okay;
1.31      www      12518: }
                   12519: 
1.210     www      12520: # --------------------------------------------------------------- Clean-up symb
                   12521: 
                   12522: sub symbclean {
                   12523:     my $symb=shift;
1.568     albertel 12524:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12525: # remove version from map
                   12526:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12527: 
1.210     www      12528: # remove version from URL
                   12529:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12530: 
1.507     www      12531: # remove wrapper
                   12532: 
1.510     www      12533:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12534:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12535:     return $symb;
1.409     www      12536: }
                   12537: 
                   12538: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12539: 
                   12540: sub encode_symb {
                   12541:     my ($map,$resid,$url)=@_;
                   12542:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12543: }
1.409     www      12544: 
                   12545: sub decode_symb {
1.568     albertel 12546:     my $symb=shift;
                   12547:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12548:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12549:     return (&fixversion($map),$resid,&fixversion($url));
                   12550: }
                   12551: 
                   12552: sub fixversion {
                   12553:     my $fn=shift;
1.609     banghart 12554:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12555:     my %bighash;
                   12556:     my $uri=&clutter($fn);
1.620     albertel 12557:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12558: # is this cached?
1.599     albertel 12559:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12560:     if (defined($cached)) { return $result; }
                   12561: # unfortunately not cached, or expired
1.620     albertel 12562:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12563: 	    &GDBM_READER(),0640)) {
                   12564:  	if ($bighash{'version_'.$uri}) {
                   12565:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12566:  	    unless (($version eq 'mostrecent') || 
                   12567: 		    ($version==&getversion($uri))) {
1.440     www      12568:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12569:  	    }
                   12570:  	}
                   12571:  	untie %bighash;
1.413     www      12572:     }
1.599     albertel 12573:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12574: }
                   12575: 
                   12576: sub deversion {
                   12577:     my $url=shift;
                   12578:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12579:     return $url;
1.210     www      12580: }
                   12581: 
1.31      www      12582: # ------------------------------------------------------ Return symb list entry
                   12583: 
                   12584: sub symbread {
1.1282    raeburn  12585:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12586:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12587:     if (defined($env{$cache_str})) {
                   12588:         if ($ignorecachednull) {
                   12589:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12590:         } else {
                   12591:             return $env{$cache_str};
                   12592:         }
                   12593:     }
1.242     www      12594: # no filename provided? try from environment
1.1265    raeburn  12595:     unless ($thisfn) {
1.620     albertel 12596:         if ($env{'request.symb'}) {
                   12597: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12598: 	}
1.620     albertel 12599: 	$thisfn=$env{'request.filename'};
1.44      www      12600:     }
1.569     albertel 12601:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12602: # is that filename actually a symb? Verify, clean, and return
                   12603:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12604: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12605: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12606: 	}
1.242     www      12607:     }
1.44      www      12608:     $thisfn=declutter($thisfn);
1.31      www      12609:     my %hash;
1.37      www      12610:     my %bighash;
                   12611:     my $syval='';
1.620     albertel 12612:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12613:         my $targetfn = $thisfn;
1.609     banghart 12614:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12615:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12616:         }
1.687     albertel 12617: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12618: 	    $targetfn=$1;
                   12619: 	}
1.620     albertel 12620:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12621:                       &GDBM_READER(),0640)) {
1.481     raeburn  12622: 	    $syval=$hash{$targetfn};
1.37      www      12623:             untie(%hash);
                   12624:         }
                   12625: # ---------------------------------------------------------- There was an entry
                   12626:         if ($syval) {
1.601     albertel 12627: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12628: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12629: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12630: 		    #return $env{$cache_str}='';
1.601     albertel 12631: 		#}    
                   12632: 		#$syval.=$1;
                   12633: 	    #}
1.37      www      12634:         } else {
                   12635: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12636:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12637:                             &GDBM_READER(),0640)) {
1.37      www      12638: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12639:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12640:               unless ($ids) { 
                   12641:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12642:               }
                   12643:               unless ($ids) {
                   12644: # alias?
                   12645: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12646:               }
1.37      www      12647:               if ($ids) {
                   12648: # ------------------------------------------------------------------- Has ID(s)
                   12649:                  my @possibilities=split(/\,/,$ids);
1.39      www      12650:                  if ($#possibilities==0) {
                   12651: # ----------------------------------------------- There is only one possibility
1.37      www      12652: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12653: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12654: 						    $resid,$thisfn);
1.1282    raeburn  12655:                      if (ref($possibles) eq 'HASH') {
                   12656:                          $possibles->{$syval} = 1;    
                   12657:                      }
                   12658:                      if ($checkforblock) {
                   12659:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12660:                          if (@blockers) {
                   12661:                              $syval = '';
                   12662:                              return;
                   12663:                          }
                   12664:                      }
                   12665:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12666: # ------------------------------------------ There is more than one possibility
                   12667:                      my $realpossible=0;
1.800     albertel 12668:                      foreach my $id (@possibilities) {
                   12669: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12670:                          my $canaccess;
                   12671:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12672:                              $canaccess = 1;
                   12673:                          } else { 
                   12674:                              $canaccess = &allowed('bre',$file);
                   12675:                          }
                   12676:                          if ($canaccess) {
                   12677:          		     my ($mapid,$resid)=split(/\./,$id);
                   12678:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12679:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12680: 						             $resid,$thisfn);
                   12681:                                  if (ref($possibles) eq 'HASH') {
                   12682:                                      $possibles->{$syval} = 1;
                   12683:                                  }
                   12684:                                  if ($checkforblock) {
                   12685:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12686:                                      unless (@blockers > 0) {
                   12687:                                          $syval = $poss_syval;
                   12688:                                          $realpossible++;
                   12689:                                      }
                   12690:                                  } else {
                   12691:                                      $syval = $poss_syval;
                   12692:                                      $realpossible++;
                   12693:                                  }
                   12694:                              }
1.39      www      12695: 			 }
1.191     harris41 12696:                      }
1.39      www      12697: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12698:                  } else {
                   12699:                      $syval='';
1.37      www      12700:                  }
                   12701: 	      }
1.1282    raeburn  12702:               untie(%bighash);
1.481     raeburn  12703:            }
1.31      www      12704:         }
1.62      www      12705:         if ($syval) {
1.620     albertel 12706: 	    return $env{$cache_str}=$syval;
1.62      www      12707:         }
1.31      www      12708:     }
1.949     raeburn  12709:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12710:     return $env{$cache_str}='';
1.31      www      12711: }
                   12712: 
                   12713: # ---------------------------------------------------------- Return random seed
                   12714: 
1.32      www      12715: sub numval {
                   12716:     my $txt=shift;
                   12717:     $txt=~tr/A-J/0-9/;
                   12718:     $txt=~tr/a-j/0-9/;
                   12719:     $txt=~tr/K-T/0-9/;
                   12720:     $txt=~tr/k-t/0-9/;
                   12721:     $txt=~tr/U-Z/0-5/;
                   12722:     $txt=~tr/u-z/0-5/;
                   12723:     $txt=~s/\D//g;
1.564     albertel 12724:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12725:     return int($txt);
1.368     albertel 12726: }
                   12727: 
1.484     albertel 12728: sub numval2 {
                   12729:     my $txt=shift;
                   12730:     $txt=~tr/A-J/0-9/;
                   12731:     $txt=~tr/a-j/0-9/;
                   12732:     $txt=~tr/K-T/0-9/;
                   12733:     $txt=~tr/k-t/0-9/;
                   12734:     $txt=~tr/U-Z/0-5/;
                   12735:     $txt=~tr/u-z/0-5/;
                   12736:     $txt=~s/\D//g;
                   12737:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12738:     my $total;
                   12739:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12740:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12741:     return int($total);
                   12742: }
                   12743: 
1.575     albertel 12744: sub numval3 {
                   12745:     use integer;
                   12746:     my $txt=shift;
                   12747:     $txt=~tr/A-J/0-9/;
                   12748:     $txt=~tr/a-j/0-9/;
                   12749:     $txt=~tr/K-T/0-9/;
                   12750:     $txt=~tr/k-t/0-9/;
                   12751:     $txt=~tr/U-Z/0-5/;
                   12752:     $txt=~tr/u-z/0-5/;
                   12753:     $txt=~s/\D//g;
                   12754:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12755:     my $total;
                   12756:     foreach my $val (@txts) { $total+=$val; }
                   12757:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12758:     return $total;
                   12759: }
                   12760: 
1.675     albertel 12761: sub digest {
                   12762:     my ($data)=@_;
                   12763:     my $digest=&Digest::MD5::md5($data);
                   12764:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12765:     my ($e,$f);
                   12766:     {
                   12767:         use integer;
                   12768:         $e=($a+$b);
                   12769:         $f=($c+$d);
                   12770:         if ($_64bit) {
                   12771:             $e=(($e<<32)>>32);
                   12772:             $f=(($f<<32)>>32);
                   12773:         }
                   12774:     }
                   12775:     if (wantarray) {
                   12776: 	return ($e,$f);
                   12777:     } else {
                   12778: 	my $g;
                   12779: 	{
                   12780: 	    use integer;
                   12781: 	    $g=($e+$f);
                   12782: 	    if ($_64bit) {
                   12783: 		$g=(($g<<32)>>32);
                   12784: 	    }
                   12785: 	}
                   12786: 	return $g;
                   12787:     }
                   12788: }
                   12789: 
1.368     albertel 12790: sub latest_rnd_algorithm_id {
1.675     albertel 12791:     return '64bit5';
1.366     albertel 12792: }
1.32      www      12793: 
1.503     albertel 12794: sub get_rand_alg {
                   12795:     my ($courseid)=@_;
1.790     albertel 12796:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12797:     if ($courseid) {
1.620     albertel 12798: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12799:     }
                   12800:     return &latest_rnd_algorithm_id();
                   12801: }
                   12802: 
1.562     albertel 12803: sub validCODE {
                   12804:     my ($CODE)=@_;
                   12805:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12806:     return 0;
                   12807: }
                   12808: 
1.491     albertel 12809: sub getCODE {
1.620     albertel 12810:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12811:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12812: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12813: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12814: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12815:     }
                   12816:     return undef;
                   12817: }
1.1133    foxr     12818: #
                   12819: #  Determines the random seed for a specific context:
                   12820: #
                   12821: # parameters:
                   12822: #   symb      - in course context the symb for the seed.
                   12823: #   course_id - The course id of the form domain_coursenum.
                   12824: #   domain    - Domain for the user.
                   12825: #   course    - Course for the user.
                   12826: #   cenv      - environment of the course.
                   12827: #
                   12828: # NOTE:
                   12829: #   All parameters are picked out of the environment if missing
                   12830: #   or not defined.
                   12831: #   If a symb cannot be determined the current time is used instead.
                   12832: #
                   12833: #  For a given well defined symb, courside, domain, username,
                   12834: #  and course environment, the seed is reproducible.
                   12835: #
1.31      www      12836: sub rndseed {
1.1133    foxr     12837:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12838:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12839:     if (!defined($symb)) {
1.366     albertel 12840: 	unless ($symb=$wsymb) { return time; }
                   12841:     }
1.1146    foxr     12842:     if (!defined $courseid) { 
                   12843: 	$courseid=$wcourseid; 
                   12844:     }
                   12845:     if (!defined $domain) { $domain=$wdomain; }
                   12846:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12847: 
                   12848:     my $which;
                   12849:     if (defined($cenv->{'rndseed'})) {
                   12850: 	$which = $cenv->{'rndseed'};
                   12851:     } else {
                   12852: 	$which =&get_rand_alg($courseid);
                   12853:     }
1.491     albertel 12854:     if (defined(&getCODE())) {
1.1133    foxr     12855: 
1.675     albertel 12856: 	if ($which eq '64bit5') {
                   12857: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12858: 	} elsif ($which eq '64bit4') {
1.575     albertel 12859: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12860: 	} else {
                   12861: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12862: 	}
1.675     albertel 12863:     } elsif ($which eq '64bit5') {
                   12864: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12865:     } elsif ($which eq '64bit4') {
                   12866: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12867:     } elsif ($which eq '64bit3') {
                   12868: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12869:     } elsif ($which eq '64bit2') {
                   12870: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12871:     } elsif ($which eq '64bit') {
                   12872: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12873:     }
                   12874:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12875: }
                   12876: 
                   12877: sub rndseed_32bit {
                   12878:     my ($symb,$courseid,$domain,$username)=@_;
                   12879:     {
                   12880: 	use integer;
                   12881: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12882: 	my $symbseed=numval($symb) << 22;
                   12883: 	my $namechck=unpack("%32C*",$username) << 17;
                   12884: 	my $nameseed=numval($username) << 12;
                   12885: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12886: 	my $courseseed=unpack("%32C*",$courseid);
                   12887: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12888: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12889: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12890: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12891: 	return $num;
                   12892:     }
                   12893: }
                   12894: 
                   12895: sub rndseed_64bit {
                   12896:     my ($symb,$courseid,$domain,$username)=@_;
                   12897:     {
                   12898: 	use integer;
                   12899: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12900: 	my $symbseed=numval($symb) << 10;
                   12901: 	my $namechck=unpack("%32S*",$username);
                   12902: 	
                   12903: 	my $nameseed=numval($username) << 21;
                   12904: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12905: 	my $courseseed=unpack("%32S*",$courseid);
                   12906: 	
                   12907: 	my $num1=$symbchck+$symbseed+$namechck;
                   12908: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12909: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12910: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12911: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12912: 	return "$num1,$num2";
1.155     albertel 12913:     }
1.366     albertel 12914: }
                   12915: 
1.443     albertel 12916: sub rndseed_64bit2 {
                   12917:     my ($symb,$courseid,$domain,$username)=@_;
                   12918:     {
                   12919: 	use integer;
                   12920: 	# strings need to be an even # of cahracters long, it it is odd the
                   12921:         # last characters gets thrown away
                   12922: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12923: 	my $symbseed=numval($symb) << 10;
                   12924: 	my $namechck=unpack("%32S*",$username.' ');
                   12925: 	
                   12926: 	my $nameseed=numval($username) << 21;
1.501     albertel 12927: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12928: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12929: 	
                   12930: 	my $num1=$symbchck+$symbseed+$namechck;
                   12931: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12932: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12933: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12934: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12935: 	return "$num1,$num2";
                   12936:     }
                   12937: }
                   12938: 
                   12939: sub rndseed_64bit3 {
                   12940:     my ($symb,$courseid,$domain,$username)=@_;
                   12941:     {
                   12942: 	use integer;
                   12943: 	# strings need to be an even # of cahracters long, it it is odd the
                   12944:         # last characters gets thrown away
                   12945: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12946: 	my $symbseed=numval2($symb) << 10;
                   12947: 	my $namechck=unpack("%32S*",$username.' ');
                   12948: 	
                   12949: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12950: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12951: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12952: 	
                   12953: 	my $num1=$symbchck+$symbseed+$namechck;
                   12954: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12955: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12956: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12957: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12958: 	
1.503     albertel 12959: 	return "$num1:$num2";
1.443     albertel 12960:     }
                   12961: }
                   12962: 
1.575     albertel 12963: sub rndseed_64bit4 {
                   12964:     my ($symb,$courseid,$domain,$username)=@_;
                   12965:     {
                   12966: 	use integer;
                   12967: 	# strings need to be an even # of cahracters long, it it is odd the
                   12968:         # last characters gets thrown away
                   12969: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12970: 	my $symbseed=numval3($symb) << 10;
                   12971: 	my $namechck=unpack("%32S*",$username.' ');
                   12972: 	
                   12973: 	my $nameseed=numval3($username) << 21;
                   12974: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12975: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12976: 	
                   12977: 	my $num1=$symbchck+$symbseed+$namechck;
                   12978: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12979: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12980: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12981: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12982: 	
1.575     albertel 12983: 	return "$num1:$num2";
                   12984:     }
                   12985: }
                   12986: 
1.675     albertel 12987: sub rndseed_64bit5 {
                   12988:     my ($symb,$courseid,$domain,$username)=@_;
                   12989:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12990:     return "$num1:$num2";
                   12991: }
                   12992: 
1.366     albertel 12993: sub rndseed_CODE_64bit {
                   12994:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12995:     {
1.366     albertel 12996: 	use integer;
1.443     albertel 12997: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12998: 	my $symbseed=numval2($symb);
1.491     albertel 12999: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13000: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13001: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13002: 	my $num1=$symbseed+$CODEchck;
                   13003: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13004: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13005: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13006: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13007: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13008: 	return "$num1:$num2";
1.366     albertel 13009:     }
                   13010: }
                   13011: 
1.575     albertel 13012: sub rndseed_CODE_64bit4 {
                   13013:     my ($symb,$courseid,$domain,$username)=@_;
                   13014:     {
                   13015: 	use integer;
                   13016: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13017: 	my $symbseed=numval3($symb);
                   13018: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13019: 	my $CODEseed=numval3(&getCODE());
                   13020: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13021: 	my $num1=$symbseed+$CODEchck;
                   13022: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13023: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13024: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13025: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13026: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13027: 	return "$num1:$num2";
                   13028:     }
                   13029: }
                   13030: 
1.675     albertel 13031: sub rndseed_CODE_64bit5 {
                   13032:     my ($symb,$courseid,$domain,$username)=@_;
                   13033:     my $code = &getCODE();
                   13034:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13035:     return "$num1:$num2";
                   13036: }
                   13037: 
1.366     albertel 13038: sub setup_random_from_rndseed {
                   13039:     my ($rndseed)=@_;
1.503     albertel 13040:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13041:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13042:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13043:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13044:         } else {
                   13045:             &Math::Random::random_set_seed($num1,$num2);
                   13046:         }
1.366     albertel 13047:     } else {
                   13048: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13049:     }
1.36      albertel 13050: }
                   13051: 
1.474     albertel 13052: sub latest_receipt_algorithm_id {
1.835     albertel 13053:     return 'receipt3';
1.474     albertel 13054: }
                   13055: 
1.480     www      13056: sub recunique {
                   13057:     my $fucourseid=shift;
                   13058:     my $unique;
1.835     albertel 13059:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13060: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13061: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13062:     } else {
                   13063: 	$unique=$perlvar{'lonReceipt'};
                   13064:     }
                   13065:     return unpack("%32C*",$unique);
                   13066: }
                   13067: 
                   13068: sub recprefix {
                   13069:     my $fucourseid=shift;
                   13070:     my $prefix;
1.835     albertel 13071:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13072: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13073: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13074:     } else {
                   13075: 	$prefix=$perlvar{'lonHostID'};
                   13076:     }
                   13077:     return unpack("%32C*",$prefix);
                   13078: }
                   13079: 
1.76      www      13080: sub ireceipt {
1.474     albertel 13081:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13082: 
                   13083:     my $return =&recprefix($fucourseid).'-';
                   13084: 
                   13085:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13086: 	$env{'request.state'} eq 'construct') {
                   13087: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13088: 	return $return;
                   13089:     }
                   13090: 
1.76      www      13091:     my $cuname=unpack("%32C*",$funame);
                   13092:     my $cudom=unpack("%32C*",$fudom);
                   13093:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13094:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13095:     my $cunique=&recunique($fucourseid);
1.474     albertel 13096:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13097:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13098: 
1.790     albertel 13099: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13100: 			       
                   13101: 	$return.= ($cunique%$cuname+
                   13102: 		   $cunique%$cudom+
                   13103: 		   $cusymb%$cuname+
                   13104: 		   $cusymb%$cudom+
                   13105: 		   $cucourseid%$cuname+
                   13106: 		   $cucourseid%$cudom+
                   13107: 		   $cpart%$cuname+
                   13108: 		   $cpart%$cudom);
                   13109:     } else {
                   13110: 	$return.= ($cunique%$cuname+
                   13111: 		   $cunique%$cudom+
                   13112: 		   $cusymb%$cuname+
                   13113: 		   $cusymb%$cudom+
                   13114: 		   $cucourseid%$cuname+
                   13115: 		   $cucourseid%$cudom);
                   13116:     }
                   13117:     return $return;
1.76      www      13118: }
                   13119: 
                   13120: sub receipt {
1.474     albertel 13121:     my ($part)=@_;
1.790     albertel 13122:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13123:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13124: }
1.260     ng       13125: 
1.790     albertel 13126: sub whichuser {
                   13127:     my ($passedsymb)=@_;
                   13128:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13129:     if (defined($env{'form.grade_symb'})) {
                   13130: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13131: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13132: 	if (!$allowed &&
                   13133: 	    exists($env{'request.course.sec'}) &&
                   13134: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13135: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13136: 			      '/'.$env{'request.course.sec'});
                   13137: 	}
                   13138: 	if ($allowed) {
                   13139: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13140: 	    $courseid=$tmp_courseid;
                   13141: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13142: 	    ($name)=&get_env_multiple('form.grade_username');
                   13143: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13144: 	}
                   13145:     }
                   13146:     if (!$passedsymb) {
                   13147: 	$symb=&symbread();
                   13148:     } else {
                   13149: 	$symb=$passedsymb;
                   13150:     }
                   13151:     $courseid=$env{'request.course.id'};
                   13152:     $domain=$env{'user.domain'};
                   13153:     $name=$env{'user.name'};
                   13154:     if ($name eq 'public' && $domain eq 'public') {
                   13155: 	if (!defined($env{'form.username'})) {
                   13156: 	    $env{'form.username'}.=time.rand(10000000);
                   13157: 	}
                   13158: 	$name.=$env{'form.username'};
                   13159:     }
                   13160:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13161: 
                   13162: }
                   13163: 
1.36      albertel 13164: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13165: # returns either the contents of the file or 
                   13166: # -1 if the file doesn't exist
1.481     raeburn  13167: #
                   13168: # if the target is a file that was uploaded via DOCS, 
                   13169: # a check will be made to see if a current copy exists on the local server,
                   13170: # if it does this will be served, otherwise a copy will be retrieved from
                   13171: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13172: # the local server.   
1.472     albertel 13173: 
1.36      albertel 13174: sub getfile {
1.538     albertel 13175:     my ($file) = @_;
1.609     banghart 13176:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13177:     &repcopy($file);
                   13178:     return &readfile($file);
                   13179: }
                   13180: 
                   13181: sub repcopy_userfile {
                   13182:     my ($file)=@_;
1.1142    raeburn  13183:     my $londocroot = $perlvar{'lonDocRoot'};
                   13184:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13185:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13186:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13187: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13188:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13189:     if (-e "$file") {
1.828     www      13190: # we already have a local copy, check it out
1.538     albertel 13191: 	my @fileinfo = stat($file);
1.828     www      13192: 	my $rtncode;
                   13193: 	my $info;
1.538     albertel 13194: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13195: 	if ($lwpresp ne 'ok') {
1.828     www      13196: # there is no such file anymore, even though we had a local copy
1.482     albertel 13197: 	    if ($rtncode eq '404') {
1.538     albertel 13198: 		unlink($file);
1.482     albertel 13199: 	    }
                   13200: 	    return -1;
                   13201: 	}
                   13202: 	if ($info < $fileinfo[9]) {
1.828     www      13203: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13204: 	    return 'ok';
1.828     www      13205: 	} else {
                   13206: # the file is outdated, get rid of it
                   13207: 	    unlink($file);
1.482     albertel 13208: 	}
1.828     www      13209:     }
                   13210: # one way or the other, at this point, we don't have the file
                   13211: # construct the correct path for the file
                   13212:     my @parts = ($cdom,$cnum); 
                   13213:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13214: 	push @parts, split(/\//,$1);
                   13215:     }
                   13216:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13217:     foreach my $part (@parts) {
                   13218: 	$path .= '/'.$part;
                   13219: 	if (!-e $path) {
                   13220: 	    mkdir($path,0770);
1.482     albertel 13221: 	}
                   13222:     }
1.828     www      13223: # now the path exists for sure
                   13224: # get a user agent
                   13225:     my $transferfile=$file.'.in.transfer';
                   13226: # FIXME: this should flock
                   13227:     if (-e $transferfile) { return 'ok'; }
                   13228:     my $request;
                   13229:     $uri=~s/^\///;
1.980     raeburn  13230:     my $homeserver = &homeserver($cnum,$cdom);
                   13231:     my $protocol = $protocol{$homeserver};
                   13232:     $protocol = 'http' if ($protocol ne 'https');
                   13233:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13234:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13235: # did it work?
                   13236:     if ($response->is_error()) {
                   13237: 	unlink($transferfile);
                   13238: 	&logthis("Userfile repcopy failed for $uri");
                   13239: 	return -1;
                   13240:     }
                   13241: # worked, rename the transfer file
                   13242:     rename($transferfile,$file);
1.607     raeburn  13243:     return 'ok';
1.481     raeburn  13244: }
                   13245: 
1.517     albertel 13246: sub tokenwrapper {
                   13247:     my $uri=shift;
1.980     raeburn  13248:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13249:     $uri=~s|^/||;
1.620     albertel 13250:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13251:     my $token=$1;
1.552     albertel 13252:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13253:     if ($udom && $uname && $file) {
                   13254: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13255:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13256:         my $homeserver = &homeserver($uname,$udom);
                   13257:         my $protocol = $protocol{$homeserver};
                   13258:         $protocol = 'http' if ($protocol ne 'https');
                   13259:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13260:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13261:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13262:     } else {
                   13263:         return '/adm/notfound.html';
                   13264:     }
                   13265: }
                   13266: 
1.828     www      13267: # call with reqtype HEAD: get last modification time
                   13268: # call with reqtype GET: get the file contents
                   13269: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13270: #
1.481     raeburn  13271: sub getuploaded {
                   13272:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13273:     $uri=~s/^\///;
1.980     raeburn  13274:     my $homeserver = &homeserver($cnum,$cdom);
                   13275:     my $protocol = $protocol{$homeserver};
                   13276:     $protocol = 'http' if ($protocol ne 'https');
                   13277:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13278:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13279:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13280:     $$rtncode = $response->code;
1.482     albertel 13281:     if (! $response->is_success()) {
                   13282: 	return 'failed';
                   13283:     }      
                   13284:     if ($reqtype eq 'HEAD') {
1.486     www      13285: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13286:     } elsif ($reqtype eq 'GET') {
                   13287: 	$$info = $response->content;
1.472     albertel 13288:     }
1.482     albertel 13289:     return 'ok';
1.36      albertel 13290: }
                   13291: 
1.481     raeburn  13292: sub readfile {
                   13293:     my $file = shift;
                   13294:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13295:     my $fh;
1.1359    raeburn  13296:     open($fh,"<",$file);
1.481     raeburn  13297:     my $a='';
1.800     albertel 13298:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13299:     return $a;
                   13300: }
                   13301: 
1.36      albertel 13302: sub filelocation {
1.590     banghart 13303:     my ($dir,$file) = @_;
                   13304:     my $location;
                   13305:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13306: 
                   13307:     if ($file =~ m-^/adm/-) {
                   13308: 	$file=~s-^/adm/wrapper/-/-;
                   13309: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13310:     }
1.882     albertel 13311: 
1.1139    www      13312:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13313:         $location = $file;
1.609     banghart 13314:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13315:         my ($udom,$uname,$filename)=
1.811     albertel 13316:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13317:         my $home=&homeserver($uname,$udom);
                   13318:         my $is_me=0;
                   13319:         my @ids=&current_machine_ids();
                   13320:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13321:         if ($is_me) {
1.1117    foxr     13322:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13323:         } else {
                   13324:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13325:   	      $udom.'/'.$uname.'/'.$filename;
                   13326:         }
1.882     albertel 13327:     } elsif ($file =~ m-^/adm/-) {
                   13328: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13329:     } else {
                   13330:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13331:         $file=~s:^/(res|priv)/:/:;
                   13332:         my $space=$1;
1.590     banghart 13333:         if ( !( $file =~ m:^/:) ) {
                   13334:             $location = $dir. '/'.$file;
                   13335:         } else {
1.1142    raeburn  13336:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13337:         }
1.59      albertel 13338:     }
1.590     banghart 13339:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13340:     while ($location=~m{/\.\./}) {
                   13341: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13342: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13343: 	} else {
                   13344: 	    $location=~ s{/\.\./}{/}g;
                   13345: 	}
                   13346:     } #remove dir/..
1.590     banghart 13347:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13348:     return $location;
1.46      www      13349: }
1.36      albertel 13350: 
1.46      www      13351: sub hreflocation {
                   13352:     my ($dir,$file)=@_;
1.980     raeburn  13353:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13354: 	$file=filelocation($dir,$file);
1.700     albertel 13355:     } elsif ($file=~m-^/adm/-) {
                   13356: 	$file=~s-^/adm/wrapper/-/-;
                   13357: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13358:     }
                   13359:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13360: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13361:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13362: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13363: 	        {/uploaded/$1/$2/}x;
1.46      www      13364:     }
1.913     albertel 13365:     if ($file=~ m{^/userfiles/}) {
                   13366: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13367:     }
1.462     albertel 13368:     return $file;
1.465     albertel 13369: }
                   13370: 
1.1139    www      13371: 
                   13372: 
                   13373: 
                   13374: 
1.465     albertel 13375: sub current_machine_domains {
1.853     albertel 13376:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13377: }
                   13378: 
                   13379: sub machine_domains {
                   13380:     my ($hostname) = @_;
1.465     albertel 13381:     my @domains;
1.838     albertel 13382:     my %hostname = &all_hostnames();
1.465     albertel 13383:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13384: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13385: 	if ($hostname eq $name) {
1.844     albertel 13386: 	    push(@domains,&host_domain($id));
1.465     albertel 13387: 	}
                   13388:     }
                   13389:     return @domains;
                   13390: }
                   13391: 
                   13392: sub current_machine_ids {
1.853     albertel 13393:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13394: }
                   13395: 
                   13396: sub machine_ids {
                   13397:     my ($hostname) = @_;
                   13398:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13399:     my @ids;
1.888     albertel 13400:     my %name_to_host = &all_names();
1.889     albertel 13401:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13402: 	return @{ $name_to_host{$hostname} };
                   13403:     }
                   13404:     return;
1.31      www      13405: }
                   13406: 
1.824     raeburn  13407: sub additional_machine_domains {
                   13408:     my @domains;
1.1359    raeburn  13409:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13410:     while( my $line = <$fh>) {
                   13411:         $line =~ s/\s//g;
                   13412:         push(@domains,$line);
                   13413:     }
                   13414:     return @domains;
                   13415: }
                   13416: 
                   13417: sub default_login_domain {
                   13418:     my $domain = $perlvar{'lonDefDomain'};
                   13419:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13420:     foreach my $posdom (&current_machine_domains(),
                   13421:                         &additional_machine_domains()) {
                   13422:         if (lc($posdom) eq lc($testdomain)) {
                   13423:             $domain=$posdom;
                   13424:             last;
                   13425:         }
                   13426:     }
                   13427:     return $domain;
                   13428: }
                   13429: 
1.31      www      13430: # ------------------------------------------------------------- Declutters URLs
                   13431: 
                   13432: sub declutter {
                   13433:     my $thisfn=shift;
1.569     albertel 13434:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13435:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13436:         $thisfn=~s{^/home/httpd/html}{};
                   13437:     }
1.31      www      13438:     $thisfn=~s/^\///;
1.697     albertel 13439:     $thisfn=~s|^adm/wrapper/||;
                   13440:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13441:     $thisfn=~s/^res\///;
1.1172    bisitz   13442:     $thisfn=~s/^priv\///;
1.1032    raeburn  13443:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13444:         $thisfn=~s/\?.+$//;
                   13445:     }
1.268     www      13446:     return $thisfn;
                   13447: }
                   13448: 
                   13449: # ------------------------------------------------------------- Clutter up URLs
                   13450: 
                   13451: sub clutter {
                   13452:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13453:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13454: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13455:        $thisfn='/res'.$thisfn; 
                   13456:     }
1.1031    raeburn  13457:     if ($thisfn !~m|^/adm|) {
                   13458: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13459: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13460: 	} else {
                   13461: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13462: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13463: 	    if ($embstyle eq 'ssi'
                   13464: 		|| ($embstyle eq 'hdn')
                   13465: 		|| ($embstyle eq 'rat')
                   13466: 		|| ($embstyle eq 'prv')
                   13467: 		|| ($embstyle eq 'ign')) {
                   13468: 		#do nothing with these
                   13469: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13470: 		|| ($embstyle eq 'emb')
                   13471: 		|| ($embstyle eq 'wrp')) {
                   13472: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13473: 	    } elsif ($embstyle eq 'unk'
                   13474: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13475: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13476: 	    } else {
1.718     www      13477: #		&logthis("Got a blank emb style");
1.695     albertel 13478: 	    }
1.694     albertel 13479: 	}
1.1343    raeburn  13480:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13481:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13482:     }
1.31      www      13483:     return $thisfn;
1.12      www      13484: }
                   13485: 
1.787     albertel 13486: sub clutter_with_no_wrapper {
                   13487:     my $uri = &clutter(shift);
                   13488:     if ($uri =~ m-^/adm/-) {
                   13489: 	$uri =~ s-^/adm/wrapper/-/-;
                   13490: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13491:     }
                   13492:     return $uri;
                   13493: }
                   13494: 
1.557     albertel 13495: sub freeze_escape {
                   13496:     my ($value)=@_;
                   13497:     if (ref($value)) {
                   13498: 	$value=&nfreeze($value);
                   13499: 	return '__FROZEN__'.&escape($value);
                   13500:     }
                   13501:     return &escape($value);
                   13502: }
                   13503: 
1.11      www      13504: 
1.557     albertel 13505: sub thaw_unescape {
                   13506:     my ($value)=@_;
                   13507:     if ($value =~ /^__FROZEN__/) {
                   13508: 	substr($value,0,10,undef);
                   13509: 	$value=&unescape($value);
                   13510: 	return &thaw($value);
                   13511:     }
                   13512:     return &unescape($value);
                   13513: }
                   13514: 
1.436     albertel 13515: sub correct_line_ends {
                   13516:     my ($result)=@_;
                   13517:     $$result =~s/\r\n/\n/mg;
                   13518:     $$result =~s/\r/\n/mg;
1.415     albertel 13519: }
1.1       albertel 13520: # ================================================================ Main Program
                   13521: 
1.184     www      13522: sub goodbye {
1.204     albertel 13523:    &logthis("Starting Shut down");
1.443     albertel 13524: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13525:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13526: #converted
1.599     albertel 13527: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13528:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13529: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13530: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13531: #1.1 only
1.870     albertel 13532: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13533: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13534: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13535: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13536:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13537:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13538:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13539:    &flushcourselogs();
                   13540:    &logthis("Shutting down");
                   13541: }
                   13542: 
1.852     albertel 13543: sub get_dns {
1.1210    raeburn  13544:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13545:     if (!$ignore_cache) {
                   13546: 	my ($content,$cached)=
                   13547: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13548: 	if ($cached) {
1.1210    raeburn  13549: 	    &$func($content,$hashref);
1.869     albertel 13550: 	    return;
                   13551: 	}
                   13552:     }
                   13553: 
                   13554:     my %alldns;
1.1379    raeburn  13555:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13556:         foreach my $dns (<$config>) {
                   13557: 	    next if ($dns !~ /^\^(\S*)/x);
                   13558:             my $line = $1;
                   13559:             my ($host,$protocol) = split(/:/,$line);
                   13560:             if ($protocol ne 'https') {
                   13561:                 $protocol = 'http';
                   13562:             }
                   13563: 	    $alldns{$host} = $protocol;
1.979     raeburn  13564:         }
1.1379    raeburn  13565:         close($config);
1.869     albertel 13566:     }
                   13567:     while (%alldns) {
1.1263    raeburn  13568: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13569: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13570:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13571:         delete($alldns{$dns});
1.852     albertel 13572: 	next if ($response->is_error());
1.1379    raeburn  13573:         if ($url eq '/adm/dns/loncapaCRL') {
                   13574:             return &$func($response);
                   13575:         } else {
                   13576: 	    my @content = split("\n",$response->content);
                   13577: 	    unless ($nocache) {
                   13578: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   13579: 	    }
                   13580: 	    &$func(\@content,$hashref);
                   13581:             return;
                   13582:         }
                   13583:     }
                   13584:     my $which = (split('/',$url,4))[3];
                   13585:     if ($which eq 'loncapaCRL') {
                   13586:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   13587:         if (-e $diskfile) {
                   13588:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   13589:         } else {
                   13590:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   13591:         }
                   13592:     } else {
                   13593:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13594:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13595:             my @content = <$config>;
                   13596:             close($config);
                   13597:             &$func(\@content,$hashref);
                   13598:         }
1.852     albertel 13599:     }
1.1210    raeburn  13600:     return;
                   13601: }
                   13602: 
                   13603: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13604: sub parse_dns_checksums_tab {
1.1210    raeburn  13605:     my ($lines,$hashref) = @_;
1.1264    raeburn  13606:     my $lonhost = $perlvar{'lonHostID'};
                   13607:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13608:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13609:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13610:     my $webconfdir = '/etc/httpd/conf';
                   13611:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13612:         $webconfdir = '/etc/apache2';
                   13613:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13614:         if ($1 >= 10) {
                   13615:             $webconfdir = '/etc/apache2';
                   13616:         }
                   13617:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13618:         if ($1 >= 10.0) {
                   13619:             $webconfdir = '/etc/apache2';
                   13620:         }
                   13621:     }
1.1210    raeburn  13622:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13623:     my (%chksum,%revnum);
                   13624:     if (ref($lines) eq 'ARRAY') {
                   13625:         chomp(@{$lines});
1.1238    raeburn  13626:         my $version = shift(@{$lines});
                   13627:         if ($version eq $release) {  
1.1210    raeburn  13628:             foreach my $line (@{$lines}) {
1.1238    raeburn  13629:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13630:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13631:                     if ($webconfdir eq '/etc/apache2') {
                   13632:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13633:                     }
                   13634:                 }
1.1238    raeburn  13635:                 $chksum{$file} = $shasum;
                   13636:                 $revnum{$file} = $version;
1.1210    raeburn  13637:             }
                   13638:             if (ref($hashref) eq 'HASH') {
                   13639:                 %{$hashref} = (
                   13640:                                 sums     => \%chksum,
                   13641:                                 versions => \%revnum,
                   13642:                               );
                   13643:             }
                   13644:         }
                   13645:     }
1.869     albertel 13646:     return;
1.852     albertel 13647: }
1.1210    raeburn  13648: 
                   13649: sub fetch_dns_checksums {
1.1238    raeburn  13650:     my %checksums;
                   13651:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13652:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13653:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13654:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13655:              \%checksums);
1.1210    raeburn  13656:     return \%checksums;
                   13657: }
                   13658: 
1.1379    raeburn  13659: sub fetch_crl_pemfile {
                   13660:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   13661: }
                   13662: 
                   13663: sub save_crl_pem {
                   13664:     my ($response) = @_;
1.1380    raeburn  13665:     my ($msg,$hadchanges);
1.1379    raeburn  13666:     if (ref($response)) {
                   13667:         my $now = time;
                   13668:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   13669:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   13670:         if (open(my $fh,'>',"$tmpcrl")) {
                   13671:             print $fh $response->content;
                   13672:             close($fh);
                   13673:             if (-e $lonca) {
                   13674:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   13675:                     my $check = <PIPE>;
                   13676:                     close(PIPE);
                   13677:                     chomp($check);
                   13678:                     if ($check eq 'verify OK') {
                   13679:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  13680:                         my $backup;
1.1379    raeburn  13681:                         if (-e $dest) {
1.1380    raeburn  13682:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   13683:                                 $backup = 'ok';
                   13684:                             }
1.1379    raeburn  13685:                         }
                   13686:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   13687:                             $msg = 'ok';
1.1380    raeburn  13688:                             if ($backup) {
                   13689:                                 my (%oldnums,%newnums);
                   13690:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   13691:                                     while (<PIPE>) {
                   13692:                                         $oldnums{(split(/:/))[1]} = 1;
                   13693:                                     }
                   13694:                                     close(PIPE);
                   13695:                                 }
                   13696:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   13697:                                     while(<PIPE>) {
                   13698:                                         $newnums{(split(/:/))[1]} = 1;
                   13699:                                     }
                   13700:                                     close(PIPE);
                   13701:                                 }
                   13702:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   13703:                                     unless (exists($oldnums{$key})) {
                   13704:                                         $hadchanges = 1;
                   13705:                                         last;
                   13706:                                     }
                   13707:                                 }
                   13708:                                 unless ($hadchanges) {
                   13709:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   13710:                                         unless (exists($newnums{$key})) {
                   13711:                                             $hadchanges = 1;
                   13712:                                             last;
                   13713:                                         }
                   13714:                                     }
                   13715:                                 }
                   13716:                             }
1.1379    raeburn  13717:                         }
                   13718:                     } else {
                   13719:                         unlink($tmpcrl);
                   13720:                     }
                   13721:                 } else {
                   13722:                     unlink($tmpcrl);
                   13723:                 }
                   13724:             } else {
                   13725:                 unlink($tmpcrl);
                   13726:             }
                   13727:         }
                   13728:     }
1.1380    raeburn  13729:     return ($msg,$hadchanges);
1.1379    raeburn  13730: }
                   13731: 
1.327     albertel 13732: # ------------------------------------------------------------ Read domain file
                   13733: {
1.852     albertel 13734:     my $loaded;
1.846     albertel 13735:     my %domain;
                   13736: 
1.852     albertel 13737:     sub parse_domain_tab {
                   13738: 	my ($lines) = @_;
                   13739: 	foreach my $line (@$lines) {
                   13740: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13741: 
1.846     albertel 13742: 	    chomp($line);
1.852     albertel 13743: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13744: 	    my %this_domain;
                   13745: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13746: 			       'lang_def', 'city', 'longi', 'lati',
                   13747: 			       'primary') {
                   13748: 		$this_domain{$field} = shift(@elements);
                   13749: 	    }
                   13750: 	    $domain{$name} = \%this_domain;
1.852     albertel 13751: 	}
                   13752:     }
1.864     albertel 13753: 
                   13754:     sub reset_domain_info {
                   13755: 	undef($loaded);
                   13756: 	undef(%domain);
                   13757:     }
                   13758: 
1.852     albertel 13759:     sub load_domain_tab {
1.1293    raeburn  13760: 	my ($ignore_cache,$nocache) = @_;
                   13761: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13762: 	my $fh;
1.1359    raeburn  13763: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13764: 	    my @lines = <$fh>;
                   13765: 	    &parse_domain_tab(\@lines);
1.448     albertel 13766: 	}
1.852     albertel 13767: 	close($fh);
                   13768: 	$loaded = 1;
1.327     albertel 13769:     }
1.846     albertel 13770: 
                   13771:     sub domain {
1.852     albertel 13772: 	&load_domain_tab() if (!$loaded);
                   13773: 
1.846     albertel 13774: 	my ($name,$what) = @_;
                   13775: 	return if ( !exists($domain{$name}) );
                   13776: 
                   13777: 	if (!$what) {
                   13778: 	    return $domain{$name}{'description'};
                   13779: 	}
                   13780: 	return $domain{$name}{$what};
                   13781:     }
1.974     raeburn  13782: 
                   13783:     sub domain_info {
                   13784:         &load_domain_tab() if (!$loaded);
                   13785:         return %domain;
                   13786:     }
                   13787: 
1.327     albertel 13788: }
                   13789: 
                   13790: 
1.1       albertel 13791: # ------------------------------------------------------------- Read hosts file
                   13792: {
1.838     albertel 13793:     my %hostname;
1.844     albertel 13794:     my %hostdom;
1.845     albertel 13795:     my %libserv;
1.852     albertel 13796:     my $loaded;
1.888     albertel 13797:     my %name_to_host;
1.1074    raeburn  13798:     my %internetdom;
1.1107    raeburn  13799:     my %LC_dns_serv;
1.852     albertel 13800: 
                   13801:     sub parse_hosts_tab {
                   13802: 	my ($file) = @_;
                   13803: 	foreach my $configline (@$file) {
                   13804: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13805:             chomp($configline);
                   13806: 	    if ($configline =~ /^\^/) {
                   13807:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13808:                     $LC_dns_serv{$1} = 1;
                   13809:                 }
                   13810:                 next;
                   13811:             }
1.1074    raeburn  13812: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13813: 	    $name=~s/\s//g;
                   13814: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13815:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13816:                     my $curr = $hostname{$id};
                   13817:                     my $skip;
                   13818:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13819:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13820:                             $skip = 1;
                   13821:                         } else {
                   13822:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13823:                         }
                   13824:                     }
                   13825:                     unless ($skip) {
                   13826:                         push(@{$name_to_host{$name}},$id);
                   13827:                     }
                   13828:                 } else {
                   13829:                     push(@{$name_to_host{$name}},$id);
                   13830:                 }
1.852     albertel 13831: 		$hostname{$id}=$name;
                   13832: 		$hostdom{$id}=$domain;
                   13833: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13834:                 if (defined($protocol)) {
                   13835:                     if ($protocol eq 'https') {
                   13836:                         $protocol{$id} = $protocol;
                   13837:                     } else {
                   13838:                         $protocol{$id} = 'http'; 
                   13839:                     }
1.968     raeburn  13840:                 } else {
1.969     raeburn  13841:                     $protocol{$id} = 'http';
1.968     raeburn  13842:                 }
1.1074    raeburn  13843:                 if (defined($intdom)) {
                   13844:                     $internetdom{$id} = $intdom;
                   13845:                 }
1.852     albertel 13846: 	    }
                   13847: 	}
                   13848:     }
1.864     albertel 13849:     
                   13850:     sub reset_hosts_info {
1.897     albertel 13851: 	&purge_remembered();
1.864     albertel 13852: 	&reset_domain_info();
                   13853: 	&reset_hosts_ip_info();
1.1339    raeburn  13854:         undef(%internetdom);
1.892     albertel 13855: 	undef(%name_to_host);
1.864     albertel 13856: 	undef(%hostname);
                   13857: 	undef(%hostdom);
                   13858: 	undef(%libserv);
                   13859: 	undef($loaded);
                   13860:     }
1.1       albertel 13861: 
1.852     albertel 13862:     sub load_hosts_tab {
1.1293    raeburn  13863: 	my ($ignore_cache,$nocache) = @_;
                   13864: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13865: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13866: 	my @config = <$config>;
                   13867: 	&parse_hosts_tab(\@config);
                   13868: 	close($config);
                   13869: 	$loaded=1;
1.1       albertel 13870:     }
1.852     albertel 13871: 
1.838     albertel 13872:     sub hostname {
1.852     albertel 13873: 	&load_hosts_tab() if (!$loaded);
                   13874: 
1.838     albertel 13875: 	my ($lonid) = @_;
                   13876: 	return $hostname{$lonid};
                   13877:     }
1.845     albertel 13878: 
1.838     albertel 13879:     sub all_hostnames {
1.852     albertel 13880: 	&load_hosts_tab() if (!$loaded);
                   13881: 
1.838     albertel 13882: 	return %hostname;
                   13883:     }
1.845     albertel 13884: 
1.888     albertel 13885:     sub all_names {
1.1293    raeburn  13886:         my ($ignore_cache,$nocache) = @_;
                   13887: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13888: 
                   13889: 	return %name_to_host;
                   13890:     }
                   13891: 
1.974     raeburn  13892:     sub all_host_domain {
                   13893:         &load_hosts_tab() if (!$loaded);
                   13894:         return %hostdom;
                   13895:     }
                   13896: 
1.1339    raeburn  13897:     sub all_host_intdom {
                   13898:         &load_hosts_tab() if (!$loaded);
                   13899:         return %internetdom;
                   13900:     }
                   13901: 
1.845     albertel 13902:     sub is_library {
1.852     albertel 13903: 	&load_hosts_tab() if (!$loaded);
                   13904: 
1.845     albertel 13905: 	return exists($libserv{$_[0]});
                   13906:     }
                   13907: 
                   13908:     sub all_library {
1.852     albertel 13909: 	&load_hosts_tab() if (!$loaded);
                   13910: 
1.845     albertel 13911: 	return %libserv;
                   13912:     }
                   13913: 
1.1062    droeschl 13914:     sub unique_library {
                   13915: 	#2x reverse removes all hostnames that appear more than once
                   13916:         my %unique = reverse &all_library();
                   13917:         return reverse %unique;
                   13918:     }
                   13919: 
1.841     albertel 13920:     sub get_servers {
1.852     albertel 13921: 	&load_hosts_tab() if (!$loaded);
                   13922: 
1.841     albertel 13923: 	my ($domain,$type) = @_;
                   13924: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13925: 	                                          : %hostname;
                   13926: 	my %result;
1.842     albertel 13927: 	if (ref($domain) eq 'ARRAY') {
                   13928: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13929: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13930: 		    $result{$host} = $hostname;
                   13931: 		}
                   13932: 	    }
                   13933: 	} else {
                   13934: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13935: 		if ($hostdom{$host} eq $domain) {
                   13936: 		    $result{$host} = $hostname;
                   13937: 		}
1.841     albertel 13938: 	    }
                   13939: 	}
                   13940: 	return %result;
                   13941:     }
1.845     albertel 13942: 
1.1062    droeschl 13943:     sub get_unique_servers {
                   13944:         my %unique = reverse &get_servers(@_);
                   13945: 	return reverse %unique;
                   13946:     }
                   13947: 
1.844     albertel 13948:     sub host_domain {
1.852     albertel 13949: 	&load_hosts_tab() if (!$loaded);
                   13950: 
1.844     albertel 13951: 	my ($lonid) = @_;
                   13952: 	return $hostdom{$lonid};
                   13953:     }
                   13954: 
1.841     albertel 13955:     sub all_domains {
1.852     albertel 13956: 	&load_hosts_tab() if (!$loaded);
                   13957: 
1.841     albertel 13958: 	my %seen;
                   13959: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13960: 	return @uniq;
                   13961:     }
1.1074    raeburn  13962: 
                   13963:     sub internet_dom {
                   13964:         &load_hosts_tab() if (!$loaded);
                   13965: 
                   13966:         my ($lonid) = @_;
                   13967:         return $internetdom{$lonid};
                   13968:     }
1.1107    raeburn  13969: 
                   13970:     sub is_LC_dns {
                   13971:         &load_hosts_tab() if (!$loaded);
                   13972: 
                   13973:         my ($hostname) = @_;
                   13974:         return exists($LC_dns_serv{$hostname});
                   13975:     }
                   13976: 
1.1       albertel 13977: }
                   13978: 
1.847     albertel 13979: { 
                   13980:     my %iphost;
1.856     albertel 13981:     my %name_to_ip;
                   13982:     my %lonid_to_ip;
1.869     albertel 13983: 
1.847     albertel 13984:     sub get_hosts_from_ip {
                   13985: 	my ($ip) = @_;
                   13986: 	my %iphosts = &get_iphost();
                   13987: 	if (ref($iphosts{$ip})) {
                   13988: 	    return @{$iphosts{$ip}};
                   13989: 	}
                   13990: 	return;
1.839     albertel 13991:     }
1.864     albertel 13992:     
                   13993:     sub reset_hosts_ip_info {
                   13994: 	undef(%iphost);
                   13995: 	undef(%name_to_ip);
                   13996: 	undef(%lonid_to_ip);
                   13997:     }
1.856     albertel 13998: 
                   13999:     sub get_host_ip {
                   14000: 	my ($lonid) = @_;
                   14001: 	if (exists($lonid_to_ip{$lonid})) {
                   14002: 	    return $lonid_to_ip{$lonid};
                   14003: 	}
                   14004: 	my $name=&hostname($lonid);
                   14005:    	my $ip = gethostbyname($name);
                   14006: 	return if (!$ip || length($ip) ne 4);
                   14007: 	$ip=inet_ntoa($ip);
                   14008: 	$name_to_ip{$name}   = $ip;
                   14009: 	$lonid_to_ip{$lonid} = $ip;
                   14010: 	return $ip;
                   14011:     }
1.847     albertel 14012:     
                   14013:     sub get_iphost {
1.1293    raeburn  14014: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14015: 
1.869     albertel 14016: 	if (!$ignore_cache) {
                   14017: 	    if (%iphost) {
                   14018: 		return %iphost;
                   14019: 	    }
                   14020: 	    my ($ip_info,$cached)=
                   14021: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14022: 	    if ($cached) {
                   14023: 		%iphost      = %{$ip_info->[0]};
                   14024: 		%name_to_ip  = %{$ip_info->[1]};
                   14025: 		%lonid_to_ip = %{$ip_info->[2]};
                   14026: 		return %iphost;
                   14027: 	    }
                   14028: 	}
1.894     albertel 14029: 
                   14030: 	# get yesterday's info for fallback
                   14031: 	my %old_name_to_ip;
                   14032: 	my ($ip_info,$cached)=
                   14033: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14034: 	if ($cached) {
                   14035: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14036: 	}
                   14037: 
1.1293    raeburn  14038: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14039: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14040: 	    my $ip;
                   14041: 	    if (!exists($name_to_ip{$name})) {
                   14042: 		$ip = gethostbyname($name);
                   14043: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14044: 		    if (defined($old_name_to_ip{$name})) {
                   14045: 			$ip = $old_name_to_ip{$name};
                   14046: 			&logthis("Can't find $name defaulting to old $ip");
                   14047: 		    } else {
                   14048: 			&logthis("Name $name no IP found");
                   14049: 			next;
                   14050: 		    }
                   14051: 		} else {
                   14052: 		    $ip=inet_ntoa($ip);
1.847     albertel 14053: 		}
                   14054: 		$name_to_ip{$name} = $ip;
                   14055: 	    } else {
                   14056: 		$ip = $name_to_ip{$name};
1.653     albertel 14057: 	    }
1.888     albertel 14058: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14059: 		$lonid_to_ip{$id} = $ip;
                   14060: 	    }
                   14061: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14062: 	}
1.1293    raeburn  14063:         unless ($nocache) {
                   14064: 	    &do_cache_new('iphost','iphost',
                   14065: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14066: 		          48*60*60);
                   14067:         }
1.869     albertel 14068: 
1.847     albertel 14069: 	return %iphost;
1.598     albertel 14070:     }
                   14071: 
1.992     raeburn  14072:     #
                   14073:     #  Given a DNS returns the loncapa host name for that DNS 
                   14074:     # 
                   14075:     sub host_from_dns {
                   14076:         my ($dns) = @_;
                   14077:         my @hosts;
                   14078:         my $ip;
                   14079: 
1.993     raeburn  14080:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14081:             $ip = $name_to_ip{$dns};
                   14082:         }
                   14083:         if (!$ip) {
                   14084:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14085:             if (length($ip) == 4) { 
                   14086: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14087:             }
                   14088:         }
                   14089:         if ($ip) {
                   14090: 	    @hosts = get_hosts_from_ip($ip);
                   14091: 	    return $hosts[0];
                   14092:         }
                   14093:         return undef;
1.986     foxr     14094:     }
1.992     raeburn  14095: 
1.1074    raeburn  14096:     sub get_internet_names {
                   14097:         my ($lonid) = @_;
                   14098:         return if ($lonid eq '');
                   14099:         my ($idnref,$cached)=
                   14100:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14101:         if ($cached) {
                   14102:             return $idnref;
                   14103:         }
                   14104:         my $ip = &get_host_ip($lonid);
                   14105:         my @hosts = &get_hosts_from_ip($ip);
                   14106:         my %iphost = &get_iphost();
                   14107:         my (@idns,%seen);
                   14108:         foreach my $id (@hosts) {
                   14109:             my $dom = &host_domain($id);
                   14110:             my $prim_id = &domain($dom,'primary');
                   14111:             my $prim_ip = &get_host_ip($prim_id);
                   14112:             next if ($seen{$prim_ip});
                   14113:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14114:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14115:                     my $intdom = &internet_dom($id);
                   14116:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14117:                         push(@idns,$intdom);
                   14118:                     }
                   14119:                 }
                   14120:             }
                   14121:             $seen{$prim_ip} = 1;
                   14122:         }
1.1219    raeburn  14123:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14124:     }
                   14125: 
1.986     foxr     14126: }
                   14127: 
1.1079    raeburn  14128: sub all_loncaparevs {
1.1249    raeburn  14129:     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  14130: }
                   14131: 
1.1227    raeburn  14132: # ---------------------------------------------------------- Read loncaparev table
                   14133: {
                   14134:     sub load_loncaparevs { 
                   14135:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14136:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14137:                 while (my $configline=<$config>) {
                   14138:                     chomp($configline);
                   14139:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14140:                     $loncaparevs{$hostid}=$loncaparev;
                   14141:                 }
                   14142:                 close($config);
                   14143:             }
                   14144:         }
                   14145:     }
                   14146: }
                   14147: 
                   14148: # ---------------------------------------------------------- Read serverhostID table
                   14149: {
                   14150:     sub load_serverhomeIDs {
                   14151:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14152:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14153:                 while (my $configline=<$config>) {
                   14154:                     chomp($configline);
                   14155:                     my ($name,$id)=split(/:/,$configline);
                   14156:                     $serverhomeIDs{$name}=$id;
                   14157:                 }
                   14158:                 close($config);
                   14159:             }
                   14160:         }
                   14161:     }
                   14162: }
                   14163: 
                   14164: 
1.862     albertel 14165: BEGIN {
                   14166: 
                   14167: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14168:     unless ($readit) {
                   14169: {
                   14170:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14171:     %perlvar = (%perlvar,%{$configvars});
                   14172: }
                   14173: 
                   14174: 
1.1       albertel 14175: # ------------------------------------------------------ Read spare server file
                   14176: {
1.1359    raeburn  14177:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14178: 
                   14179:     while (my $configline=<$config>) {
                   14180:        chomp($configline);
1.284     matthew  14181:        if ($configline) {
1.784     albertel 14182: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14183: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14184: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14185:        }
                   14186:     }
1.448     albertel 14187:     close($config);
1.1       albertel 14188: }
1.11      www      14189: # ------------------------------------------------------------ Read permissions
                   14190: {
1.1359    raeburn  14191:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14192: 
                   14193:     while (my $configline=<$config>) {
1.448     albertel 14194: 	chomp($configline);
                   14195: 	if ($configline) {
                   14196: 	    my ($role,$perm)=split(/ /,$configline);
                   14197: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14198: 	}
1.11      www      14199:     }
1.448     albertel 14200:     close($config);
1.11      www      14201: }
                   14202: 
                   14203: # -------------------------------------------- Read plain texts for permissions
                   14204: {
1.1359    raeburn  14205:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14206: 
                   14207:     while (my $configline=<$config>) {
1.448     albertel 14208: 	chomp($configline);
                   14209: 	if ($configline) {
1.742     raeburn  14210: 	    my ($short,@plain)=split(/:/,$configline);
                   14211:             %{$prp{$short}} = ();
                   14212: 	    if (@plain > 0) {
                   14213:                 $prp{$short}{'std'} = $plain[0];
                   14214:                 for (my $i=1; $i<@plain; $i++) {
                   14215:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14216:                 }
                   14217:             }
1.448     albertel 14218: 	}
1.135     www      14219:     }
1.448     albertel 14220:     close($config);
1.135     www      14221: }
                   14222: 
                   14223: # ---------------------------------------------------------- Read package table
                   14224: {
1.1359    raeburn  14225:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14226: 
                   14227:     while (my $configline=<$config>) {
1.483     albertel 14228: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14229: 	chomp($configline);
                   14230: 	my ($short,$plain)=split(/:/,$configline);
                   14231: 	my ($pack,$name)=split(/\&/,$short);
                   14232: 	if ($plain ne '') {
                   14233: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14234: 	    $packagetab{$short}=$plain; 
                   14235: 	}
1.11      www      14236:     }
1.448     albertel 14237:     close($config);
1.329     matthew  14238: }
                   14239: 
1.1073    raeburn  14240: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14241: 
                   14242: &load_loncaparevs();
1.1073    raeburn  14243: 
1.1074    raeburn  14244: # ---------------------------------------------------------- Read serverhostID table
                   14245: 
1.1227    raeburn  14246: &load_serverhomeIDs();
                   14247: 
                   14248: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14249: {
                   14250:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14251:     if (-e $file) {
                   14252:         my $parser = HTML::LCParser->new($file);
                   14253:         while (my $token = $parser->get_token()) {
                   14254:             if ($token->[0] eq 'S') {
                   14255:                 my $item = $token->[1];
                   14256:                 my $name = $token->[2]{'name'};
                   14257:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14258:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14259:                 my $namematch = $token->[2]{'namematch'};
                   14260:                 if ($item eq 'parameter') {
                   14261:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14262:                         my $release = $parser->get_text();
                   14263:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14264:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14265:                     }
                   14266:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14267:                     my $release = $parser->get_text();
                   14268:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14269:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14270:                 }
                   14271:             }
                   14272:         }
                   14273:     }
1.1073    raeburn  14274: }
                   14275: 
1.1138    raeburn  14276: # ---------------------------------------------------------- Read managers table
                   14277: {
                   14278:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14279:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14280:             while (my $configline=<$config>) {
                   14281:                 chomp($configline);
                   14282:                 next if ($configline =~ /^\#/);
                   14283:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14284:                     $managerstab{$configline} = 1;
                   14285:                 }
                   14286:             }
                   14287:             close($config);
                   14288:         }
                   14289:     }
                   14290: }
                   14291: 
1.329     matthew  14292: # ------------- set up temporary directory
                   14293: {
1.1117    foxr     14294:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14295: 
1.11      www      14296: }
                   14297: 
1.794     albertel 14298: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14299: 				'compress_threshold'=> 20_000,
                   14300:  			        });
1.185     www      14301: 
1.281     www      14302: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14303: $dumpcount=0;
1.958     www      14304: $locknum=0;
1.22      www      14305: 
1.163     harris41 14306: &logtouch();
1.672     albertel 14307: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14308: $readit=1;
1.564     albertel 14309:     {
                   14310: 	use integer;
                   14311: 	my $test=(2**32)+1;
1.568     albertel 14312: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14313: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14314:     }
1.195     www      14315: }
1.1       albertel 14316: }
1.179     www      14317: 
1.1       albertel 14318: 1;
1.191     harris41 14319: __END__
                   14320: 
1.243     albertel 14321: =pod
                   14322: 
1.191     harris41 14323: =head1 NAME
                   14324: 
1.243     albertel 14325: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14326: 
                   14327: =head1 SYNOPSIS
                   14328: 
1.243     albertel 14329: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14330: 
                   14331:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14332: 
1.243     albertel 14333: Common parameters:
                   14334: 
                   14335: =over 4
                   14336: 
                   14337: =item *
                   14338: 
                   14339: $uname : an internal username (if $cname expecting a course Id specifically)
                   14340: 
                   14341: =item *
                   14342: 
                   14343: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14344: 
                   14345: =item *
                   14346: 
                   14347: $symb : a resource instance identifier
                   14348: 
                   14349: =item *
                   14350: 
                   14351: $namespace : the name of a .db file that contains the data needed or
                   14352: being set.
                   14353: 
                   14354: =back
                   14355: 
1.394     bowersj2 14356: =head1 OVERVIEW
1.191     harris41 14357: 
1.394     bowersj2 14358: lonnet provides subroutines which interact with the
                   14359: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14360: about classes, users, and resources.
1.243     albertel 14361: 
                   14362: For many of these objects you can also use this to store data about
                   14363: them or modify them in various ways.
1.191     harris41 14364: 
1.394     bowersj2 14365: =head2 Symbs
1.191     harris41 14366: 
1.394     bowersj2 14367: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14368: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14369: map, the resource number of the resource in the map, and the URL of
                   14370: the resource itself. The latter is somewhat redundant, but might help
                   14371: if maps change.
                   14372: 
                   14373: An example is
                   14374: 
                   14375:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14376: 
                   14377: The respective map entry is
                   14378: 
                   14379:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14380:   title="Problem 2">
                   14381:  </resource>
                   14382: 
                   14383: Symbs are used by the random number generator, as well as to store and
                   14384: restore data specific to a certain instance of for example a problem.
                   14385: 
                   14386: =head2 Storing And Retrieving Data
                   14387: 
                   14388: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14389: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14390: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14391: is is the non-critical message twin of cstore. These functions are for
                   14392: handlers to store a perl hash to a user's permanent data space in an
                   14393: easy manner, and to retrieve it again on another call. It is expected
                   14394: that a handler would use this once at the beginning to retrieve data,
                   14395: and then again once at the end to send only the new data back.
                   14396: 
                   14397: The data is stored in the user's data directory on the user's
                   14398: homeserver under the ID of the course.
                   14399: 
                   14400: The hash that is returned by restore will have all of the previous
                   14401: value for all of the elements of the hash.
                   14402: 
                   14403: Example:
                   14404: 
                   14405:  #creating a hash
                   14406:  my %hash;
                   14407:  $hash{'foo'}='bar';
                   14408: 
                   14409:  #storing it
                   14410:  &Apache::lonnet::cstore(\%hash);
                   14411: 
                   14412:  #changing a value
                   14413:  $hash{'foo'}='notbar';
                   14414: 
                   14415:  #adding a new value
                   14416:  $hash{'bar'}='foo';
                   14417:  &Apache::lonnet::cstore(\%hash);
                   14418: 
                   14419:  #retrieving the hash
                   14420:  my %history=&Apache::lonnet::restore();
                   14421: 
                   14422:  #print the hash
                   14423:  foreach my $key (sort(keys(%history))) {
                   14424:    print("\%history{$key} = $history{$key}");
                   14425:  }
                   14426: 
                   14427: Will print out:
1.191     harris41 14428: 
1.394     bowersj2 14429:  %history{1:foo} = bar
                   14430:  %history{1:keys} = foo:timestamp
                   14431:  %history{1:timestamp} = 990455579
                   14432:  %history{2:bar} = foo
                   14433:  %history{2:foo} = notbar
                   14434:  %history{2:keys} = foo:bar:timestamp
                   14435:  %history{2:timestamp} = 990455580
                   14436:  %history{bar} = foo
                   14437:  %history{foo} = notbar
                   14438:  %history{timestamp} = 990455580
                   14439:  %history{version} = 2
                   14440: 
                   14441: Note that the special hash entries C<keys>, C<version> and
                   14442: C<timestamp> were added to the hash. C<version> will be equal to the
                   14443: total number of versions of the data that have been stored. The
                   14444: C<timestamp> attribute will be the UNIX time the hash was
                   14445: stored. C<keys> is available in every historical section to list which
                   14446: keys were added or changed at a specific historical revision of a
                   14447: hash.
                   14448: 
                   14449: B<Warning>: do not store the hash that restore returns directly. This
                   14450: will cause a mess since it will restore the historical keys as if the
                   14451: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14452: 
1.394     bowersj2 14453: Calling convention:
1.191     harris41 14454: 
1.1225    raeburn  14455:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14456:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14457: 
1.394     bowersj2 14458: For more detailed information, see lonnet specific documentation.
1.191     harris41 14459: 
1.394     bowersj2 14460: =head1 RETURN MESSAGES
1.191     harris41 14461: 
1.394     bowersj2 14462: =over 4
1.191     harris41 14463: 
1.394     bowersj2 14464: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14465: 
1.394     bowersj2 14466: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14467: when the connection is brought back up
1.191     harris41 14468: 
1.394     bowersj2 14469: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14470: for later delivery
1.191     harris41 14471: 
1.967     bisitz   14472: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14473: 
1.394     bowersj2 14474: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14475: that was requested
1.191     harris41 14476: 
1.243     albertel 14477: =back
1.191     harris41 14478: 
1.243     albertel 14479: =head1 PUBLIC SUBROUTINES
1.191     harris41 14480: 
1.243     albertel 14481: =head2 Session Environment Functions
1.191     harris41 14482: 
1.243     albertel 14483: =over 4
1.191     harris41 14484: 
1.394     bowersj2 14485: =item * 
                   14486: X<appenv()>
1.949     raeburn  14487: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14488: the user envirnoment file, and will be restored for each access this
1.620     albertel 14489: user makes during this session, also modifies the %env for the current
1.949     raeburn  14490: process. Optional rolesarrayref - if defined contains a reference to an array
                   14491: of roles which are exempt from the restriction on modifying user.role entries 
                   14492: in the user's environment.db and in %env.    
1.191     harris41 14493: 
                   14494: =item *
1.394     bowersj2 14495: X<delenv()>
1.987     raeburn  14496: B<delenv($delthis,$regexp)>: removes all items from the session
                   14497: environment file that begin with $delthis. If the 
                   14498: optional second arg - $regexp - is true, $delthis is treated as a 
                   14499: regular expression, otherwise \Q$delthis\E is used. 
                   14500: The values are also deleted from the current processes %env.
1.191     harris41 14501: 
1.795     albertel 14502: =item * get_env_multiple($name) 
                   14503: 
                   14504: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14505: values may be defined and end up as an array ref.
                   14506: 
                   14507: returns an array of values
                   14508: 
1.243     albertel 14509: =back
                   14510: 
                   14511: =head2 User Information
1.191     harris41 14512: 
1.243     albertel 14513: =over 4
1.191     harris41 14514: 
                   14515: =item *
1.394     bowersj2 14516: X<queryauthenticate()>
                   14517: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14518: authentication scheme
                   14519: 
                   14520: =item *
1.394     bowersj2 14521: X<authenticate()>
1.1073    raeburn  14522: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14523: authenticate user from domain's lib servers (first use the current
                   14524: one). C<$upass> should be the users password.
1.1073    raeburn  14525: $checkdefauth is optional (value is 1 if a check should be made to
                   14526:    authenticate user using default authentication method, and allow
                   14527:    account creation if username does not have account in the domain).
                   14528: $clientcancheckhost is optional (value is 1 if checking whether the
                   14529:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14530: 
                   14531: =item *
1.394     bowersj2 14532: X<homeserver()>
                   14533: B<homeserver($uname,$udom)>: find the server which has
                   14534: the user's directory and files (there must be only one), this caches
                   14535: the answer, and also caches if there is a borken connection.
1.191     harris41 14536: 
                   14537: =item *
1.394     bowersj2 14538: X<idget()>
1.1300    raeburn  14539: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14540: a list of student/employee IDs or clicker IDs
                   14541: (student/employee IDs are a unique resource in a domain, there must be 
                   14542: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14543: clickerIDs are not necessarily unique, as students might share clickers.
                   14544: (returns hash: id=>name,id=>name)
1.191     harris41 14545: 
                   14546: =item *
1.394     bowersj2 14547: X<idrget()>
                   14548: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14549: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14550: 
                   14551: =item *
1.394     bowersj2 14552: X<idput()>
1.1300    raeburn  14553: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14554: names and associated student/employee IDs or clicker IDs.
                   14555: 
                   14556: =item *
                   14557: X<iddel()>
                   14558: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14559: student/employee ID or clicker ID username look-ups from domain.
                   14560: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14561: If no $uhome is provided, it will be determined usig &homeserver()
                   14562: for each user.  If no $namespace is provided, the default is ids.
                   14563: 
                   14564: =item *
                   14565: X<updateclickers()>
                   14566: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14567: clicker ID-to-username look-ups in clickers.db on library server.
                   14568: Permitted actions are add or del (i.e., add or delete). The 
                   14569: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14570: value is an escaped comma-separated list of usernames (for whom the
                   14571: library server is the homeserver), who registered that particular ID.
                   14572: If $critical is true, the update will be sent via &critical, otherwise
                   14573: &reply() will be used.
1.191     harris41 14574: 
                   14575: =item *
1.394     bowersj2 14576: X<rolesinit()>
1.1169    droeschl 14577: B<rolesinit($udom,$username)>: get user privileges.
                   14578: returns user role, first access and timer interval hashes
1.243     albertel 14579: 
                   14580: =item *
1.1171    droeschl 14581: X<privileged()>
                   14582: B<privileged($username,$domain)>: returns a true if user has a
                   14583: privileged and active role (i.e. su or dc), false otherwise.
                   14584: 
                   14585: =item *
1.551     albertel 14586: X<getsection()>
                   14587: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14588: course $cname, return section name/number or '' for "not in course"
                   14589: and '-1' for "no section"
                   14590: 
                   14591: =item *
1.394     bowersj2 14592: X<userenvironment()>
                   14593: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14594: passed in @what from the requested user's environment, returns a hash
                   14595: 
1.858     raeburn  14596: =item * 
                   14597: X<userlog_query()>
1.859     albertel 14598: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14599: activity.log file. %filters defines filters applied when parsing the
                   14600: log file. These can be start or end timestamps, or the type of action
                   14601: - log to look for Login or Logout events, check for Checkin or
                   14602: Checkout, role for role selection. The response is in the form
                   14603: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14604: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14605: 
1.243     albertel 14606: =back
                   14607: 
                   14608: =head2 User Roles
                   14609: 
                   14610: =over 4
                   14611: 
                   14612: =item *
                   14613: 
1.1284    raeburn  14614: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14615: returns codes for allowed actions.
                   14616: 
                   14617: The first argument is required, all others are optional.
                   14618: 
                   14619: $priv is the privilege being checked.
                   14620: $uri contains additional information about what is being checked for access (e.g.,
                   14621: URL, course ID etc.). 
                   14622: $symb is the unique resource instance identifier in a course; if needed,
                   14623: but not provided, it will be retrieved via a call to &symbread(). 
                   14624: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14625: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14626: files).
                   14627: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14628: prevents recursive calls to &allowed.
                   14629: 
1.243     albertel 14630:  F: full access
                   14631:  U,I,K: authentication modes (cxx only)
                   14632:  '': forbidden
                   14633:  1: user needs to choose course
                   14634:  2: browse allowed
1.766     albertel 14635:  A: passphrase authentication needed
1.1284    raeburn  14636:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14637: 
                   14638: =item *
                   14639: 
1.1192    raeburn  14640: constructaccess($url,$setpriv) : check for access to construction space URL
                   14641: 
                   14642: See if the owner domain and name in the URL match those in the
                   14643: expected environment.  If so, return three element list
                   14644: ($ownername,$ownerdomain,$ownerhome).
                   14645: 
                   14646: Otherwise return the null string.
                   14647: 
                   14648: If second argument 'setpriv' is true, it assigns the privileges,
                   14649: and returns the same three element list, unless the owner has
                   14650: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14651: in which case the null string is returned.
                   14652: 
                   14653: =item *
                   14654: 
1.1326    raeburn  14655: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14656: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14657: for system, domain, and course level. $uname and $udom are optional (current
                   14658: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14659: 
                   14660: =item *
                   14661: 
1.988     raeburn  14662: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14663: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14664: $type is Course (default) or Community.
1.988     raeburn  14665: If $forcedefault evaluates to true, text returned will be default 
                   14666: text for $type. Otherwise, if this is a course, the text returned 
                   14667: will be a custom name for the role (if defined in the course's 
                   14668: environment).  If no custom name is defined the default is returned.
                   14669:    
1.832     raeburn  14670: =item *
                   14671: 
1.1219    raeburn  14672: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14673: All arguments are optional. Returns a hash of a roles, either for
                   14674: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14675: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14676: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14677: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14678: For each key, value is set to colon-separated start and end times for
                   14679: the role.  If no username and domain are specified, will default to
1.934     raeburn  14680: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14681: of role statuses (active, future or previous), roles 
                   14682: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14683: to restrict the list of roles reported. If no array ref is 
                   14684: provided for types, will default to return only active roles.
1.834     albertel 14685: 
1.1195    raeburn  14686: =item *
                   14687: 
                   14688: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14689: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14690: 
                   14691: Additional optional arguments are: $type (if role checking is to be restricted 
                   14692: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14693: available roles) or future (roles available in the future), and
                   14694: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14695: have active Domain Coordinator role in course's domain or in additional
                   14696: domains (specified in 'Domains to check for privileged users' in course
                   14697: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14698: 
                   14699: =item *
                   14700: 
                   14701: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14702: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14703: $possdomains and $possroles are optional array refs -- to domains to check and
                   14704: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14705: users' roles.db to check for a dc or su role in any domain. This can be
                   14706: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14707: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14708: this then allows &privileged_by_domain() to be used, which caches the identity
                   14709: of privileged users, eliminating the need for repeated calls to &dump().
                   14710: 
                   14711: =item *
                   14712: 
                   14713: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14714: where the outer hash keys are domains specified in the $possdomains array ref,
                   14715: next inner hash keys are privileged roles specified in the $roles array ref,
                   14716: and the innermost hash contains key = value pairs for username:domain = end:start
                   14717: for active or future "privileged" users with that role in that domain. To avoid
                   14718: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14719: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14720: 
1.243     albertel 14721: =back
                   14722: 
                   14723: =head2 User Modification
                   14724: 
                   14725: =over 4
                   14726: 
                   14727: =item *
                   14728: 
1.957     raeburn  14729: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14730: user for the level given by URL.  Optional start and end dates (leave empty
                   14731: string or zero for "no date")
1.191     harris41 14732: 
                   14733: =item *
                   14734: 
1.243     albertel 14735: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14736: change a users, password, possible return values are: ok,
                   14737: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14738: refused
1.191     harris41 14739: 
                   14740: =item *
                   14741: 
1.243     albertel 14742: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14743: 
                   14744: =item *
                   14745: 
1.1058    raeburn  14746: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14747:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14748: 
                   14749: will update user information (firstname,middlename,lastname,generation,
                   14750: permanentemail), and if forceid is true, student/employee ID also.
                   14751: A user's institutional affiliation(s) can also be updated.
                   14752: User information fields will not be overwritten with empty entries 
                   14753: unless the field is included in the $candelete array reference.
                   14754: This array is included when a single user is modified via "Manage Users",
                   14755: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14756: 
                   14757: =item *
                   14758: 
1.286     matthew  14759: modifystudent
                   14760: 
1.957     raeburn  14761: modify a student's enrollment and identification information.
1.1235    raeburn  14762: The course id is resolved based on the current user's environment.  
                   14763: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14764: associated with a course.
                   14765: 
1.297     matthew  14766: This call is essentially a wrapper for lonnet::modifyuser and
                   14767: lonnet::modify_student_enrollment
1.286     matthew  14768: 
                   14769: Inputs: 
                   14770: 
                   14771: =over 4
                   14772: 
1.957     raeburn  14773: =item B<$udom> Student's loncapa domain
1.286     matthew  14774: 
1.957     raeburn  14775: =item B<$uname> Student's loncapa login name
1.286     matthew  14776: 
1.964     bisitz   14777: =item B<$uid> Student/Employee ID
1.286     matthew  14778: 
1.957     raeburn  14779: =item B<$umode> Student's authentication mode
1.286     matthew  14780: 
1.957     raeburn  14781: =item B<$upass> Student's password
1.286     matthew  14782: 
1.957     raeburn  14783: =item B<$first> Student's first name
1.286     matthew  14784: 
1.957     raeburn  14785: =item B<$middle> Student's middle name
1.286     matthew  14786: 
1.957     raeburn  14787: =item B<$last> Student's last name
1.286     matthew  14788: 
1.957     raeburn  14789: =item B<$gene> Student's generation
1.286     matthew  14790: 
1.957     raeburn  14791: =item B<$usec> Student's section in course
1.286     matthew  14792: 
                   14793: =item B<$end> Unix time of the roles expiration
                   14794: 
                   14795: =item B<$start> Unix time of the roles start date
                   14796: 
                   14797: =item B<$forceid> If defined, allow $uid to be changed
                   14798: 
                   14799: =item B<$desiredhome> server to use as home server for student
                   14800: 
1.957     raeburn  14801: =item B<$email> Student's permanent e-mail address
                   14802: 
                   14803: =item B<$type> Type of enrollment (auto or manual)
                   14804: 
1.963     raeburn  14805: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14806: 
                   14807: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14808: 
1.963     raeburn  14809: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14810: 
1.963     raeburn  14811: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14812: 
1.1216    raeburn  14813: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14814: 
                   14815: =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  14816: 
1.286     matthew  14817: =back
1.297     matthew  14818: 
                   14819: =item *
                   14820: 
                   14821: modify_student_enrollment
                   14822: 
1.1235    raeburn  14823: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14824: 'role.request.course' must be defined for this function to proceed.
                   14825: 
                   14826: Inputs:
                   14827: 
                   14828: =over 4
                   14829: 
1.1235    raeburn  14830: =item $udom, student's domain
1.297     matthew  14831: 
1.1235    raeburn  14832: =item $uname, student's name
1.297     matthew  14833: 
1.1235    raeburn  14834: =item $uid, student's user id
1.297     matthew  14835: 
1.1235    raeburn  14836: =item $first, student's first name
1.297     matthew  14837: 
                   14838: =item $middle
                   14839: 
                   14840: =item $last
                   14841: 
                   14842: =item $gene
                   14843: 
                   14844: =item $usec
                   14845: 
                   14846: =item $end
                   14847: 
                   14848: =item $start
                   14849: 
1.957     raeburn  14850: =item $type
                   14851: 
                   14852: =item $locktype
                   14853: 
                   14854: =item $cid
                   14855: 
                   14856: =item $selfenroll
                   14857: 
                   14858: =item $context
                   14859: 
1.1216    raeburn  14860: =item $credits, number of credits student will earn from this class
                   14861: 
1.1314    raeburn  14862: =item $instsec, institutional course section code for student
                   14863: 
1.297     matthew  14864: =back
                   14865: 
1.191     harris41 14866: 
                   14867: =item *
                   14868: 
1.243     albertel 14869: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14870: custom role; give a custom role to a user for the level given by URL.  Specify
                   14871: name and domain of role author, and role name
1.191     harris41 14872: 
                   14873: =item *
                   14874: 
1.243     albertel 14875: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14876: 
                   14877: =item *
                   14878: 
1.243     albertel 14879: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14880: 
                   14881: =back
                   14882: 
                   14883: =head2 Course Infomation
                   14884: 
                   14885: =over 4
1.191     harris41 14886: 
                   14887: =item *
                   14888: 
1.1118    foxr     14889: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14890: specified course id, including all environment settings for the
                   14891: course, the description of the course will be in the hash under the
                   14892: key 'description'
1.191     harris41 14893: 
1.1118    foxr     14894: $options is an optional parameter that if supplied is a hash reference that controls
                   14895: what how this function works.  It has the following key/values:
                   14896: 
                   14897: =over 4
                   14898: 
                   14899: =item freshen_cache
                   14900: 
                   14901: If defined, and the environment cache for the course is valid, it is 
                   14902: returned in the returned hash.
                   14903: 
                   14904: =item one_time
                   14905: 
                   14906: If defined, the last cache time is set to _now_
                   14907: 
                   14908: =item user
                   14909: 
                   14910: If defined, the supplied username is used instead of the current user.
                   14911: 
                   14912: 
                   14913: =back
                   14914: 
1.191     harris41 14915: =item *
                   14916: 
1.624     albertel 14917: resdata($name,$domain,$type,@which) : request for current parameter
                   14918: setting for a specific $type, where $type is either 'course' or 'user',
                   14919: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14920: answers for 10 minutes.
1.243     albertel 14921: 
1.877     foxr     14922: =item *
                   14923: 
                   14924: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14925: data base, returning a hash that is keyed by the resource name and has
                   14926: values that are the resource value.  I believe that the timestamps and
                   14927: versions are also returned.
                   14928: 
1.1236    raeburn  14929: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14930: supplemental content area. This routine caches the number of files for 
                   14931: 10 minutes.
                   14932: 
1.243     albertel 14933: =back
                   14934: 
                   14935: =head2 Course Modification
                   14936: 
                   14937: =over 4
1.191     harris41 14938: 
                   14939: =item *
                   14940: 
1.243     albertel 14941: writecoursepref($courseid,%prefs) : write preferences (environment
                   14942: database) for a course
1.191     harris41 14943: 
                   14944: =item *
                   14945: 
1.1011    raeburn  14946: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14947: 
                   14948: =item *
                   14949: 
1.1038    raeburn  14950: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14951: 
1.1167    droeschl 14952: =item *
                   14953: 
                   14954: is_course($courseid), is_course($cdom, $cnum)
                   14955: 
                   14956: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14957: two component version $cdom, $cnum. It checks if the specified course exists.
                   14958: 
                   14959: Returns:
                   14960:     undef if the course doesn't exist, otherwise
                   14961:     in scalar context the combined courseid.
                   14962:     in list context the two components of the course identifier, domain and 
                   14963:     courseid.    
                   14964: 
1.243     albertel 14965: =back
                   14966: 
                   14967: =head2 Resource Subroutines
                   14968: 
                   14969: =over 4
1.191     harris41 14970: 
                   14971: =item *
                   14972: 
1.243     albertel 14973: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14974: 
                   14975: =item *
                   14976: 
1.243     albertel 14977: repcopy($filename) : subscribes to the requested file, and attempts to
                   14978: replicate from the owning library server, Might return
1.607     raeburn  14979: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14980: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14981: resource. Expects the local filesystem pathname
                   14982: (/home/httpd/html/res/....)
                   14983: 
                   14984: =back
                   14985: 
                   14986: =head2 Resource Information
                   14987: 
                   14988: =over 4
1.191     harris41 14989: 
                   14990: =item *
                   14991: 
1.1228    raeburn  14992: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14993: and returns the value of a variety of different possible values,
                   14994: $varname should be a request string, and the other parameters can be
                   14995: used to specify who and what one is asking about. Ordinarily, $cid 
                   14996: does not need to be specified, as it is retrived from 
                   14997: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14998: within lonuserstate::loadmap() when initializing a course, before
                   14999: $env{'request.course.id'} has been set, so it needs to be provided
                   15000: in that one case.
1.243     albertel 15001: 
                   15002: Possible values for $varname are environment.lastname (or other item
                   15003: from the envirnment hash), user.name (or someother aspect about the
                   15004: user), resource.0.maxtries (or some other part and parameter of a
                   15005: resource)
1.204     albertel 15006: 
                   15007: =item *
                   15008: 
1.243     albertel 15009: directcondval($number) : get current value of a condition; reads from a state
                   15010: string
1.204     albertel 15011: 
                   15012: =item *
                   15013: 
1.243     albertel 15014: condval($condidx) : value of condition index based on state
1.204     albertel 15015: 
                   15016: =item *
                   15017: 
1.1362    raeburn  15018: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15019: resource's metadata, $what should be either a specific key, or either
                   15020: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15021: packages that this resource currently uses, the last 3 arguments are 
                   15022: only used internally for recursive metadata.
                   15023: 
                   15024: the toolsymb is only used where the uri is for an external tool (for which
                   15025: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15026: 
1.1371    raeburn  15027: this function automatically caches all requests except any made recursively
                   15028: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15029: defined).
1.191     harris41 15030: 
                   15031: =item *
                   15032: 
1.243     albertel 15033: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15034: network of library servers; returns file handle of where SQL and regex results
                   15035: will be stored for query
1.191     harris41 15036: 
                   15037: =item *
                   15038: 
1.1282    raeburn  15039: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15040: return symbolic list entry (all arguments optional). 
                   15041: 
                   15042: Args: filename is the filename (including path) for the file for which a symb 
                   15043: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15044: to check access status if more than one resource was found in the bighash 
                   15045: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15046: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15047: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15048: cause possible symbs to be checked to determine if they are subject to content
                   15049: blocking, if so they will not be included as possible symbs; possibles is a
                   15050: ref to a hash, which, as a side effect, will be populated with all possible 
                   15051: symbs (content blocking not tested).
                   15052:  
1.243     albertel 15053: returns the data handle
1.191     harris41 15054: 
                   15055: =item *
                   15056: 
1.1190    raeburn  15057: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15058: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15059: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15060: on failure, user must be in a course, as it assumes the existence of
                   15061: the course initial hash, and uses $env('request.course.id'}.  The third
                   15062: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15063: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15064: encrypted; otherwise it will be null.  
1.191     harris41 15065: 
                   15066: =item *
                   15067: 
1.243     albertel 15068: symbclean($symb) : removes versions numbers from a symb, returns the
                   15069: cleaned symb
1.191     harris41 15070: 
                   15071: =item *
                   15072: 
1.243     albertel 15073: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15074: course map, user must be in a course for it to work.
1.191     harris41 15075: 
                   15076: =item *
                   15077: 
1.243     albertel 15078: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15079: 
                   15080: =item *
                   15081: 
1.243     albertel 15082: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15083: a random seed, all arguments are optional, if they aren't sent it uses the
                   15084: environment to derive them. Note: if symb isn't sent and it can't get one
                   15085: from &symbread it will use the current time as its return value
1.191     harris41 15086: 
                   15087: =item *
                   15088: 
1.243     albertel 15089: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15090: unfakeable, receipt
1.191     harris41 15091: 
                   15092: =item *
                   15093: 
1.620     albertel 15094: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15095: 
                   15096: =item *
                   15097: 
1.243     albertel 15098: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15099: 
                   15100: =item *
                   15101: 
1.243     albertel 15102: 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 15103: 
                   15104: =item *
                   15105: 
1.243     albertel 15106: 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 15107: 
                   15108: =item *
                   15109: 
1.243     albertel 15110: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15111: 
                   15112: =item *
                   15113: 
1.243     albertel 15114: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15115: forcing spreadsheet to reevaluate the resource scores next time.
                   15116: 
1.1195    raeburn  15117: =item * 
                   15118: 
1.1196    raeburn  15119: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15120: when viewing in course context.
1.1195    raeburn  15121: 
1.1196    raeburn  15122:  input: six args -- filename (decluttered), course number, course domain,
                   15123:                     url, symb (if registered) and group (if this is a 
                   15124:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15125: 
1.1196    raeburn  15126:  output: array of five scalars --
1.1195    raeburn  15127:          $cfile -- url for file editing if editable on current server
                   15128:          $home -- homeserver of resource (i.e., for author if published,
                   15129:                                           or course if uploaded.).
                   15130:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15131:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15132:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15133: 
                   15134: =item *
                   15135: 
                   15136: is_course_upload($file,$cnum,$cdom)
                   15137: 
                   15138: Used in course context to determine if current file was uploaded to 
                   15139: the course (i.e., would be found in /userfiles/docs on the course's 
                   15140: homeserver.
                   15141: 
                   15142:   input: 3 args -- filename (decluttered), course number and course domain.
                   15143:   output: boolean -- 1 if file was uploaded.
                   15144: 
1.243     albertel 15145: =back
                   15146: 
                   15147: =head2 Storing/Retreiving Data
                   15148: 
                   15149: =over 4
1.191     harris41 15150: 
                   15151: =item *
                   15152: 
1.1269    raeburn  15153: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15154: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15155: the remaining args aren't required and if they aren't passed or are '' they will
                   15156: be derived from the env (with the exception of $laststore, which is an 
                   15157: optional arg used when a user's submission is stored in grading).
                   15158: $laststore is $version=$timestamp, where $version is the most recent version
                   15159: number retrieved for the corresponding $symb in the $namespace db file, and
                   15160: $timestamp is the timestamp for that transaction (UNIX time).
                   15161: $laststore is currently only passed when cstore() is called by 
                   15162: structuretags::finalize_storage().
1.191     harris41 15163: 
                   15164: =item *
                   15165: 
1.1269    raeburn  15166: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15167: but uses critical subroutine
1.191     harris41 15168: 
                   15169: =item *
                   15170: 
1.243     albertel 15171: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15172: all args are optional
1.191     harris41 15173: 
                   15174: =item *
                   15175: 
1.717     albertel 15176: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15177: dumps the complete (or key matching regexp) namespace into a hash
                   15178: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15179: normally &store()ed into
                   15180: 
                   15181: $range should be either an integer '100' (give me the first 100
                   15182:                                            matching records)
                   15183:               or be  two integers sperated by a - with no spaces
                   15184:                  '30-50' (give me the 30th through the 50th matching
                   15185:                           records)
                   15186: 
                   15187: 
                   15188: =item *
                   15189: 
1.1269    raeburn  15190: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15191: replaces a &store() version of data with a replacement set of data
                   15192: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15193: reference. If $tolog is true, the transaction is logged in the courselog
                   15194: with an action=PUTSTORE.
1.717     albertel 15195: 
                   15196: =item *
                   15197: 
1.243     albertel 15198: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15199: works very similar to store/cstore, but all data is stored in a
                   15200: temporary location and can be reset using tmpreset, $storehash should
                   15201: be a hash reference, returns nothing on success
1.191     harris41 15202: 
                   15203: =item *
                   15204: 
1.243     albertel 15205: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15206: similar to restore, but all data is stored in a temporary location and
                   15207: can be reset using tmpreset. Returns a hash of values on success,
                   15208: error string otherwise.
1.191     harris41 15209: 
                   15210: =item *
                   15211: 
1.243     albertel 15212: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15213: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15214: 
                   15215: =item *
                   15216: 
1.243     albertel 15217: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15218: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15219: 
                   15220: =item *
                   15221: 
1.243     albertel 15222: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15223: namesp ($udom and $uname are optional)
1.191     harris41 15224: 
                   15225: =item *
                   15226: 
1.702     albertel 15227: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15228: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15229: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15230: 
1.702     albertel 15231: $range should be either an integer '100' (give me the first 100
                   15232:                                            matching records)
                   15233:               or be  two integers sperated by a - with no spaces
                   15234:                  '30-50' (give me the 30th through the 50th matching
                   15235:                           records)
1.449     matthew  15236: =item *
                   15237: 
                   15238: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15239: $store can be a scalar, an array reference, or if the amount to be 
                   15240: incremented is > 1, a hash reference.
                   15241: 
                   15242: ($udom and $uname are optional)
1.191     harris41 15243: 
                   15244: =item *
                   15245: 
1.243     albertel 15246: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15247: ($udom and $uname are optional)
1.191     harris41 15248: 
                   15249: =item *
                   15250: 
1.243     albertel 15251: cput($namespace,$storehash,$udom,$uname) : critical put
                   15252: ($udom and $uname are optional)
1.191     harris41 15253: 
                   15254: =item *
                   15255: 
1.748     albertel 15256: newput($namespace,$storehash,$udom,$uname) :
                   15257: 
                   15258: Attempts to store the items in the $storehash, but only if they don't
                   15259: currently exist, if this succeeds you can be certain that you have 
                   15260: successfully created a new key value pair in the $namespace db.
                   15261: 
                   15262: 
                   15263: Args:
                   15264:  $namespace: name of database to store values to
                   15265:  $storehash: hashref to store to the db
                   15266:  $udom: (optional) domain of user containing the db
                   15267:  $uname: (optional) name of user caontaining the db
                   15268: 
                   15269: Returns:
                   15270:  'ok' -> succeeded in storing all keys of $storehash
                   15271:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15272:                         least <key> already existed in the db (other
                   15273:                         requested keys may also already exist)
1.967     bisitz   15274:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15275:  'con_lost' -> unable to contact request server
                   15276:  'refused' -> action was not allowed by remote machine
                   15277: 
                   15278: 
                   15279: =item *
                   15280: 
1.243     albertel 15281: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15282: reference filled in from namesp (encrypts the return communication)
                   15283: ($udom and $uname are optional)
1.191     harris41 15284: 
                   15285: =item *
                   15286: 
1.243     albertel 15287: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15288: critical subroutine
                   15289: 
1.806     raeburn  15290: =item *
                   15291: 
1.860     raeburn  15292: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15293: array reference filled in from namespace found in domain level on either
                   15294: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15295: 
                   15296: =item *
                   15297: 
1.860     raeburn  15298: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15299: domain level either on specified domain server ($uhome) or primary domain 
                   15300: server ($udom and $uhome are optional)
1.806     raeburn  15301: 
1.943     raeburn  15302: =item * 
                   15303: 
1.1240    raeburn  15304: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15305: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15306: the target domain.
                   15307: 
                   15308: May also include additional key => value pairs for the following groups:
                   15309: 
                   15310: =over
                   15311: 
                   15312: =item
                   15313: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15314: 
                   15315: =over
                   15316: 
                   15317: =item defaultquota, authorquota
                   15318: 
                   15319: =back
                   15320: 
                   15321: =item
                   15322: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15323: portfolio for users).
                   15324: 
                   15325: =over
                   15326: 
                   15327: =item
                   15328: aboutme, blog, webdav, portfolio
                   15329: 
                   15330: =back
                   15331: 
                   15332: =item
                   15333: requestcourses: ability to request courses, and how requests are processed.
                   15334: 
                   15335: =over
                   15336: 
                   15337: =item
1.1305    raeburn  15338: official, unofficial, community, textbook, placement
1.1240    raeburn  15339: 
                   15340: =back
                   15341: 
                   15342: =item
                   15343: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15344: 
                   15345: =over
                   15346: 
                   15347: =item
1.1256    raeburn  15348: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15349: 
                   15350: =back
                   15351: 
                   15352: =item
                   15353: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15354: for course's uploaded content.
                   15355: 
                   15356: =over
                   15357: 
                   15358: =item
1.1246    raeburn  15359: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15360: communityquota, textbookquota, placementquota
1.1240    raeburn  15361: 
                   15362: =back
                   15363: 
                   15364: =item
                   15365: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15366: on your servers.
                   15367: 
                   15368: =over
                   15369: 
                   15370: =item 
                   15371: remotesessions, hostedsessions
                   15372: 
                   15373: =back
                   15374: 
                   15375: =back
                   15376: 
                   15377: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15378: utility to create a configuration.db file on a domain's primary library server 
                   15379: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15380: -- corresponding values are authentication type (internal, krb4, krb5,
                   15381: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15382: will be available. Values are retrieved from cache (if current), unless the
                   15383: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15384: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15385: 
                   15386: Typical usage:
1.943     raeburn  15387: 
1.1240    raeburn  15388: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15389: 
1.243     albertel 15390: =back
                   15391: 
                   15392: =head2 Network Status Functions
                   15393: 
                   15394: =over 4
1.191     harris41 15395: 
                   15396: =item *
                   15397: 
1.1137    raeburn  15398: dirlist() : return directory list based on URI (first arg).
                   15399: 
                   15400: Inputs: 1 required, 5 optional.
                   15401: 
                   15402: =over
                   15403: 
                   15404: =item 
                   15405: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15406: 
                   15407: =item
                   15408: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15409: 
                   15410: =item
                   15411: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15412: 
                   15413: =item
                   15414: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15415: 
                   15416: =item
                   15417: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15418: 
                   15419: =item 
                   15420: $alternateRoot - path to prepend in place of path from $uri.
                   15421: 
                   15422: =back
                   15423: 
                   15424: Returns: Array of up to two items.
                   15425: 
                   15426: =over
                   15427: 
                   15428: a reference to an array of files/subdirectories
                   15429: 
                   15430: =over
                   15431: 
                   15432: Each element in the array of files/subdirectories is a & separated list of
                   15433: item name and the result of running stat on the item.  If dirlist was requested
                   15434: for a file instead of a directory, the item name will be ''. For a directory 
                   15435: listing, if the item is a metadata file, the element will end &N&M 
                   15436: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15437: default copyright set (1).  
                   15438: 
                   15439: =back
                   15440: 
                   15441: a scalar containing error condition (if encountered).
                   15442: 
                   15443: =over
                   15444: 
                   15445: =item 
                   15446: no_host (no homeserver identified for $username:$domain).
                   15447: 
                   15448: =item 
                   15449: no_such_host (server contacted for listing not identified as valid host).
                   15450: 
                   15451: =item 
                   15452: con_lost (connection to remote server failed).
                   15453: 
                   15454: =item 
                   15455: refused (invalid $username:$domain received on lond side).
                   15456: 
                   15457: =item 
                   15458: no_such_dir (directory at specified path on lond side does not exist). 
                   15459: 
                   15460: =item 
                   15461: empty (directory at specified path on lond side is empty).
                   15462: 
                   15463: =over
                   15464: 
                   15465: This is currently not encountered because the &ls3, &ls2, 
                   15466: &ls (_handler) routines on the lond side do not filter out
                   15467: . and .. from a directory listing. 
                   15468: 
                   15469: =back
                   15470: 
                   15471: =back
                   15472: 
                   15473: =back
1.191     harris41 15474: 
                   15475: =item *
                   15476: 
1.243     albertel 15477: spareserver() : find server with least workload from spare.tab
                   15478: 
1.986     foxr     15479: 
                   15480: =item *
                   15481: 
                   15482: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15483: if there is no corresponding loncapa host.
                   15484: 
1.243     albertel 15485: =back
                   15486: 
1.986     foxr     15487: 
1.243     albertel 15488: =head2 Apache Request
                   15489: 
                   15490: =over 4
1.191     harris41 15491: 
                   15492: =item *
                   15493: 
1.243     albertel 15494: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15495: localhost, posts hash
                   15496: 
                   15497: =back
                   15498: 
                   15499: =head2 Data to String to Data
                   15500: 
                   15501: =over 4
1.191     harris41 15502: 
                   15503: =item *
                   15504: 
1.243     albertel 15505: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15506: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15507: 
                   15508: =item *
                   15509: 
1.243     albertel 15510: hashref2str($hashref) : convert a hashref into a string complete with
                   15511: escaping and '=' and '&' separators, supports elements that are
                   15512: arrayrefs and hashrefs
1.191     harris41 15513: 
                   15514: =item *
                   15515: 
1.243     albertel 15516: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15517: with escaping and '&' separators, supports elements that are arrayrefs
                   15518: and hashrefs
1.191     harris41 15519: 
                   15520: =item *
                   15521: 
1.243     albertel 15522: str2hash($string) : convert string to hash using unescaping and
                   15523: splitting on '=' and '&', supports elements that are arrayrefs and
                   15524: hashrefs
1.191     harris41 15525: 
                   15526: =item *
                   15527: 
1.243     albertel 15528: str2array($string) : convert string to hash using unescaping and
                   15529: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15530: 
                   15531: =back
                   15532: 
                   15533: =head2 Logging Routines
                   15534: 
                   15535: 
                   15536: These routines allow one to make log messages in the lonnet.log and
                   15537: lonnet.perm logfiles.
1.191     harris41 15538: 
1.1119    foxr     15539: =over 4
                   15540: 
1.191     harris41 15541: =item *
                   15542: 
1.243     albertel 15543: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15544: 
                   15545: =item *
                   15546: 
1.243     albertel 15547: logthis() : append message to the normal lonnet.log file, it gets
                   15548: preiodically rolled over and deleted.
1.191     harris41 15549: 
                   15550: =item *
                   15551: 
1.243     albertel 15552: logperm() : append a permanent message to lonnet.perm.log, this log
                   15553: file never gets deleted by any automated portion of the system, only
                   15554: messages of critical importance should go in here.
                   15555: 
1.1119    foxr     15556: 
1.243     albertel 15557: =back
                   15558: 
                   15559: =head2 General File Helper Routines
                   15560: 
                   15561: =over 4
1.191     harris41 15562: 
                   15563: =item *
                   15564: 
1.481     raeburn  15565: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15566: (a) files in /uploaded
                   15567:   (i) If a local copy of the file exists - 
                   15568:       compares modification date of local copy with last-modified date for 
                   15569:       definitive version stored on home server for course. If local copy is 
                   15570:       stale, requests a new version from the home server and stores it. 
                   15571:       If the original has been removed from the home server, then local copy 
                   15572:       is unlinked.
                   15573:   (ii) If local copy does not exist -
                   15574:       requests the file from the home server and stores it. 
                   15575:   
                   15576:   If $caller is 'uploadrep':  
                   15577:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15578:     for request for files originally uploaded via DOCS. 
                   15579:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15580:   
                   15581:   Otherwise:
                   15582:      This indicates a call from the content generation phase of the request.
                   15583:      -  returns the entire contents of the file or -1.
                   15584:      
                   15585: (b) files in /res
                   15586:    - returns the entire contents of a file or -1; 
                   15587:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15588: 
1.712     albertel 15589: 
                   15590: =item *
                   15591: 
                   15592: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15593:                   reference
                   15594: 
                   15595: returns either a stat() list of data about the file or an empty list
                   15596: if the file doesn't exist or couldn't find out about it (connection
                   15597: problems or user unknown)
                   15598: 
1.191     harris41 15599: =item *
                   15600: 
1.243     albertel 15601: filelocation($dir,$file) : returns file system location of a file
                   15602: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15603: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15604: and a file of ../bob will become /a/bob)
1.191     harris41 15605: 
                   15606: =item *
                   15607: 
                   15608: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15609: filelocation except for hrefs
                   15610: 
                   15611: =item *
                   15612: 
1.1261    raeburn  15613: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15614: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15615: 
1.243     albertel 15616: =back
                   15617: 
1.608     albertel 15618: =head2 Usererfile file routines (/uploaded*)
                   15619: 
                   15620: =over 4
                   15621: 
                   15622: =item *
                   15623: 
                   15624: userfileupload(): main rotine for putting a file in a user or course's
                   15625:                   filespace, arguments are,
                   15626: 
1.620     albertel 15627:  formname - required - this is the name of the element in $env where the
1.608     albertel 15628:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15629:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15630:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15631:  context - if coursedoc, store the file in the course of the active role
                   15632:              of the current user; 
                   15633:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15634:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15635:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15636:          if undefined, it will be placed in "unknown"
                   15637: 
                   15638:  (This routine calls clean_filename() to remove any dangerous
                   15639:  characters from the filename, and then calls finuserfileupload() to
                   15640:  complete the transaction)
                   15641: 
                   15642:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15643:  and /adm/notfound.html if unsuccessful
                   15644: 
                   15645: =item *
                   15646: 
                   15647: clean_filename(): routine for cleaing a filename up for storage in
                   15648:                  userfile space, argument is:
                   15649: 
                   15650:  filename - proposed filename
                   15651: 
                   15652: returns: the new clean filename
                   15653: 
                   15654: =item *
                   15655: 
1.1090    raeburn  15656: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15657: userspace, probably shouldn't be called directly
                   15658: 
                   15659:   docuname: username or courseid of destination for the file
                   15660:   docudom: domain of user/course of destination for the file
                   15661:   formname: same as for userfileupload()
1.1090    raeburn  15662:   fname: filename (including subdirectories) for the file
                   15663:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15664:   allfiles: reference to hash used to store objects found by parser
                   15665:   codebase: reference to hash used for codebases of java objects found by parser
                   15666:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15667:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15668:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15669:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15670:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15671:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15672:   mimetype: reference to scalar to accommodate mime type determined
                   15673:             from File::MMagic if $parser = parse.
1.608     albertel 15674: 
                   15675:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15676:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15677:  was 'overwrite').
                   15678:  
1.608     albertel 15679: 
                   15680: =item *
                   15681: 
                   15682: renameuserfile(): renames an existing userfile to a new name
                   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:    old: current file name (including any subdirs under userfiles)
                   15688:    new: desired file name (including any subdirs under userfiles)
                   15689: 
                   15690: =item *
                   15691: 
                   15692: mkdiruserfile(): creates a directory is a userfiles dir
                   15693: 
                   15694:   Args:
                   15695:    docuname: username or courseid of destination for the file
                   15696:    docudom: domain of user/course of destination for the file
                   15697:    dir: dir to create (including any subdirs under userfiles)
                   15698: 
                   15699: =item *
                   15700: 
                   15701: removeuserfile(): removes a file that exists in userfiles
                   15702: 
                   15703:   Args:
                   15704:    docuname: username or courseid of destination for the file
                   15705:    docudom: domain of user/course of destination for the file
                   15706:    fname: filname to delete (including any subdirs under userfiles)
                   15707: 
                   15708: =item *
                   15709: 
                   15710: removeuploadedurl(): convience function for removeuserfile()
                   15711: 
                   15712:   Args:
                   15713:    url:  a full /uploaded/... url to delete
                   15714: 
1.747     albertel 15715: =item * 
                   15716: 
                   15717: get_portfile_permissions():
                   15718:   Args:
                   15719:     domain: domain of user or course contain the portfolio files
                   15720:     user: name of user or num of course contain the portfolio files
                   15721:   Returns:
                   15722:     hashref of a dump of the proper file_permissions.db
                   15723:    
                   15724: 
                   15725: =item * 
                   15726: 
                   15727: get_access_controls():
                   15728: 
                   15729: Args:
                   15730:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15731:   group: (optional) the group you want the files associated with
                   15732:   file: (optional) the file you want access info on
                   15733: 
                   15734: Returns:
1.749     raeburn  15735:     a hash (keys are file names) of hashes containing
                   15736:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15737:         values are XML containing access control settings (see below) 
1.747     albertel 15738: 
                   15739: Internal notes:
                   15740: 
1.749     raeburn  15741:  access controls are stored in file_permissions.db as key=value pairs.
                   15742:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15743:         where scope -> public,guest,course,group,domains or users.
                   15744:               end -> UNIX time for end of access (0 -> no end date)
                   15745:               start -> UNIX time for start of access
                   15746: 
                   15747:     value -> XML description of access control
                   15748:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15749:             <start></start>
                   15750:             <end></end>
                   15751: 
                   15752:             <password></password>  for scope type = guest
                   15753: 
                   15754:             <domain></domain>     for scope type = course or group
                   15755:             <number></number>
                   15756:             <roles id="">
                   15757:              <role></role>
                   15758:              <access></access>
                   15759:              <section></section>
                   15760:              <group></group>
                   15761:             </roles>
                   15762: 
                   15763:             <dom></dom>         for scope type = domains
                   15764: 
                   15765:             <users>             for scope type = users
                   15766:              <user>
                   15767:               <uname></uname>
                   15768:               <udom></udom>
                   15769:              </user>
                   15770:             </users>
                   15771:            </scope> 
                   15772:               
                   15773:  Access data is also aggregated for each file in an additional key=value pair:
                   15774:  key -> path to file/file_name\0accesscontrol 
                   15775:  value -> reference to hash
                   15776:           hash contains key = value pairs
                   15777:           where key = uniqueID:scope_end_start
                   15778:                 value = UNIX time record was last updated
                   15779: 
                   15780:           Used to improve speed of look-ups of access controls for each file.  
                   15781:  
                   15782:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15783: 
1.1198    raeburn  15784: =item *
                   15785: 
1.749     raeburn  15786: modify_access_controls():
                   15787: 
                   15788: Modifies access controls for a portfolio file
                   15789: Args
                   15790: 1. file name
                   15791: 2. reference to hash of required changes,
                   15792: 3. domain
                   15793: 4. username
                   15794:   where domain,username are the domain of the portfolio owner 
                   15795:   (either a user or a course) 
                   15796: 
                   15797: Returns:
                   15798: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15799: 2. result of deletions ('ok' or 'error', with error message).
                   15800: 3. reference to hash of any new or updated access controls.
                   15801: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15802:    key = integer (inbound ID)
1.1198    raeburn  15803:    value = uniqueID
                   15804: 
                   15805: =item *
                   15806: 
                   15807: get_timebased_id():
                   15808: 
                   15809: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15810: course via the Course Editor (e.g., folders, composite pages, 
                   15811: group bulletin boards).
                   15812: 
                   15813: Args: (first three required; six others optional)
                   15814: 
                   15815: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15816:    docssequence, or name of group
                   15817: 
                   15818: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15819:    e.g., num, boardids
                   15820: 
                   15821: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15822:    file will be named nohist_namespace.db
                   15823: 
                   15824: 4. cdom: domain of course; default is current course domain from %env
                   15825: 
                   15826: 5. cnum: course number; default is current course number from %env
                   15827: 
                   15828: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15829:    unix timestamp to form the suffix, if the plain timestamp is already
                   15830:    in use.  Default is to not do this, but simply increment the unix 
                   15831:    timestamp by 1 until a unique key is obtained.
                   15832: 
                   15833: 7. who: holder of locking key; defaults to user:domain for user.
                   15834: 
                   15835: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15836:    retrying); default is 3.
                   15837: 
                   15838: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15839: 
                   15840: Returns:
                   15841: 
                   15842: 1. suffix obtained (numeric)
                   15843: 
                   15844: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15845: 
                   15846: 3. error: contains (localized) error message if an error occurred.
                   15847: 
1.747     albertel 15848: 
1.608     albertel 15849: =back
                   15850: 
1.243     albertel 15851: =head2 HTTP Helper Routines
                   15852: 
                   15853: =over 4
                   15854: 
1.191     harris41 15855: =item *
                   15856: 
                   15857: escape() : unpack non-word characters into CGI-compatible hex codes
                   15858: 
                   15859: =item *
                   15860: 
                   15861: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15862: 
1.243     albertel 15863: =back
                   15864: 
                   15865: =head1 PRIVATE SUBROUTINES
                   15866: 
                   15867: =head2 Underlying communication routines (Shouldn't call)
                   15868: 
                   15869: =over 4
                   15870: 
                   15871: =item *
                   15872: 
                   15873: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15874: 
                   15875: =item *
                   15876: 
                   15877: reply() : uses subreply to send a message to remote machine, logs all failures
                   15878: 
                   15879: =item *
                   15880: 
                   15881: critical() : passes a critical message to another server; if cannot
                   15882: get through then place message in connection buffer directory and
                   15883: returns con_delayed, if incapable of saving message, returns
                   15884: con_failed
                   15885: 
                   15886: =item *
                   15887: 
                   15888: reconlonc() : tries to reconnect lonc client processes.
                   15889: 
                   15890: =back
                   15891: 
                   15892: =head2 Resource Access Logging
                   15893: 
                   15894: =over 4
                   15895: 
                   15896: =item *
                   15897: 
                   15898: flushcourselogs() : flush (save) buffer logs and access logs
                   15899: 
                   15900: =item *
                   15901: 
                   15902: courselog($what) : save message for course in hash
                   15903: 
                   15904: =item *
                   15905: 
                   15906: courseacclog($what) : save message for course using &courselog().  Perform
                   15907: special processing for specific resource types (problems, exams, quizzes, etc).
                   15908: 
1.191     harris41 15909: =item *
                   15910: 
                   15911: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15912: as a PerlChildExitHandler
1.243     albertel 15913: 
                   15914: =back
                   15915: 
                   15916: =head2 Other
                   15917: 
                   15918: =over 4
                   15919: 
                   15920: =item *
                   15921: 
                   15922: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15923: 
                   15924: =back
                   15925: 
                   15926: =cut
1.877     foxr     15927: 

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