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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1397  ! raeburn     4: # $Id: lonnet.pm,v 1.1396 2018/12/22 01:56:25 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
1.1389    raeburn    76: use CGI::Cookie;
1.1182    foxr       77: 
1.1173    foxr       78: use Encode;
                     79: 
1.1245    raeburn    80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     82:             %managerstab);
1.871     albertel   83: 
                     84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        87:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        88: 
1.1       albertel   89: use IO::Socket;
1.31      www        90: use GDBM_File;
1.208     albertel   91: use HTML::LCParser;
1.88      www        92: use Fcntl qw(:flock);
1.870     albertel   93: use Storable qw(thaw nfreeze);
1.1289    damieng    94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   95: use Cache::Memcached;
1.676     albertel   96: use Digest::MD5;
1.790     albertel   97: use Math::Random;
1.1024    raeburn    98: use File::MMagic;
1.807     albertel   99: use LONCAPA qw(:DEFAULT :match);
1.740     www       100: use LONCAPA::Configuration;
1.1160    www       101: use LONCAPA::lonmetadata;
1.1167    droeschl  102: use LONCAPA::Lond;
1.1345    raeburn   103: use LONCAPA::LWPReq;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.1359    raeburn   161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.1359    raeburn   174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.1315    raeburn   232: sub get_servercerts_info {
1.1383    raeburn   233:     my ($lonhost,$hostname,$context) = @_;
                    234:     return if ($lonhost eq '');
                    235:     if ($hostname eq '') {
                    236:         $hostname = &hostname($lonhost);
                    237:     }
                    238:     return if ($hostname eq '');
1.1315    raeburn   239:     my ($rep,$uselocal);
1.1388    raeburn   240:     if ($context eq 'install') {
1.1387    raeburn   241:         $uselocal = 1;
                    242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   243:         $uselocal = 1;
                    244:     }
1.1387    raeburn   245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   247:         if ($distro eq '') {
                    248:             $uselocal = 0;
                    249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   250:             if ($1 < 6) {
                    251:                 $uselocal = 0;
                    252:             }
1.1346    raeburn   253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    254:             if ($1 < 12) {
                    255:                 $uselocal = 0;
                    256:             }
1.1315    raeburn   257:         }
                    258:     }
                    259:     if ($uselocal) {
1.1383    raeburn   260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   261:     } else {
                    262:         $rep=&reply('servercerts',$lonhost);
                    263:     }
                    264:     my ($result,%returnhash);
                    265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    266:         ($rep eq 'unknown_cmd')) {
                    267:         $result = $rep;
                    268:     } else {
                    269:         $result = 'ok';
                    270:         my @pairs=split(/\&/,$rep);
                    271:         foreach my $item (@pairs) {
                    272:             my ($key,$value)=split(/=/,$item,2);
                    273:             my $what = &unescape($key);
                    274:             $returnhash{$what}=&thaw_unescape($value);
                    275:         }
                    276:     }
                    277:     return ($result,\%returnhash);
                    278: }
                    279: 
1.993     raeburn   280: sub get_server_loncaparev {
1.1073    raeburn   281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   282:     if (defined($lonhost)) {
                    283:         if (!defined(&hostname($lonhost))) {
                    284:             undef($lonhost);
                    285:         }
                    286:     }
                    287:     if (!defined($lonhost)) {
                    288:         if (defined(&domain($dom,'primary'))) {
                    289:             $lonhost=&domain($dom,'primary');
                    290:             if ($lonhost eq 'no_host') {
                    291:                 undef($lonhost);
                    292:             }
                    293:         }
                    294:     }
                    295:     if (defined($lonhost)) {
1.1073    raeburn   296:         my $cachetime = 12*3600;
                    297:         if (!$ignore_cache) {
                    298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    299:             if (defined($cached)) {
                    300:                 return $loncaparev;
                    301:             }
                    302:         }
                    303:         my ($answer,$loncaparev);
                    304:         my @ids=&current_machine_ids();
                    305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    306:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   308:                 $loncaparev = $1;
                    309:             }
                    310:         } else {
                    311:             $answer = &reply('serverloncaparev',$lonhost);
                    312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    313:                 if ($caller eq 'loncron') {
1.1397  ! raeburn   314:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   315:                     my $protocol = $protocol{$lonhost};
                    316:                     $protocol = 'http' if ($protocol ne 'https');
1.1397  ! raeburn   317:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   318:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   319:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   320:                     unless ($response->is_error()) {
                    321:                         my $content = $response->content;
1.1081    raeburn   322:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   323:                             $loncaparev = $1;
                    324:                         }
                    325:                     }
                    326:                 } else {
                    327:                     $loncaparev = $loncaparevs{$lonhost};
                    328:                 }
1.1081    raeburn   329:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   330:                 $loncaparev = $1;
                    331:             }
1.993     raeburn   332:         }
1.1073    raeburn   333:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   334:     }
                    335: }
                    336: 
1.1074    raeburn   337: sub get_server_homeID {
                    338:     my ($hostname,$ignore_cache,$caller) = @_;
                    339:     unless ($ignore_cache) {
                    340:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    341:         if (defined($cached)) {
                    342:             return $serverhomeID;
                    343:         }
                    344:     }
                    345:     my $cachetime = 12*3600;
                    346:     my $serverhomeID;
                    347:     if ($caller eq 'loncron') { 
                    348:         my @machine_ids = &machine_ids($hostname);
                    349:         foreach my $id (@machine_ids) {
                    350:             my $response = &reply('serverhomeID',$id);
                    351:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    352:                 $serverhomeID = $response;
                    353:                 last;
                    354:             }
                    355:         }
                    356:         if ($serverhomeID eq '') {
                    357:             $serverhomeID = $machine_ids[-1];
                    358:         }
                    359:     } else {
                    360:         $serverhomeID = $serverhomeIDs{$hostname};
                    361:     }
                    362:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    363: }
                    364: 
1.1121    raeburn   365: sub get_remote_globals {
                    366:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   367:     my ($result,%returnhash,%whatneeded);
                    368:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   369:         foreach my $what (sort(keys(%{$whathash}))) {
                    370:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   371:             my ($response,$cached);
1.1121    raeburn   372:             unless ($ignore_cache) {
1.1125    raeburn   373:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   374:             }
                    375:             if (defined($cached)) {
1.1125    raeburn   376:                 $returnhash{$what} = $response;
1.1121    raeburn   377:             } else {
1.1125    raeburn   378:                 $whatneeded{$what} = 1;
1.1121    raeburn   379:             }
                    380:         }
1.1125    raeburn   381:         if (keys(%whatneeded) == 0) {
                    382:             $result = 'ok';
                    383:         } else {
1.1121    raeburn   384:             my $requested = &freeze_escape(\%whatneeded);
                    385:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   386:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    387:                 ($rep eq 'unknown_cmd')) {
                    388:                 $result = $rep;
                    389:             } else {
                    390:                 $result = 'ok';
1.1121    raeburn   391:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   392:                 foreach my $item (@pairs) {
                    393:                     my ($key,$value)=split(/=/,$item,2);
                    394:                     my $what = &unescape($key);
                    395:                     my $hashid = $lonhost.'-'.$what;
                    396:                     $returnhash{$what}=&thaw_unescape($value);
                    397:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   398:                 }
                    399:             }
                    400:         }
                    401:     }
1.1125    raeburn   402:     return ($result,\%returnhash);
1.1121    raeburn   403: }
                    404: 
1.1124    raeburn   405: sub remote_devalidate_cache {
1.1241    raeburn   406:     my ($lonhost,$cachekeys) = @_;
                    407:     my $items;
                    408:     return unless (ref($cachekeys) eq 'ARRAY');
                    409:     my $cachestr = join('&',@{$cachekeys});
                    410:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   411:     return $response;
                    412: }
                    413: 
1.1       albertel  414: # -------------------------------------------------- Non-critical communication
                    415: sub subreply {
                    416:     my ($cmd,$server)=@_;
1.838     albertel  417:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      418:     #
                    419:     #  With loncnew process trimming, there's a timing hole between lonc server
                    420:     #  process exit and the master server picking up the listen on the AF_UNIX
                    421:     #  socket.  In that time interval, a lock file will exist:
                    422: 
                    423:     my $lockfile=$peerfile.".lock";
                    424:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   425: 	sleep(0.1);
1.549     foxr      426:     }
                    427:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      428:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      429:     #
1.550     foxr      430:     #   We'll give the connection a few tries before abandoning it.  If
                    431:     #   connection is not possible, we'll con_lost back to the client.
                    432:     #   
                    433:     my $client;
                    434:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    435: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    436: 				      Type    => SOCK_STREAM,
                    437: 				      Timeout => 10);
1.869     albertel  438: 	if ($client) {
1.550     foxr      439: 	    last;		# Connected!
1.850     albertel  440: 	} else {
1.853     albertel  441: 	    &create_connection(&hostname($server),$server);
1.550     foxr      442: 	}
1.1289    damieng   443:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      444:     }
                    445:     my $answer;
                    446:     if ($client) {
1.704     albertel  447: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      448: 	$answer=<$client>;
                    449: 	if (!$answer) { $answer="con_lost"; }
                    450: 	chomp($answer);
                    451:     } else {
                    452: 	$answer = 'con_lost';	# Failed connection.
                    453:     }
1.1       albertel  454:     return $answer;
                    455: }
                    456: 
                    457: sub reply {
                    458:     my ($cmd,$server)=@_;
1.838     albertel  459:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  460:     my $answer=subreply($cmd,$server);
1.65      www       461:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396    raeburn   462:         my $logged = $cmd;
                    463:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    464:             my $subcmd = $1;
                    465:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    466:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    467:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    468:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    469:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    470:                     splice(@rest,2,1,'Hidden');
                    471:                 } elsif ($subcmd eq 'passwd') {
                    472:                     splice(@rest,2,2,('Hidden','Hidden'));
                    473:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    474:                          ($subcmd eq 'autoexportgrades')) {
                    475:                     splice(@rest,3,1,'Hidden');
                    476:                 }
                    477:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    478:             }
                    479:         }
                    480:         &logthis("<font color=\"blue\">WARNING:".
                    481:                  " $logged to $server returned $answer</font>");
1.12      www       482:     }
1.1       albertel  483:     return $answer;
                    484: }
                    485: 
                    486: # ----------------------------------------------------------- Send USR1 to lonc
                    487: 
                    488: sub reconlonc {
1.891     albertel  489:     my ($lonid) = @_;
                    490:     if ($lonid) {
1.1295    raeburn   491:         my $hostname = &hostname($lonid);
1.891     albertel  492: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    493: 	if ($hostname && -e $peerfile) {
                    494: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    495: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    496: 					     Type    => SOCK_STREAM,
                    497: 					     Timeout => 10);
                    498: 	    if ($client) {
                    499: 		print $client ("reset_retries\n");
                    500: 		my $answer=<$client>;
                    501: 		#reset just this one.
                    502: 	    }
                    503: 	}
                    504: 	return;
                    505:     }
                    506: 
1.836     www       507:     &logthis("Trying to reconnect lonc");
1.1       albertel  508:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   509:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  510: 	my $loncpid=<$fh>;
                    511:         chomp($loncpid);
                    512:         if (kill 0 => $loncpid) {
                    513: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    514:             kill USR1 => $loncpid;
                    515:             sleep 1;
1.1295    raeburn   516:         } else {
1.12      www       517: 	    &logthis(
1.672     albertel  518:                "<font color=\"blue\">WARNING:".
1.12      www       519:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  520:         }
                    521:     } else {
1.836     www       522: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  523:     }
                    524: }
                    525: 
                    526: # ------------------------------------------------------ Critical communication
1.12      www       527: 
1.1       albertel  528: sub critical {
                    529:     my ($cmd,$server)=@_;
1.838     albertel  530:     unless (&hostname($server)) {
1.672     albertel  531:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       532:                " Critical message to unknown server ($server)</font>");
                    533:         return 'no_such_host';
                    534:     }
1.1       albertel  535:     my $answer=reply($cmd,$server);
                    536:     if ($answer eq 'con_lost') {
1.1295    raeburn   537: 	&reconlonc($server);
1.589     albertel  538: 	my $answer=reply($cmd,$server);
1.1       albertel  539:         if ($answer eq 'con_lost') {
                    540:             my $now=time;
                    541:             my $middlename=$cmd;
1.5       www       542:             $middlename=substr($middlename,0,16);
1.1       albertel  543:             $middlename=~s/\W//g;
                    544:             my $dfilename=
1.305     www       545:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    546:             $dumpcount++;
1.1       albertel  547:             {
1.448     albertel  548: 		my $dfh;
1.1359    raeburn   549: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  550: 		    print $dfh "$cmd\n"; 
                    551: 		    close($dfh);
                    552: 		}
1.1       albertel  553:             }
1.1288    damieng   554:             sleep 1;
1.1       albertel  555:             my $wcmd='';
                    556:             {
1.448     albertel  557: 		my $dfh;
1.1359    raeburn   558: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  559: 		    $wcmd=<$dfh>; 
                    560: 		    close($dfh);
                    561: 		}
1.1       albertel  562:             }
                    563:             chomp($wcmd);
1.7       www       564:             if ($wcmd eq $cmd) {
1.672     albertel  565: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       566:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  567:                 &logperm("D:$server:$cmd");
                    568: 	        return 'con_delayed';
                    569:             } else {
1.672     albertel  570:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       571:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  572:                 &logperm("F:$server:$cmd");
                    573:                 return 'con_failed';
                    574:             }
                    575:         }
                    576:     }
                    577:     return $answer;
1.405     albertel  578: }
                    579: 
1.755     albertel  580: # ------------------------------------------- check if return value is an error
                    581: 
                    582: sub error {
                    583:     my ($result) = @_;
1.756     albertel  584:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  585: 	if ($2 == 2) { return undef; }
                    586: 	return $1;
                    587:     }
                    588:     return undef;
                    589: }
                    590: 
1.783     albertel  591: sub convert_and_load_session_env {
                    592:     my ($lonidsdir,$handle)=@_;
                    593:     my @profile;
                    594:     {
1.917     albertel  595: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    596: 	if (!$opened) {
1.915     albertel  597: 	    return 0;
                    598: 	}
1.783     albertel  599: 	flock($idf,LOCK_SH);
                    600: 	@profile=<$idf>;
                    601: 	close($idf);
                    602:     }
                    603:     my %temp_env;
                    604:     foreach my $line (@profile) {
1.786     albertel  605: 	if ($line !~ m/=/) {
                    606: 	    return 0;
                    607: 	}
1.783     albertel  608: 	chomp($line);
                    609: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    610: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    611:     }
                    612:     unlink("$lonidsdir/$handle.id");
                    613:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    614: 	    0640)) {
                    615: 	%disk_env = %temp_env;
                    616: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    617: 	untie(%disk_env);
                    618:     }
1.786     albertel  619:     return 1;
1.783     albertel  620: }
                    621: 
1.374     www       622: # ------------------------------------------- Transfer profile into environment
1.780     albertel  623: my $env_loaded;
                    624: sub transfer_profile_to_env {
1.788     albertel  625:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    626:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       627: 
1.720     albertel  628:     if (!defined($lonidsdir)) {
                    629: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    630:     }
                    631:     if (!defined($handle)) {
                    632:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    633:     }
                    634: 
1.786     albertel  635:     my $convert;
                    636:     {
1.917     albertel  637:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    638: 	if (!$opened) {
1.915     albertel  639: 	    return;
                    640: 	}
1.786     albertel  641: 	flock($idf,LOCK_SH);
                    642: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    643: 		&GDBM_READER(),0640)) {
                    644: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    645: 	    untie(%disk_env);
                    646: 	} else {
                    647: 	    $convert = 1;
                    648: 	}
                    649:     }
                    650:     if ($convert) {
                    651: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    652: 	    &logthis("Failed to load session, or convert session.");
                    653: 	}
1.374     www       654:     }
1.783     albertel  655: 
1.786     albertel  656:     my %remove;
1.783     albertel  657:     while ( my $envname = each(%env) ) {
1.433     matthew   658:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    659:             if ($time < time-300) {
1.783     albertel  660:                 $remove{$key}++;
1.433     matthew   661:             }
                    662:         }
                    663:     }
1.783     albertel  664: 
1.619     albertel  665:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  666:     $env_loaded=1;
1.783     albertel  667:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   668:         &delenv($expired_key);
1.374     www       669:     }
1.1       albertel  670: }
                    671: 
1.916     albertel  672: # ---------------------------------------------------- Check for valid session 
                    673: sub check_for_valid_session {
1.1355    raeburn   674:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  675:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   676:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    677:     if ($name eq 'lonDAV') {
                    678:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    679:     } else {
                    680:         $lonidsdir=$r->dir_config('lonIDsDir');
                    681:         if ($name eq '') {
                    682:             $name = 'lonID';
                    683:         }
                    684:     }
                    685:     if ($name eq 'lonID') {
                    686:         $secure = 'lonSID';
1.1337    raeburn   687:         $linkname = 'lonLinkID';
                    688:         $pubname = 'lonPubID';
1.1378    raeburn   689:         if (exists($cookies{$secure})) {
                    690:             $lonid=$cookies{$secure};
                    691:         } elsif (exists($cookies{$name})) {
                    692:             $lonid=$cookies{$name};
                    693:         } elsif (exists($cookies{$linkname})) {
1.1337    raeburn   694:             $lonid=$cookies{$linkname};
1.1378    raeburn   695:         } elsif (exists($cookies{$pubname})) {
                    696:             $lonid=$cookies{$pubname};
1.1337    raeburn   697:         }
1.1378    raeburn   698:     } else {
                    699:         $lonid=$cookies{$name};
1.1337    raeburn   700:     }
1.916     albertel  701:     return undef if (!$lonid);
                    702: 
                    703:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   704:     if (-l "$lonidsdir/$handle.id") {
                    705:         my $link = readlink("$lonidsdir/$handle.id");
                    706:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    707:             $handle = $1;
                    708:         }
1.1155    raeburn   709:     }
1.1355    raeburn   710:     if (!-e "$lonidsdir/$handle.id") {
                    711:         if ((ref($domref)) && ($name eq 'lonID') && 
                    712:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    713:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    714:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    715:                 $$domref = $possudom;
                    716:             }
                    717:         }
                    718:         return undef;
                    719:     }
1.916     albertel  720: 
1.917     albertel  721:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    722:     return undef if (!$opened);
1.916     albertel  723: 
                    724:     flock($idf,LOCK_SH);
                    725:     my %disk_env;
                    726:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    727: 	    &GDBM_READER(),0640)) {
                    728: 	return undef;	
                    729:     }
                    730: 
                    731:     if (!defined($disk_env{'user.name'})
                    732: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   733:         untie(%disk_env);
1.916     albertel  734: 	return undef;
                    735:     }
1.1245    raeburn   736: 
                    737:     if (ref($userhashref) eq 'HASH') {
                    738:         $userhashref->{'name'} = $disk_env{'user.name'};
                    739:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   740:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   741:         if ($userhashref->{'lti'}) {
                    742:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    743:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    744:         }
1.1212    raeburn   745:     }
1.1394    raeburn   746:     untie(%disk_env);
1.1245    raeburn   747: 
1.916     albertel  748:     return $handle;
                    749: }
                    750: 
1.830     albertel  751: sub timed_flock {
                    752:     my ($file,$lock_type) = @_;
                    753:     my $failed=0;
                    754:     eval {
                    755: 	local $SIG{__DIE__}='DEFAULT';
                    756: 	local $SIG{ALRM}=sub {
                    757: 	    $failed=1;
                    758: 	    die("failed lock");
                    759: 	};
                    760: 	alarm(13);
                    761: 	flock($file,$lock_type);
                    762: 	alarm(0);
                    763:     };
                    764:     if ($failed) {
                    765: 	return undef;
                    766:     } else {
                    767: 	return 1;
                    768:     }
                    769: }
                    770: 
1.1392    raeburn   771: sub get_sessionfile_vars {
                    772:     my ($handle,$lonidsdir,$storearr) = @_;
                    773:     my %returnhash;
                    774:     unless (ref($storearr) eq 'ARRAY') {
                    775:         return %returnhash;
                    776:     }
                    777:     if (-l "$lonidsdir/$handle.id") {
                    778:         my $link = readlink("$lonidsdir/$handle.id");
                    779:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    780:             $handle = $1;
                    781:         }
                    782:     }
                    783:     if ((-e "$lonidsdir/$handle.id") &&
                    784:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    785:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    786:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    787:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    788:                 flock($idf,LOCK_SH);
                    789:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    790:                         &GDBM_READER(),0640)) {
                    791:                     foreach my $item (@{$storearr}) {
                    792:                         $returnhash{$item} = $disk_env{$item};
                    793:                     }
                    794:                     untie(%disk_env);
                    795:                 }
                    796:             }
                    797:         }
                    798:     }
                    799:     return %returnhash;
                    800: }
                    801: 
1.5       www       802: # ---------------------------------------------------------- Append Environment
                    803: 
                    804: sub appenv {
1.949     raeburn   805:     my ($newenv,$roles) = @_;
                    806:     if (ref($newenv) eq 'HASH') {
                    807:         foreach my $key (keys(%{$newenv})) {
                    808:             my $refused = 0;
                    809: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    810:                 $refused = 1;
                    811:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   812:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   813:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    814:                         $refused = 0;
                    815:                     }
                    816:                 }
                    817:             }
                    818:             if ($refused) {
                    819:                 &logthis("<font color=\"blue\">WARNING: ".
                    820:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    821:                          .'</font>');
                    822: 	        delete($newenv->{$key});
                    823:             } else {
                    824:                 $env{$key}=$newenv->{$key};
                    825:             }
                    826:         }
1.1376    raeburn   827:         my $lonids = $perlvar{'lonIDsDir'};
                    828:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    829:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    830:             if ($opened
                    831: 	        && &timed_flock($env_file,LOCK_EX)
                    832: 	        &&
                    833: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    834: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    835: 	        while (my ($key,$value) = each(%{$newenv})) {
                    836: 	            $disk_env{$key} = $value;
                    837: 	        }
                    838: 	        untie(%disk_env);
                    839:             }
1.35      www       840:         }
1.191     harris41  841:     }
1.56      www       842:     return 'ok';
                    843: }
                    844: # ----------------------------------------------------- Delete from Environment
                    845: 
                    846: sub delenv {
1.1104    raeburn   847:     my ($delthis,$regexp,$roles) = @_;
                    848:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    849:         my $refused = 1;
                    850:         if (ref($roles) eq 'ARRAY') {
                    851:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    852:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    853:                 $refused = 0;
                    854:             }
                    855:         }
                    856:         if ($refused) {
                    857:             &logthis("<font color=\"blue\">WARNING: ".
                    858:                      "Attempt to delete from environment ".$delthis);
                    859:             return 'error';
                    860:         }
1.56      www       861:     }
1.917     albertel  862:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    863:     if ($opened
1.915     albertel  864: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  865: 	&&
                    866: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    867: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  868: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   869: 	    if ($regexp) {
                    870:                 if ($key=~/^$delthis/) {
                    871:                     delete($env{$key});
                    872:                     delete($disk_env{$key});
                    873:                 } 
                    874:             } else {
                    875:                 if ($key=~/^\Q$delthis\E/) {
                    876: 		    delete($env{$key});
                    877: 		    delete($disk_env{$key});
                    878: 	        }
                    879:             }
1.448     albertel  880: 	}
1.783     albertel  881: 	untie(%disk_env);
1.5       www       882:     }
                    883:     return 'ok';
1.369     albertel  884: }
                    885: 
1.790     albertel  886: sub get_env_multiple {
                    887:     my ($name) = @_;
                    888:     my @values;
                    889:     if (defined($env{$name})) {
                    890:         # exists is it an array
                    891:         if (ref($env{$name})) {
                    892:             @values=@{ $env{$name} };
                    893:         } else {
                    894:             $values[0]=$env{$name};
                    895:         }
                    896:     }
                    897:     return(@values);
                    898: }
                    899: 
1.958     www       900: # ------------------------------------------------------------------- Locking
                    901: 
                    902: sub set_lock {
                    903:     my ($text)=@_;
                    904:     $locknum++;
                    905:     my $id=$$.'-'.$locknum;
                    906:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    907:              'session.lock.'.$id => $text});
                    908:     return $id;
                    909: }
                    910: 
                    911: sub get_locks {
                    912:     my $num=0;
                    913:     my %texts=();
                    914:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    915:        if ($lock=~/\w/) {
                    916:           $num++;
                    917:           $texts{$lock}=$env{'session.lock.'.$lock};
                    918:        }
                    919:    }
                    920:    return ($num,%texts);
                    921: }
                    922: 
                    923: sub remove_lock {
                    924:     my ($id)=@_;
                    925:     my $newlocks='';
                    926:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    927:        if (($lock=~/\w/) && ($lock ne $id)) {
                    928:           $newlocks.=','.$lock;
                    929:        }
                    930:     }
                    931:     &appenv({'session.locks' => $newlocks});
                    932:     &delenv('session.lock.'.$id);
                    933: }
                    934: 
                    935: sub remove_all_locks {
                    936:     my $activelocks=$env{'session.locks'};
                    937:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    938:        if ($lock=~/\w/) {
                    939:           &remove_lock($lock);
                    940:        }
                    941:     }
                    942: }
                    943: 
                    944: 
1.369     albertel  945: # ------------------------------------------ Find out current server userload
                    946: sub userload {
                    947:     my $numusers=0;
                    948:     {
                    949: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    950: 	my $filename;
                    951: 	my $curtime=time;
                    952: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  953: 	    next if ($filename eq '.' || $filename eq '..');
                    954: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   955:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  956: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  957: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  958: 	}
                    959: 	closedir(LONIDS);
                    960:     }
                    961:     my $userloadpercent=0;
                    962:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    963:     if ($maxuserload) {
1.371     albertel  964: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  965:     }
1.372     albertel  966:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  967:     return $userloadpercent;
1.283     www       968: }
                    969: 
1.1       albertel  970: # ------------------------------ Find server with least workload from spare.tab
1.11      www       971: 
1.1       albertel  972: sub spareserver {
1.1083    raeburn   973:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  974:     my $spare_server;
1.370     albertel  975:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  976:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    977:                                                      :  $userloadpercent;
1.1083    raeburn   978:     my ($uint_dom,$remotesessions);
                    979:     if (($udom ne '') && (&domain($udom) ne '')) {
                    980:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    981:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    982:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    983:         $remotesessions = $udomdefaults{'remotesessions'};
                    984:     }
1.1123    raeburn   985:     my $spareshash = &this_host_spares($udom);
                    986:     if (ref($spareshash) eq 'HASH') {
                    987:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    988:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   989:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    990:                                              $try_server));
1.1123    raeburn   991: 	        ($spare_server, $lowest_load) =
                    992: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    993:             }
1.1083    raeburn   994:         }
1.784     albertel  995: 
1.1123    raeburn   996:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    997: 
                    998:         if (!$found_server) {
                    999:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1000: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1001:                     next unless (&spare_can_host($udom,$uint_dom,
                   1002:                                                  $remotesessions,$try_server));
1.1123    raeburn  1003: 	            ($spare_server, $lowest_load) =
                   1004: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1005:                 }
                   1006: 	    }
                   1007:         }
1.784     albertel 1008:     }
                   1009: 
                   1010:     if (!$want_server_name) {
1.1001    raeburn  1011:         if (defined($spare_server)) {
                   1012:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1013:             if (defined($hostname)) {
1.1397  ! raeburn  1014:                 my $protocol = 'http';
        !          1015:                 if ($protocol{$spare_server} eq 'https') {
        !          1016:                     $protocol = $protocol{$spare_server};
        !          1017:                 }
1.1001    raeburn  1018: 	        $spare_server = $protocol.'://'.$hostname;
                   1019:             }
                   1020:         }
1.784     albertel 1021:     }
                   1022:     return $spare_server;
                   1023: }
                   1024: 
                   1025: sub compare_server_load {
1.1253    raeburn  1026:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1027: 
                   1028:     if ($required) {
                   1029:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1030:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1031:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1032:         if (($major eq '' && $minor eq '') ||
                   1033:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1034:             return ($spare_server,$lowest_load);
                   1035:         }
                   1036:     }
1.784     albertel 1037: 
                   1038:     my $loadans     = &reply('load',    $try_server);
                   1039:     my $userloadans = &reply('userload',$try_server);
                   1040: 
                   1041:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1042: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1043:     }
                   1044: 
                   1045:     my $load;
                   1046:     if ($loadans =~ /\d/) {
                   1047: 	if ($userloadans =~ /\d/) {
                   1048: 	    #both are numbers, pick the bigger one
                   1049: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1050: 		                              : $userloadans;
1.411     albertel 1051: 	} else {
1.784     albertel 1052: 	    $load = $loadans;
1.411     albertel 1053: 	}
1.784     albertel 1054:     } else {
                   1055: 	$load = $userloadans;
                   1056:     }
                   1057: 
                   1058:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1059: 	$spare_server = $try_server;
                   1060: 	$lowest_load  = $load;
1.370     albertel 1061:     }
1.784     albertel 1062:     return ($spare_server,$lowest_load);
1.202     matthew  1063: }
1.914     albertel 1064: 
                   1065: # --------------------------- ask offload servers if user already has a session
                   1066: sub find_existing_session {
                   1067:     my ($udom,$uname) = @_;
1.1123    raeburn  1068:     my $spareshash = &this_host_spares($udom);
                   1069:     if (ref($spareshash) eq 'HASH') {
                   1070:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1071:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1072:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1073:             }
                   1074:         }
                   1075:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1076:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1077:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1078:             }
                   1079:         }
1.914     albertel 1080:     }
                   1081:     return;
                   1082: }
                   1083: 
1.1389    raeburn  1084: # check if user's browser sent load balancer cookie and server still has session
                   1085: # and is not overloaded.
                   1086: sub check_for_balancer_cookie {
                   1087:     my ($r,$update_mtime) = @_;
                   1088:     my ($otherserver,$cookie);
                   1089:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1090:     if (exists($cookies{'balanceID'})) {
                   1091:         my $balid = $cookies{'balanceID'};
                   1092:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1093:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1094:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1095:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1096:                 my ($possudom,$possuname) = ($1,$2);
                   1097:                 my $has_session = 0;
                   1098:                 if ((&domain($possudom) ne '') &&
                   1099:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1100:                     my $try_server;
                   1101:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1102:                     if ($opened) {
                   1103:                         flock($idf,LOCK_SH);
                   1104:                         while (my $line = <$idf>) {
                   1105:                             chomp($line);
                   1106:                             if (&hostname($line) ne '') {
                   1107:                                 $try_server = $line;
                   1108:                                 last;
                   1109:                             }
                   1110:                         }
                   1111:                         close($idf);
                   1112:                         if (($try_server) &&
                   1113:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1114:                             my $lowest_load = 30000;
                   1115:                             ($otherserver,$lowest_load) =
                   1116:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1117:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1118:                                 $has_session = 1;
                   1119:                             } else {
                   1120:                                 undef($otherserver);
                   1121:                             }
                   1122:                         }
                   1123:                     }
                   1124:                 }
                   1125:                 if ($has_session) {
                   1126:                     if ($update_mtime) {
                   1127:                         my $atime = my $mtime = time;
                   1128:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1129:                     }
                   1130:                 } else {
                   1131:                     unlink("$balancedir/$cookie.id");
                   1132:                 }
                   1133:             }
                   1134:         }
                   1135:     }
                   1136:     return ($otherserver,$cookie);
                   1137: }
                   1138: 
                   1139: sub delbalcookie {
                   1140:     my ($cookie,$balancer) =@_;
                   1141:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1142:         my ($udom,$uname) = ($1,$2);
                   1143:         my $uprimary_id = &domain($udom,'primary');
                   1144:         my $uintdom = &internet_dom($uprimary_id);
                   1145:         my $intdom = &internet_dom($balancer);
                   1146:         my $serverhomedom = &host_domain($balancer);
                   1147:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1148:             return &reply("delbalcookie:$cookie",$balancer);
                   1149:         }
                   1150:     }
                   1151: }
                   1152: 
1.914     albertel 1153: # -------------------------------- ask if server already has a session for user
                   1154: sub has_user_session {
                   1155:     my ($lonid,$udom,$uname) = @_;
                   1156:     my $result = &reply(join(':','userhassession',
                   1157: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1158:     return 1 if ($result eq 'ok');
                   1159: 
                   1160:     return 0;
                   1161: }
                   1162: 
1.1076    raeburn  1163: # --------- determine least loaded server in a user's domain which allows login
                   1164: 
                   1165: sub choose_server {
1.1259    raeburn  1166:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1167:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1168:     my %servers = &get_servers($udom);
1.1076    raeburn  1169:     my $lowest_load = 30000;
1.1259    raeburn  1170:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1171:     if ($skiploadbal) {
                   1172:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1173:         unless (defined($cached)) {
                   1174:             my $cachetime = 60*60*24;
                   1175:             my %domconfig =
                   1176:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1177:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1178:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1179:                                            $cachetime);
                   1180:             }
                   1181:         }
                   1182:     }
1.1076    raeburn  1183:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1184:         if ($skiploadbal) {
                   1185:             if (ref($balancers) eq 'HASH') {
                   1186:                 next if (exists($balancers->{$lonhost}));
                   1187:             }
1.1389    raeburn  1188:         }
1.1115    raeburn  1189:         my $loginvia;
                   1190:         if ($checkloginvia) {
                   1191:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1192:             if ($loginvia) {
                   1193:                 my ($server,$path) = split(/:/,$loginvia);
                   1194:                 ($login_host, $lowest_load) =
1.1253    raeburn  1195:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1196:                 if ($login_host eq $server) {
                   1197:                     $portal_path = $path;
1.1151    raeburn  1198:                     $isredirect = 1;
1.1116    raeburn  1199:                 }
                   1200:             } else {
                   1201:                 ($login_host, $lowest_load) =
1.1253    raeburn  1202:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1203:                 if ($login_host eq $lonhost) {
                   1204:                     $portal_path = '';
1.1151    raeburn  1205:                     $isredirect = ''; 
1.1116    raeburn  1206:                 }
                   1207:             }
                   1208:         } else {
1.1076    raeburn  1209:             ($login_host, $lowest_load) =
1.1253    raeburn  1210:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1211:         }
                   1212:     }
                   1213:     if ($login_host ne '') {
1.1116    raeburn  1214:         $hostname = &hostname($login_host);
1.1076    raeburn  1215:     }
1.1331    raeburn  1216:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1217: }
                   1218: 
1.202     matthew  1219: # --------------------------------------------- Try to change a user's password
                   1220: 
                   1221: sub changepass {
1.799     raeburn  1222:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1223:     $currentpass = &escape($currentpass);
                   1224:     $newpass     = &escape($newpass);
1.1030    raeburn  1225:     my $lonhost = $perlvar{'lonHostID'};
                   1226:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1227: 		       $server);
                   1228:     if (! $answer) {
                   1229: 	&logthis("No reply on password change request to $server ".
                   1230: 		 "by $uname in domain $udom.");
                   1231:     } elsif ($answer =~ "^ok") {
                   1232:         &logthis("$uname in $udom successfully changed their password ".
                   1233: 		 "on $server.");
                   1234:     } elsif ($answer =~ "^pwchange_failure") {
                   1235: 	&logthis("$uname in $udom was unable to change their password ".
                   1236: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1237: 		 "or pwchange");
                   1238:     } elsif ($answer =~ "^non_authorized") {
                   1239:         &logthis("$uname in $udom did not get their password correct when ".
                   1240: 		 "attempting to change it on $server.");
                   1241:     } elsif ($answer =~ "^auth_mode_error") {
                   1242:         &logthis("$uname in $udom attempted to change their password despite ".
                   1243: 		 "not being locally or internally authenticated on $server.");
                   1244:     } elsif ($answer =~ "^unknown_user") {
                   1245:         &logthis("$uname in $udom attempted to change their password ".
                   1246: 		 "on $server but were unable to because $server is not ".
                   1247: 		 "their home server.");
                   1248:     } elsif ($answer =~ "^refused") {
                   1249: 	&logthis("$server refused to change $uname in $udom password because ".
                   1250: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1251:     } elsif ($answer =~ "invalid_client") {
                   1252:         &logthis("$server refused to change $uname in $udom password because ".
                   1253:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1254:     }
                   1255:     return $answer;
1.1       albertel 1256: }
                   1257: 
1.169     harris41 1258: # ----------------------- Try to determine user's current authentication scheme
                   1259: 
                   1260: sub queryauthenticate {
                   1261:     my ($uname,$udom)=@_;
1.456     albertel 1262:     my $uhome=&homeserver($uname,$udom);
                   1263:     if (!$uhome) {
                   1264: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1265: 	return 'no_host';
                   1266:     }
                   1267:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1268:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1269: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1270:     }
1.456     albertel 1271:     return $answer;
1.169     harris41 1272: }
                   1273: 
1.1       albertel 1274: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1275: 
1.1       albertel 1276: sub authenticate {
1.1073    raeburn  1277:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1278:     $upass=&escape($upass);
                   1279:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1280:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1281:     my $newhome;
1.836     www      1282:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1283: # Maybe the machine was offline and only re-appeared again recently?
                   1284:         &reconlonc();
                   1285: # One more
1.952     raeburn  1286: 	$uhome=&homeserver($uname,$udom,1);
                   1287:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1288:             if (defined(&domain($udom,'primary'))) {
                   1289:                 $newhome=&domain($udom,'primary');
                   1290:             }
                   1291:             if ($newhome ne '') {
                   1292:                 $uhome = $newhome;
                   1293:             }
                   1294:         }
1.836     www      1295: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1296: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1297: 	    return 'no_host';
                   1298:         }
1.1       albertel 1299:     }
1.1073    raeburn  1300:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1301:     if ($answer eq 'authorized') {
1.952     raeburn  1302:         if ($newhome) {
                   1303:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1304:             return 'no_account_on_host'; 
                   1305:         } else {
                   1306:             &logthis("User $uname at $udom authorized by $uhome");
                   1307:             return $uhome;
                   1308:         }
1.471     albertel 1309:     }
                   1310:     if ($answer eq 'non_authorized') {
                   1311: 	&logthis("User $uname at $udom rejected by $uhome");
                   1312: 	return 'no_host'; 
1.9       www      1313:     }
1.471     albertel 1314:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1315:     return 'no_host';
                   1316: }
                   1317: 
1.1073    raeburn  1318: sub can_host_session {
1.1074    raeburn  1319:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1320:     my $canhost = 1;
1.1074    raeburn  1321:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1322:     if (ref($remotesessions) eq 'HASH') {
                   1323:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1324:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1325:                 $canhost = 0;
                   1326:             } else {
                   1327:                 $canhost = 1;
                   1328:             }
                   1329:         }
                   1330:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1331:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1332:                 $canhost = 1;
                   1333:             } else {
                   1334:                 $canhost = 0;
                   1335:             }
                   1336:         }
                   1337:         if ($canhost) {
                   1338:             if ($remotesessions->{'version'} ne '') {
                   1339:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1340:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1341:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1342:                         my $major = $1;
                   1343:                         my $minor = $2;
                   1344:                         if (($major < $reqmajor ) ||
                   1345:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1346:                             $canhost = 0;
                   1347:                         }
                   1348:                     } else {
                   1349:                         $canhost = 0;
                   1350:                     }
                   1351:                 }
                   1352:             }
                   1353:         }
                   1354:     }
                   1355:     if ($canhost) {
                   1356:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1357:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1358:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1359:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1360:                 if (($uint_dom ne '') && 
                   1361:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1362:                     $canhost = 0;
                   1363:                 } else {
                   1364:                     $canhost = 1;
                   1365:                 }
                   1366:             }
                   1367:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1368:                 if (($uint_dom ne '') && 
                   1369:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1370:                     $canhost = 1;
                   1371:                 } else {
                   1372:                     $canhost = 0;
                   1373:                 }
                   1374:             }
                   1375:         }
                   1376:     }
                   1377:     return $canhost;
                   1378: }
                   1379: 
1.1083    raeburn  1380: sub spare_can_host {
                   1381:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1382:     my $canhost=1;
1.1279    raeburn  1383:     my $try_server_hostname = &hostname($try_server);
                   1384:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1385:     my $serverhomedom = &host_domain($serverhomeID);
                   1386:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1387:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1388:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1389:             $canhost = 0;
                   1390:         }
                   1391:     }
                   1392:     if (($canhost) && ($uint_dom)) {
                   1393:         my @intdoms;
                   1394:         my $internet_names = &get_internet_names($try_server);
                   1395:         if (ref($internet_names) eq 'ARRAY') {
                   1396:             @intdoms = @{$internet_names};
                   1397:         }
                   1398:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1399:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1400:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1401:                                          $remotesessions,
                   1402:                                          $defdomdefaults{'hostedsessions'});
                   1403:         }
1.1083    raeburn  1404:     }
                   1405:     return $canhost;
                   1406: }
                   1407: 
1.1123    raeburn  1408: sub this_host_spares {
                   1409:     my ($dom) = @_;
1.1126    raeburn  1410:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1411:     my @hosts = &current_machine_ids();
                   1412:     foreach my $lonhost (@hosts) {
                   1413:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1414:             $dom_in_use = $dom;
                   1415:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1416:             last;
                   1417:         }
                   1418:     }
1.1126    raeburn  1419:     if ($dom_in_use ne '') {
                   1420:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1421:     }
                   1422:     if (ref($result) ne 'HASH') {
                   1423:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1424:         $dom_in_use = &host_domain($lonhost_in_use);
                   1425:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1426:         if (ref($result) ne 'HASH') {
                   1427:             $result = \%spareid;
                   1428:         }
                   1429:     }
                   1430:     return $result;
                   1431: }
                   1432: 
                   1433: sub spares_for_offload  {
                   1434:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1435:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1436:     if (defined($cached)) {
                   1437:         return $result;
                   1438:     } else {
1.1126    raeburn  1439:         my $cachetime = 60*60*24;
                   1440:         my %domconfig =
                   1441:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1442:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1443:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1444:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1445:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1446:                 }
                   1447:             }
                   1448:         }
                   1449:     }
1.1126    raeburn  1450:     return;
1.1123    raeburn  1451: }
                   1452: 
1.1129    raeburn  1453: sub get_lonbalancer_config {
                   1454:     my ($servers) = @_;
                   1455:     my ($currbalancer,$currtargets);
                   1456:     if (ref($servers) eq 'HASH') {
                   1457:         foreach my $server (keys(%{$servers})) {
                   1458:             my %what = (
                   1459:                          spareid => 1,
                   1460:                          perlvar => 1,
                   1461:                        );
                   1462:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1463:             if ($result eq 'ok') {
                   1464:                 if (ref($returnhash) eq 'HASH') {
                   1465:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1466:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1467:                             $currbalancer = $server;
                   1468:                             $currtargets = {};
                   1469:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1470:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1471:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1472:                                 }
                   1473:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1474:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1475:                                 }
                   1476:                             }
                   1477:                             last;
                   1478:                         }
                   1479:                     }
                   1480:                 }
                   1481:             }
                   1482:         }
                   1483:     }
                   1484:     return ($currbalancer,$currtargets);
                   1485: }
                   1486: 
                   1487: sub check_loadbalancing {
1.1331    raeburn  1488:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1489:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1490:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1491:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1492:     my @hosts = &current_machine_ids();
1.1129    raeburn  1493:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1494:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1495:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1496:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1497:     my $domneedscache;
1.1129    raeburn  1498:     my $cachetime = 60*60*24;
                   1499: 
                   1500:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1501:         $dom_in_use = $udom;
                   1502:         $homeintdom = 1;
                   1503:     } else {
                   1504:         $dom_in_use = $serverhomedom;
                   1505:     }
                   1506:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1507:     unless (defined($cached)) {
                   1508:         my %domconfig =
                   1509:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1510:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1511:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1512:         } else {
                   1513:             $domneedscache = $dom_in_use;
1.1129    raeburn  1514:         }
                   1515:     }
                   1516:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1517:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1518:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1519:         if ($is_balancer) {
                   1520:             if (ref($currrules) eq 'HASH') {
                   1521:                 if ($homeintdom) {
                   1522:                     if ($uname ne '') {
                   1523:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1524:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1525:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1526:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1527:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1528:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1529:                             }
                   1530:                         }
                   1531:                         if ($rule_in_effect eq '') {
                   1532:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1533:                             if ($userenv{'inststatus'} ne '') {
                   1534:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1535:                                 my ($othertitle,$usertypes,$types) =
                   1536:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1537:                                 if (ref($types) eq 'ARRAY') {
                   1538:                                     foreach my $type (@{$types}) {
                   1539:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1540:                                             if (exists($currrules->{$type})) {
                   1541:                                                 $rule_in_effect = $currrules->{$type};
                   1542:                                             }
                   1543:                                         }
                   1544:                                     }
                   1545:                                 }
                   1546:                             } else {
                   1547:                                 if (exists($currrules->{'default'})) {
                   1548:                                     $rule_in_effect = $currrules->{'default'};
                   1549:                                 }
                   1550:                             }
                   1551:                         }
                   1552:                     } else {
                   1553:                         if (exists($currrules->{'default'})) {
                   1554:                             $rule_in_effect = $currrules->{'default'};
                   1555:                         }
                   1556:                     }
                   1557:                 } else {
                   1558:                     if ($currrules->{'_LC_external'} ne '') {
                   1559:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1560:                     }
                   1561:                 }
                   1562:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1563:                                                        $uname,$udom);
                   1564:             }
                   1565:         }
                   1566:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1567:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1568:         unless (defined($cached)) {
                   1569:             my %domconfig =
                   1570:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1571:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1572:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1573:             } else {
                   1574:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1575:             }
                   1576:         }
                   1577:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1578:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1579:                 &check_balancer_result($result,@hosts);
                   1580:             if ($is_balancer) {
1.1129    raeburn  1581:                 if (ref($currrules) eq 'HASH') {
                   1582:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1583:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1584:                     }
                   1585:                 }
                   1586:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1587:                                                        $uname,$udom);
                   1588:             }
                   1589:         } else {
                   1590:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1591:                 $is_balancer = 1;
                   1592:                 $offloadto = &this_host_spares($dom_in_use);
                   1593:             }
1.1307    raeburn  1594:             unless (defined($cached)) {
                   1595:                 $domneedscache = $serverhomedom;
                   1596:             }
1.1129    raeburn  1597:         }
                   1598:     } else {
                   1599:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1600:             $is_balancer = 1;
                   1601:             $offloadto = &this_host_spares($dom_in_use);
                   1602:         }
1.1307    raeburn  1603:         unless (defined($cached)) {
                   1604:             $domneedscache = $serverhomedom;
                   1605:         }
                   1606:     }
                   1607:     if ($domneedscache) {
                   1608:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1609:     }
1.1176    raeburn  1610:     if ($is_balancer) {
                   1611:         my $lowest_load = 30000;
                   1612:         if (ref($offloadto) eq 'HASH') {
                   1613:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1614:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1615:                     ($otherserver,$lowest_load) =
                   1616:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1617:                 }
1.1129    raeburn  1618:             }
1.1176    raeburn  1619:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1620: 
1.1176    raeburn  1621:             if (!$found_server) {
                   1622:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1623:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1624:                         ($otherserver,$lowest_load) =
                   1625:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1626:                     }
                   1627:                 }
                   1628:             }
                   1629:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1630:             if (@{$offloadto} == 1) {
                   1631:                 $otherserver = $offloadto->[0];
                   1632:             } elsif (@{$offloadto} > 1) {
                   1633:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1634:                     ($otherserver,$lowest_load) =
                   1635:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1636:                 }
                   1637:             }
                   1638:         }
1.1331    raeburn  1639:         unless ($caller eq 'login') {
                   1640:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1641:                 $is_balancer = 0;
                   1642:                 if ($uname ne '' && $udom ne '') {
                   1643:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1644:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1645:                                  'user.loadbalcheck.time' => time});
                   1646:                     }
1.1176    raeburn  1647:                 }
1.1129    raeburn  1648:             }
                   1649:         }
1.1389    raeburn  1650:         unless ($homeintdom) {
                   1651:             undef($setcookie);
                   1652:         }
1.1129    raeburn  1653:     }
1.1391    raeburn  1654:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1655: }
                   1656: 
1.1191    raeburn  1657: sub check_balancer_result {
                   1658:     my ($result,@hosts) = @_;
1.1391    raeburn  1659:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1660:     if (ref($result) eq 'HASH') {
                   1661:         if ($result->{'lonhost'} ne '') {
                   1662:             my $currbalancer = $result->{'lonhost'};
                   1663:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1664:                 $is_balancer = 1;
                   1665:                 $currtargets = $result->{'targets'};
                   1666:                 $currrules = $result->{'rules'};
                   1667:             }
1.1391    raeburn  1668:             $dom_balancers = $currbalancer;
1.1191    raeburn  1669:         } else {
1.1391    raeburn  1670:             if (keys(%{$result})) {
                   1671:                 foreach my $key (keys(%{$result})) {
                   1672:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1673:                         (ref($result->{$key}) eq 'HASH')) {
                   1674:                         $is_balancer = 1;
                   1675:                         $currrules = $result->{$key}{'rules'};
                   1676:                         $currtargets = $result->{$key}{'targets'};
                   1677:                         $setcookie = $result->{$key}{'cookie'};
                   1678:                         last;
                   1679:                     }
1.1191    raeburn  1680:                 }
1.1391    raeburn  1681:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1682:             }
                   1683:         }
                   1684:     }
1.1391    raeburn  1685:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1686: }
                   1687: 
1.1129    raeburn  1688: sub get_loadbalancer_targets {
                   1689:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1690:     my $offloadto;
1.1175    raeburn  1691:     if ($rule_in_effect eq 'none') {
                   1692:         return [$perlvar{'lonHostID'}];
                   1693:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1694:         $offloadto = $currtargets;
                   1695:     } else {
                   1696:         if ($rule_in_effect eq 'homeserver') {
                   1697:             my $homeserver = &homeserver($uname,$udom);
                   1698:             if ($homeserver ne 'no_host') {
                   1699:                 $offloadto = [$homeserver];
                   1700:             }
                   1701:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1702:             my %domconfig =
                   1703:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1704:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1705:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1706:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1707:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1708:                     }
                   1709:                 }
                   1710:             } else {
1.1178    raeburn  1711:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1712:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1713:                 if (&hostname($remotebalancer) ne '') {
                   1714:                     $offloadto = [$remotebalancer];
                   1715:                 }
                   1716:             }
                   1717:         } elsif (&hostname($rule_in_effect) ne '') {
                   1718:             $offloadto = [$rule_in_effect];
                   1719:         }
                   1720:     }
                   1721:     return $offloadto;
                   1722: }
                   1723: 
1.1127    raeburn  1724: sub internet_dom_servers {
                   1725:     my ($dom) = @_;
                   1726:     my (%uniqservers,%servers);
                   1727:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1728:     my @machinedoms = &machine_domains($primaryserver);
                   1729:     foreach my $mdom (@machinedoms) {
                   1730:         my %currservers = %servers;
                   1731:         my %server = &get_servers($mdom);
                   1732:         %servers = (%currservers,%server);
                   1733:     }
                   1734:     my %by_hostname;
                   1735:     foreach my $id (keys(%servers)) {
                   1736:         push(@{$by_hostname{$servers{$id}}},$id);
                   1737:     }
                   1738:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1739:         if (@{$by_hostname{$hostname}} > 1) {
                   1740:             my $match = 0;
                   1741:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1742:                 if (&host_domain($id) eq $dom) {
                   1743:                     $uniqservers{$id} = $hostname;
                   1744:                     $match = 1;
                   1745:                 }
                   1746:             }
                   1747:             unless ($match) {
                   1748:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1749:             }
                   1750:         } else {
                   1751:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1752:         }
                   1753:     }
                   1754:     return %uniqservers;
                   1755: }
                   1756: 
1.1347    raeburn  1757: sub trusted_domains {
                   1758:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1759:     my ($trusted,$untrusted);
1.1347    raeburn  1760:     if (&domain($calldom) eq '') {
1.1349    raeburn  1761:         return ($trusted,$untrusted);
1.1347    raeburn  1762:     }
1.1395    raeburn  1763:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1764:         return ($trusted,$untrusted);
1.1347    raeburn  1765:     }
                   1766:     my $callprimary = &domain($calldom,'primary');
                   1767:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1768:     if ($intcalldom eq '') {
1.1349    raeburn  1769:         return ($trusted,$untrusted);
1.1347    raeburn  1770:     }
                   1771: 
                   1772:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1773:     unless (defined($cached)) {
                   1774:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1775:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1776:         $trustconfig = $domconfig{'trust'};
                   1777:     }
                   1778:     if (ref($trustconfig)) {
                   1779:         my (%possexc,%possinc,@allexc,@allinc); 
                   1780:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1781:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1782:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1783:             }
                   1784:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1785:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1786:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1787:             }
                   1788:         }
                   1789:         if (keys(%possexc)) {
                   1790:             if (keys(%possinc)) {
                   1791:                 foreach my $key (sort(keys(%possexc))) {
                   1792:                     next if ($key eq $intcalldom);
                   1793:                     unless ($possinc{$key}) {
                   1794:                         push(@allexc,$key);
                   1795:                     }
                   1796:                 }
                   1797:             } else {
                   1798:                 @allexc = sort(keys(%possexc));
                   1799:             }
                   1800:         }
                   1801:         if (keys(%possinc)) {
                   1802:             $possinc{$intcalldom} = 1;
                   1803:             @allinc = sort(keys(%possinc));
                   1804:         }
                   1805:         if ((@allexc > 0) || (@allinc > 0)) {
                   1806:             my %doms_by_intdom;
                   1807:             my %allintdoms = &all_host_intdom();
                   1808:             my %alldoms = &all_host_domain();
                   1809:             foreach my $key (%allintdoms) {
                   1810:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1811:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1812:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1813:                     }
                   1814:                 } else {
                   1815:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1816:                 }
                   1817:             }
                   1818:             foreach my $exc (@allexc) {
                   1819:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1820:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1821:                 }
                   1822:             }
                   1823:             foreach my $inc (@allinc) {
                   1824:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1825:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1826:                 }
                   1827:             }
                   1828:         }
                   1829:     }
1.1349    raeburn  1830:     return ($trusted,$untrusted);
1.1347    raeburn  1831: }
                   1832: 
                   1833: sub will_trust {
                   1834:     my ($cmdtype,$domain,$possdom) = @_;
                   1835:     return 1 if ($domain eq $possdom);
                   1836:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1837:     my $willtrust; 
                   1838:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1839:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1840:             $willtrust = 1;
                   1841:         }
                   1842:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1843:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1844:             $willtrust = 1;
                   1845:         }
                   1846:     } else {
                   1847:         $willtrust = 1;
                   1848:     }
                   1849:     return $willtrust;
                   1850: }
                   1851: 
1.1       albertel 1852: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1853: 
1.599     albertel 1854: my %homecache;
1.1       albertel 1855: sub homeserver {
1.230     stredwic 1856:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1857:     my $index="$uname:$udom";
1.426     albertel 1858: 
1.599     albertel 1859:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1860: 
                   1861:     my %servers = &get_servers($udom,'library');
                   1862:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1863:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1864: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1865: 
                   1866: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1867: 	if ($answer eq 'found') {
                   1868: 	    delete($badServerCache{$tryserver}); 
                   1869: 	    return $homecache{$index}=$tryserver;
                   1870: 	} elsif ($answer eq 'no_host') {
                   1871: 	    $badServerCache{$tryserver}=1;
                   1872: 	}
1.1       albertel 1873:     }    
                   1874:     return 'no_host';
1.70      www      1875: }
                   1876: 
1.1300    raeburn  1877: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1878: 
                   1879: sub idget {
1.1300    raeburn  1880:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1881:     my %returnhash=();
1.1300    raeburn  1882:     my @ids=(); 
                   1883:     if (ref($idsref) eq 'ARRAY') {
                   1884:         @ids = @{$idsref};
                   1885:     } else {
                   1886:         return %returnhash; 
                   1887:     }
                   1888:     if ($namespace eq '') {
                   1889:         $namespace = 'ids';
                   1890:     }
1.70      www      1891:     
1.841     albertel 1892:     my %servers = &get_servers($udom,'library');
                   1893:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1894: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1895: 	if ($namespace eq 'ids') {
                   1896: 	    $idlist=~tr/A-Z/a-z/;
                   1897: 	}
                   1898: 	my $reply;
                   1899: 	if ($namespace eq 'ids') {
                   1900: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1901: 	} else {
                   1902: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1903: 	}
1.841     albertel 1904: 	my @answer=();
                   1905: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1906: 	    @answer=split(/\&/,$reply);
                   1907: 	}                    ;
                   1908: 	my $i;
                   1909: 	for ($i=0;$i<=$#ids;$i++) {
                   1910: 	    if ($answer[$i]) {
1.1299    raeburn  1911: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1912: 	    }
1.841     albertel 1913: 	}
1.1300    raeburn  1914:     }
1.70      www      1915:     return %returnhash;
                   1916: }
                   1917: 
                   1918: # ------------------------------------- Find the IDs behind a list of usernames
                   1919: 
                   1920: sub idrget {
                   1921:     my ($udom,@unames)=@_;
                   1922:     my %returnhash=();
1.800     albertel 1923:     foreach my $uname (@unames) {
                   1924:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1925:     }
1.70      www      1926:     return %returnhash;
                   1927: }
                   1928: 
1.1300    raeburn  1929: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1930: 
                   1931: sub idput {
1.1300    raeburn  1932:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1933:     my %servers=();
1.1300    raeburn  1934:     my %ids=();
                   1935:     my %byid = ();
                   1936:     if (ref($idsref) eq 'HASH') {
                   1937:         %ids=%{$idsref};
                   1938:     }
                   1939:     if ($namespace eq '') {
                   1940:         $namespace = 'ids'; 
                   1941:     }
1.800     albertel 1942:     foreach my $uname (keys(%ids)) {
                   1943: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1944:         if ($uhom eq '') {
                   1945:             $uhom=&homeserver($uname,$udom);
                   1946:         }
1.70      www      1947:         if ($uhom ne 'no_host') {
1.800     albertel 1948:             my $esc_unam=&escape($uname);
1.1300    raeburn  1949:             if ($namespace eq 'ids') {
                   1950:                 my $id=&escape($ids{$uname});
                   1951:                 $id=~tr/A-Z/a-z/;
                   1952:                 my $esc_unam=&escape($uname);
                   1953:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1954:             } else {
1.1300    raeburn  1955:                 my @currids = split(/,/,$ids{$uname});
                   1956:                 foreach my $id (@currids) {
                   1957:                     $byid{$uhom}{$id} .= $uname.',';
                   1958:                 }
                   1959:             }
                   1960:         }
                   1961:     }
                   1962:     if ($namespace eq 'clickers') {
                   1963:         foreach my $server (keys(%byid)) {
                   1964:             if (ref($byid{$server}) eq 'HASH') {
                   1965:                 foreach my $id (keys(%{$byid{$server}})) {
                   1966:                     $byid{$server} =~ s/,$//;
                   1967:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1968:                 }
1.70      www      1969:             }
                   1970:         }
1.191     harris41 1971:     }
1.800     albertel 1972:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1973:         $servers{$server} =~ s/\&$//;
                   1974:         if ($namespace eq 'ids') {     
                   1975:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1976:         } else {
                   1977:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1978:         }
1.191     harris41 1979:     }
1.344     www      1980: }
                   1981: 
1.1300    raeburn  1982: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1983: 
                   1984: sub iddel {
1.1300    raeburn  1985:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1986:     my %result=();
1.1300    raeburn  1987:     my %ids=();
                   1988:     my %byid = ();
                   1989:     if (ref($idshashref) eq 'HASH') {
                   1990:         %ids=%{$idshashref};
                   1991:     } else {
1.1231    raeburn  1992:         return %result;
                   1993:     }
1.1300    raeburn  1994:     if ($namespace eq '') {
                   1995:         $namespace = 'ids';
                   1996:     }
1.1231    raeburn  1997:     my %servers=();
1.1300    raeburn  1998:     while (my ($id,$unamestr) = each(%ids)) {
                   1999:         if ($namespace eq 'ids') {
                   2000:             my $uhom = $uhome;
                   2001:             if ($uhom eq '') { 
                   2002:                 $uhom=&homeserver($unamestr,$udom);
                   2003:             }
                   2004:             if ($uhom ne 'no_host') {
                   2005:                 $servers{$uhom}.='&'.&escape($id);
                   2006:             }
                   2007:          } else {
                   2008:             my @curritems = split(/,/,$ids{$id});
                   2009:             foreach my $uname (@curritems) {
                   2010:                 my $uhom = $uhome;
                   2011:                 if ($uhom eq '') {
                   2012:                     $uhom=&homeserver($uname,$udom);
                   2013:                 }
                   2014:                 if ($uhom ne 'no_host') { 
                   2015:                     $byid{$uhom}{$id} .= $uname.',';
                   2016:                 }
                   2017:             }
1.1231    raeburn  2018:         }
1.1300    raeburn  2019:     }
                   2020:     if ($namespace eq 'clickers') {
                   2021:         foreach my $server (keys(%byid)) {
                   2022:             if (ref($byid{$server}) eq 'HASH') {
                   2023:                 foreach my $id (keys(%{$byid{$server}})) {
                   2024:                     $byid{$server}{$id} =~ s/,$//;
                   2025:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2026:                 }
1.1231    raeburn  2027:             }
                   2028:         }
                   2029:     }
                   2030:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2031:         $servers{$server} =~ s/\&$//;
                   2032:         if ($namespace eq 'ids') {
                   2033:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2034:         } elsif ($namespace eq 'clickers') {
                   2035:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2036:         }
1.1231    raeburn  2037:     }
                   2038:     return %result;
                   2039: }
                   2040: 
1.1300    raeburn  2041: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2042: 
                   2043: sub updateclickers {
                   2044:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2045:     my %clickers;
                   2046:     if (ref($idshashref) eq 'HASH') {
                   2047:         %clickers=%{$idshashref};
                   2048:     } else {
                   2049:         return;
                   2050:     }
                   2051:     my $items='';
                   2052:     foreach my $item (keys(%clickers)) {
                   2053:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2054:     }
                   2055:     $items=~s/\&$//;
                   2056:     my $request = "updateclickers:$udom:$action:$items";
                   2057:     if ($critical) {
                   2058:         return &critical($request,$uhome);
                   2059:     } else {
                   2060:         return &reply($request,$uhome);
                   2061:     }
                   2062: }
                   2063: 
1.1023    raeburn  2064: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2065: sub dump_dom {
1.1165    droeschl 2066:     my ($namespace, $udom, $regexp) = @_;
                   2067: 
                   2068:     $udom ||= $env{'user.domain'};
                   2069: 
                   2070:     return () unless $udom;
                   2071: 
                   2072:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2073: }
                   2074: 
1.1023    raeburn  2075: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2076: 
                   2077: sub get_dom {
1.860     raeburn  2078:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2079:     return if ($udom eq 'public');
1.806     raeburn  2080:     my $items='';
                   2081:     foreach my $item (@$storearr) {
                   2082:         $items.=&escape($item).'&';
                   2083:     }
                   2084:     $items=~s/\&$//;
1.860     raeburn  2085:     if (!$udom) {
                   2086:         $udom=$env{'user.domain'};
1.1267    raeburn  2087:         return if ($udom eq 'public');
1.860     raeburn  2088:         if (defined(&domain($udom,'primary'))) {
                   2089:             $uhome=&domain($udom,'primary');
                   2090:         } else {
1.874     albertel 2091:             undef($uhome);
1.860     raeburn  2092:         }
                   2093:     } else {
                   2094:         if (!$uhome) {
                   2095:             if (defined(&domain($udom,'primary'))) {
                   2096:                 $uhome=&domain($udom,'primary');
                   2097:             }
                   2098:         }
                   2099:     }
                   2100:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2101:         my $rep;
                   2102:         if ($namespace =~ /^enc/) {
                   2103:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2104:         } else {
                   2105:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2106:         }
1.866     raeburn  2107:         my %returnhash;
1.875     albertel 2108:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2109:             return %returnhash;
                   2110:         }
1.806     raeburn  2111:         my @pairs=split(/\&/,$rep);
                   2112:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2113:             return @pairs;
                   2114:         }
                   2115:         my $i=0;
                   2116:         foreach my $item (@$storearr) {
                   2117:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2118:             $i++;
                   2119:         }
                   2120:         return %returnhash;
                   2121:     } else {
1.880     banghart 2122:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2123:     }
                   2124: }
                   2125: 
                   2126: # -------------------------------------------- put items in domain db files 
                   2127: 
                   2128: sub put_dom {
1.860     raeburn  2129:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2130:     if (!$udom) {
                   2131:         $udom=$env{'user.domain'};
                   2132:         if (defined(&domain($udom,'primary'))) {
                   2133:             $uhome=&domain($udom,'primary');
                   2134:         } else {
1.874     albertel 2135:             undef($uhome);
1.860     raeburn  2136:         }
                   2137:     } else {
                   2138:         if (!$uhome) {
                   2139:             if (defined(&domain($udom,'primary'))) {
                   2140:                 $uhome=&domain($udom,'primary');
                   2141:             }
                   2142:         }
                   2143:     } 
                   2144:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2145:         my $items='';
                   2146:         foreach my $item (keys(%$storehash)) {
                   2147:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2148:         }
                   2149:         $items=~s/\&$//;
1.1344    raeburn  2150:         if ($namespace =~ /^enc/) {
                   2151:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2152:         } else {
                   2153:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2154:         }
1.806     raeburn  2155:     } else {
1.860     raeburn  2156:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2157:     }
                   2158: }
                   2159: 
1.1023    raeburn  2160: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2161: sub newput_dom {
1.1023    raeburn  2162:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2163:     my $result;
                   2164:     if (!$udom) {
                   2165:         $udom=$env{'user.domain'};
                   2166:     }
1.1023    raeburn  2167:     if ($udom) {
                   2168:         my $uname = &get_domainconfiguser($udom);
                   2169:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2170:     }
                   2171:     return $result;
                   2172: }
                   2173: 
1.1023    raeburn  2174: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2175: sub del_dom {
1.1023    raeburn  2176:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2177:     if (ref($storearr) eq 'ARRAY') {
                   2178:         if (!$udom) {
                   2179:             $udom=$env{'user.domain'};
                   2180:         }
1.1023    raeburn  2181:         if ($udom) {
                   2182:             my $uname = &get_domainconfiguser($udom); 
                   2183:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2184:         }
                   2185:     }
                   2186: }
                   2187: 
1.1023    raeburn  2188: # ----------------------------------construct domainconfig user for a domain 
                   2189: sub get_domainconfiguser {
                   2190:     my ($udom) = @_;
                   2191:     return $udom.'-domainconfig';
                   2192: }
                   2193: 
1.837     raeburn  2194: sub retrieve_inst_usertypes {
                   2195:     my ($udom) = @_;
                   2196:     my (%returnhash,@order);
1.989     raeburn  2197:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2198:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2199:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2200:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2201:     } else {
                   2202:         if (defined(&domain($udom,'primary'))) {
                   2203:             my $uhome=&domain($udom,'primary');
                   2204:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2205:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2206:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2207:                 return (\%returnhash,\@order);
                   2208:             }
                   2209:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2210:             my @pairs=split(/\&/,$hashitems);
                   2211:             foreach my $item (@pairs) {
                   2212:                 my ($key,$value)=split(/=/,$item,2);
                   2213:                 $key = &unescape($key);
                   2214:                 next if ($key =~ /^error: 2 /);
                   2215:                 $returnhash{$key}=&thaw_unescape($value);
                   2216:             }
                   2217:             my @esc_order = split(/\&/,$orderitems);
                   2218:             foreach my $item (@esc_order) {
                   2219:                 push(@order,&unescape($item));
                   2220:             }
                   2221:         } else {
1.1256    raeburn  2222:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2223:         }
1.1256    raeburn  2224:         return (\%returnhash,\@order);
1.837     raeburn  2225:     }
                   2226: }
                   2227: 
1.868     raeburn  2228: sub is_domainimage {
                   2229:     my ($url) = @_;
1.1306    raeburn  2230:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2231:         if (&domain($1) ne '') {
                   2232:             return '1';
                   2233:         }
                   2234:     }
                   2235:     return;
                   2236: }
                   2237: 
1.899     raeburn  2238: sub inst_directory_query {
                   2239:     my ($srch) = @_;
                   2240:     my $udom = $srch->{'srchdomain'};
                   2241:     my %results;
                   2242:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2243:     my $outcome;
1.899     raeburn  2244:     if ($homeserver ne '') {
1.1357    raeburn  2245:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2246:             if ($srch->{'srchby'} eq 'email') {
                   2247:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2248:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2249:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2250:                     (($major == 2) && ($minor < 12))) {
                   2251:                     return;
                   2252:                 }
                   2253:             }
                   2254:         }
1.904     albertel 2255: 	my $queryid=&reply("querysend:instdirsearch:".
                   2256: 			   &escape($srch->{'srchby'}).':'.
                   2257: 			   &escape($srch->{'srchterm'}).':'.
                   2258: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2259: 	my $host=&hostname($homeserver);
                   2260: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2261: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2262: 	    return;
                   2263: 	}
                   2264: 	my $response = &get_query_reply($queryid);
                   2265: 	my $maxtries = 5;
                   2266: 	my $tries = 1;
                   2267: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2268: 	    $response = &get_query_reply($queryid);
                   2269: 	    $tries ++;
                   2270: 	}
                   2271: 
                   2272:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2273:             if ($response eq 'unavailable') {
                   2274:                 $outcome = $response;
                   2275:             } else {
                   2276:                 $outcome = 'ok';
                   2277:                 my @matches = split(/\n/,$response);
                   2278:                 foreach my $match (@matches) {
                   2279:                     my ($key,$value) = split(/=/,$match);
                   2280:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2281:                 }
1.899     raeburn  2282:             }
                   2283:         }
                   2284:     }
1.909     raeburn  2285:     return ($outcome,%results);
1.899     raeburn  2286: }
                   2287: 
                   2288: sub usersearch {
                   2289:     my ($srch) = @_;
                   2290:     my $dom = $srch->{'srchdomain'};
                   2291:     my %results;
                   2292:     my %libserv = &all_library();
                   2293:     my $query = 'usersearch';
                   2294:     foreach my $tryserver (keys(%libserv)) {
                   2295:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2296:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2297:                 if ($srch->{'srchby'} eq 'email') {
                   2298:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2299:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2300:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2301:                              (($major == 2) && ($minor < 12)));
                   2302:                 }
                   2303:             }
1.899     raeburn  2304:             my $host=&hostname($tryserver);
                   2305:             my $queryid=
1.911     raeburn  2306:                 &reply("querysend:".&escape($query).':'.
                   2307:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2308:                        &escape($srch->{'srchtype'}).':'.
                   2309:                        &escape($srch->{'srchterm'}),$tryserver);
                   2310:             if ($queryid !~/^\Q$host\E\_/) {
                   2311:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2312:                 next;
1.899     raeburn  2313:             }
                   2314:             my $reply = &get_query_reply($queryid);
                   2315:             my $maxtries = 1;
                   2316:             my $tries = 1;
                   2317:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2318:                 $reply = &get_query_reply($queryid);
                   2319:                 $tries ++;
                   2320:             }
                   2321:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2322:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2323:             } else {
1.911     raeburn  2324:                 my @matches;
                   2325:                 if ($reply =~ /\n/) {
                   2326:                     @matches = split(/\n/,$reply);
                   2327:                 } else {
                   2328:                     @matches = split(/\&/,$reply);
                   2329:                 }
1.899     raeburn  2330:                 foreach my $match (@matches) {
                   2331:                     my ($uname,$udom,%userhash);
1.911     raeburn  2332:                     foreach my $entry (split(/:/,$match)) {
                   2333:                         my ($key,$value) =
                   2334:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2335:                         $userhash{$key} = $value;
                   2336:                         if ($key eq 'username') {
                   2337:                             $uname = $value;
                   2338:                         } elsif ($key eq 'domain') {
                   2339:                             $udom = $value;
1.911     raeburn  2340:                         }
1.899     raeburn  2341:                     }
                   2342:                     $results{$uname.':'.$udom} = \%userhash;
                   2343:                 }
                   2344:             }
                   2345:         }
                   2346:     }
                   2347:     return %results;
                   2348: }
                   2349: 
1.912     raeburn  2350: sub get_instuser {
                   2351:     my ($udom,$uname,$id) = @_;
                   2352:     my $homeserver = &domain($udom,'primary');
                   2353:     my ($outcome,%results);
                   2354:     if ($homeserver ne '') {
                   2355:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2356:                            &escape($id).':'.&escape($udom),$homeserver);
                   2357:         my $host=&hostname($homeserver);
                   2358:         if ($queryid !~/^\Q$host\E\_/) {
                   2359:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2360:             return;
                   2361:         }
                   2362:         my $response = &get_query_reply($queryid);
                   2363:         my $maxtries = 5;
                   2364:         my $tries = 1;
                   2365:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2366:             $response = &get_query_reply($queryid);
                   2367:             $tries ++;
                   2368:         }
                   2369:         if (!&error($response) && $response ne 'refused') {
                   2370:             if ($response eq 'unavailable') {
                   2371:                 $outcome = $response;
                   2372:             } else {
                   2373:                 $outcome = 'ok';
                   2374:                 my @matches = split(/\n/,$response);
                   2375:                 foreach my $match (@matches) {
                   2376:                     my ($key,$value) = split(/=/,$match);
                   2377:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2378:                 }
                   2379:             }
                   2380:         }
                   2381:     }
                   2382:     my %userinfo;
                   2383:     if (ref($results{$uname}) eq 'HASH') {
                   2384:         %userinfo = %{$results{$uname}};
                   2385:     } 
                   2386:     return ($outcome,%userinfo);
                   2387: }
                   2388: 
1.1290    raeburn  2389: sub get_multiple_instusers {
                   2390:     my ($udom,$users,$caller) = @_;
                   2391:     my ($outcome,$results);
                   2392:     if (ref($users) eq 'HASH') {
                   2393:         my $count = keys(%{$users}); 
                   2394:         my $requested = &freeze_escape($users);
                   2395:         my $homeserver = &domain($udom,'primary');
                   2396:         if ($homeserver ne '') {
                   2397:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2398:             my $host=&hostname($homeserver);
                   2399:             if ($queryid !~/^\Q$host\E\_/) {
                   2400:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2401:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2402:                 return ($outcome,$results);
                   2403:             }
                   2404:             my $response = &get_query_reply($queryid);
                   2405:             my $maxtries = 5;
                   2406:             if ($count > 100) {
                   2407:                 $maxtries = 1+int($count/20);
                   2408:             }
                   2409:             my $tries = 1;
                   2410:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2411:                 $response = &get_query_reply($queryid);
                   2412:                 $tries ++;
                   2413:             }
                   2414:             if ($response eq '') {
                   2415:                 $results = {};
                   2416:                 foreach my $key (keys(%{$users})) {
                   2417:                     my ($uname,$id);
                   2418:                     if ($caller eq 'id') {
                   2419:                         $id = $key;
                   2420:                     } else {
                   2421:                         $uname = $key;
                   2422:                     }
                   2423:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2424:                     $outcome = $resp;
1.1290    raeburn  2425:                     if ($resp eq 'ok') {
                   2426:                         %{$results} = (%{$results}, %info);
                   2427:                     } else {
                   2428:                         last;
                   2429:                     }
                   2430:                 }
                   2431:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2432:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2433:                     $outcome = $response;
                   2434:                 } else {
1.1291    raeburn  2435:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2436:                     if ($outcome eq 'ok') {
                   2437:                         $results = &thaw_unescape($userdata); 
                   2438:                     }
                   2439:                 }
                   2440:             }
                   2441:         }
                   2442:     }
                   2443:     return ($outcome,$results);
                   2444: }
                   2445: 
1.912     raeburn  2446: sub inst_rulecheck {
1.923     raeburn  2447:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2448:     my %returnhash;
                   2449:     if ($udom ne '') {
                   2450:         if (ref($rules) eq 'ARRAY') {
                   2451:             @{$rules} = map {&escape($_);} (@{$rules});
                   2452:             my $rulestr = join(':',@{$rules});
                   2453:             my $homeserver=&domain($udom,'primary');
                   2454:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2455:                 my $response;
                   2456:                 if ($item eq 'username') {                
                   2457:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2458:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2459:                                               $homeserver));
1.923     raeburn  2460:                 } elsif ($item eq 'id') {
                   2461:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2462:                                               ':'.&escape($id).':'.$rulestr,
                   2463:                                               $homeserver));
1.945     raeburn  2464:                 } elsif ($item eq 'selfcreate') {
                   2465:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2466:                                                &escape($udom).':'.&escape($uname).
                   2467:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2468:                 }
1.912     raeburn  2469:                 if ($response ne 'refused') {
                   2470:                     my @pairs=split(/\&/,$response);
                   2471:                     foreach my $item (@pairs) {
                   2472:                         my ($key,$value)=split(/=/,$item,2);
                   2473:                         $key = &unescape($key);
                   2474:                         next if ($key =~ /^error: 2 /);
                   2475:                         $returnhash{$key}=&thaw_unescape($value);
                   2476:                     }
                   2477:                 }
                   2478:             }
                   2479:         }
                   2480:     }
                   2481:     return %returnhash;
                   2482: }
                   2483: 
                   2484: sub inst_userrules {
1.923     raeburn  2485:     my ($udom,$check) = @_;
1.912     raeburn  2486:     my (%ruleshash,@ruleorder);
                   2487:     if ($udom ne '') {
                   2488:         my $homeserver=&domain($udom,'primary');
                   2489:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2490:             my $response;
                   2491:             if ($check eq 'id') {
                   2492:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2493:                                  $homeserver);
1.943     raeburn  2494:             } elsif ($check eq 'email') {
                   2495:                 $response=&reply('instemailrules:'.&escape($udom),
                   2496:                                  $homeserver);
1.923     raeburn  2497:             } else {
                   2498:                 $response=&reply('instuserrules:'.&escape($udom),
                   2499:                                  $homeserver);
                   2500:             }
1.912     raeburn  2501:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2502:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2503:                 ($response ne 'no_such_host')) {
                   2504:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2505:                 my @pairs=split(/\&/,$hashitems);
                   2506:                 foreach my $item (@pairs) {
                   2507:                     my ($key,$value)=split(/=/,$item,2);
                   2508:                     $key = &unescape($key);
                   2509:                     next if ($key =~ /^error: 2 /);
                   2510:                     $ruleshash{$key}=&thaw_unescape($value);
                   2511:                 }
                   2512:                 my @esc_order = split(/\&/,$orderitems);
                   2513:                 foreach my $item (@esc_order) {
                   2514:                     push(@ruleorder,&unescape($item));
                   2515:                 }
                   2516:             }
                   2517:         }
                   2518:     }
                   2519:     return (\%ruleshash,\@ruleorder);
                   2520: }
                   2521: 
1.976     raeburn  2522: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2523: 
                   2524: sub get_domain_defaults {
1.1240    raeburn  2525:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2526:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2527:     my $cachetime = 60*60*24;
1.1240    raeburn  2528:     unless ($ignore_cache) {
                   2529:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2530:         if (defined($cached)) {
                   2531:             if (ref($result) eq 'HASH') {
                   2532:                 return %{$result};
                   2533:             }
1.943     raeburn  2534:         }
                   2535:     }
                   2536:     my %domdefaults;
                   2537:     my %domconfig =
1.989     raeburn  2538:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2539:                                   'requestcourses','inststatus',
1.1183    raeburn  2540:                                   'coursedefaults','usersessions',
1.1258    raeburn  2541:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2542:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2543:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2544:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2545:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2546:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2547:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2548:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2549:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2550:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2551:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2552:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2553:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2554:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2555:     } else {
                   2556:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2557:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2558:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2559:     }
1.976     raeburn  2560:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2561:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2562:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2563:         } else {
                   2564:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2565:         }
1.1177    raeburn  2566:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2567:         foreach my $item (@usertools) {
                   2568:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2569:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2570:             }
                   2571:         }
1.1229    raeburn  2572:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2573:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2574:         }
1.976     raeburn  2575:     }
1.985     raeburn  2576:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2577:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2578:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2579:         }
                   2580:     }
1.1183    raeburn  2581:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2582:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2583:     }
1.989     raeburn  2584:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2585:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2586:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2587:         }
                   2588:     }
1.1047    raeburn  2589:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2590:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2591:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2592:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2593:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2594:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2595:         }
1.1254    raeburn  2596:         foreach my $type (@coursetypes) {
                   2597:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2598:                 unless ($type eq 'community') {
                   2599:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2600:                 }
                   2601:             }
                   2602:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2603:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2604:             }
1.1277    raeburn  2605:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2606:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2607:                     $domdefaults{$type.'postsubtimeout'} = 
                   2608:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2609:                 }
                   2610:             }
1.1230    raeburn  2611:         }
1.1286    raeburn  2612:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2613:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2614:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2615:                 if (@clonecodes) {
                   2616:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2617:                 }
                   2618:             }
                   2619:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2620:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2621:         }
1.1356    raeburn  2622:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2623:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2624:         } 
1.1047    raeburn  2625:     }
1.1073    raeburn  2626:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2627:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2628:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2629:         }
                   2630:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2631:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2632:         }
1.1279    raeburn  2633:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2634:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2635:         }
1.1073    raeburn  2636:     }
1.1254    raeburn  2637:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2638:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2639:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2640:                             'approval','limit');
                   2641:             foreach my $type (@coursetypes) {
                   2642:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2643:                     my @mgrdc = ();
                   2644:                     foreach my $item (@settings) {
                   2645:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2646:                             push(@mgrdc,$item);
                   2647:                         }
                   2648:                     }
                   2649:                     if (@mgrdc) {
                   2650:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2651:                     }
                   2652:                 }
                   2653:             }
                   2654:         }
                   2655:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2656:             foreach my $type (@coursetypes) {
                   2657:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2658:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2659:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2660:                     }
                   2661:                 }
                   2662:             }
                   2663:         }
                   2664:     }
1.1258    raeburn  2665:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2666:         $domdefaults{'catauth'} = 'std';
                   2667:         $domdefaults{'catunauth'} = 'std';
                   2668:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2669:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2670:         }
                   2671:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2672:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2673:         }
                   2674:     }
1.1315    raeburn  2675:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2676:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2677:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2678:         }
1.1338    raeburn  2679:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2680:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2681:         }
                   2682:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2683:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2684:         }
                   2685:     }
1.1320    raeburn  2686:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2687:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2688:         foreach my $prefix (@prefixes) {
                   2689:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2690:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2691:             }
                   2692:         }
                   2693:     }
1.1314    raeburn  2694:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2695:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2696:     }
1.1332    raeburn  2697:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2698:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2699:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2700:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2701:         }
                   2702:     }
1.1219    raeburn  2703:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2704:     return %domdefaults;
                   2705: }
                   2706: 
1.1311    raeburn  2707: sub course_portal_url {
                   2708:     my ($cnum,$cdom) = @_;
                   2709:     my $chome = &homeserver($cnum,$cdom);
                   2710:     my $hostname = &hostname($chome);
                   2711:     my $protocol = $protocol{$chome};
                   2712:     $protocol = 'http' if ($protocol ne 'https');
                   2713:     my %domdefaults = &get_domain_defaults($cdom);
                   2714:     my $firsturl;
                   2715:     if ($domdefaults{'portal_def'}) {
                   2716:         $firsturl = $domdefaults{'portal_def'};
                   2717:     } else {
                   2718:         $firsturl = $protocol.'://'.$hostname;
                   2719:     }
                   2720:     return $firsturl;
                   2721: }
                   2722: 
1.344     www      2723: # --------------------------------------------------- Assign a key to a student
                   2724: 
                   2725: sub assign_access_key {
1.364     www      2726: #
                   2727: # a valid key looks like uname:udom#comments
                   2728: # comments are being appended
                   2729: #
1.498     www      2730:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2731:     $kdom=
1.620     albertel 2732:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2733:     $knum=
1.620     albertel 2734:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2735:     $cdom=
1.620     albertel 2736:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2737:     $cnum=
1.620     albertel 2738:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2739:     $udom=$env{'user.name'} unless (defined($udom));
                   2740:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2741:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2742:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2743:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2744:                                                   # assigned to this person
                   2745:                                                   # - this should not happen,
1.345     www      2746:                                                   # unless something went wrong
                   2747:                                                   # the first time around
                   2748: # ready to assign
1.364     www      2749:         $logentry=$1.'; '.$logentry;
1.496     www      2750:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2751:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2752: # key now belongs to user
1.346     www      2753: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2754:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2755:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2756:                 return 'ok';
                   2757:             } else {
                   2758:                 return 
                   2759:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2760: 	    }
                   2761:         } else {
                   2762:             return 'error: Could not assign key, try again later.';
                   2763:         }
1.364     www      2764:     } elsif (!$existing{$ckey}) {
1.345     www      2765: # the key does not exist
                   2766: 	return 'error: The key does not exist';
                   2767:     } else {
                   2768: # the key is somebody else's
                   2769: 	return 'error: The key is already in use';
                   2770:     }
1.344     www      2771: }
                   2772: 
1.364     www      2773: # ------------------------------------------ put an additional comment on a key
                   2774: 
                   2775: sub comment_access_key {
                   2776: #
                   2777: # a valid key looks like uname:udom#comments
                   2778: # comments are being appended
                   2779: #
                   2780:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2781:     $cdom=
1.620     albertel 2782:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2783:     $cnum=
1.620     albertel 2784:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2785:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2786:     if ($existing{$ckey}) {
                   2787:         $existing{$ckey}.='; '.$logentry;
                   2788: # ready to assign
1.367     www      2789:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2790:                                                  $cdom,$cnum) eq 'ok') {
                   2791: 	    return 'ok';
                   2792:         } else {
                   2793: 	    return 'error: Count not store comment.';
                   2794:         }
                   2795:     } else {
                   2796: # the key does not exist
                   2797: 	return 'error: The key does not exist';
                   2798:     }
                   2799: }
                   2800: 
1.344     www      2801: # ------------------------------------------------------ Generate a set of keys
                   2802: 
                   2803: sub generate_access_keys {
1.364     www      2804:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2805:     $cdom=
1.620     albertel 2806:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2807:     $cnum=
1.620     albertel 2808:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2809:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2810:     unless (($cdom) && ($cnum)) { return 0; }
                   2811:     if ($number>10000) { return 0; }
                   2812:     sleep(2); # make sure don't get same seed twice
                   2813:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2814:     my $total=0;
                   2815:     for (my $i=1;$i<=$number;$i++) {
                   2816:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2817:                   sprintf("%lx",int(100000*rand)).'-'.
                   2818:                   sprintf("%lx",int(100000*rand));
                   2819:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2820:        $newkey=~s/0/h/g; # and also 0 and O
                   2821:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2822:        if ($existing{$newkey}) {
                   2823:            $i--;
                   2824:        } else {
1.364     www      2825: 	  if (&put('accesskeys',
                   2826:               { $newkey => '# generated '.localtime().
1.620     albertel 2827:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2828:                            '; '.$logentry },
                   2829: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2830:               $total++;
                   2831: 	  }
                   2832:        }
                   2833:     }
1.620     albertel 2834:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2835:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2836:     return $total;
                   2837: }
                   2838: 
                   2839: # ------------------------------------------------------- Validate an accesskey
                   2840: 
                   2841: sub validate_access_key {
                   2842:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2843:     $cdom=
1.620     albertel 2844:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2845:     $cnum=
1.620     albertel 2846:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2847:     $udom=$env{'user.domain'} unless (defined($udom));
                   2848:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2849:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2850:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2851: }
                   2852: 
                   2853: # ------------------------------------- Find the section of student in a course
1.652     albertel 2854: sub devalidate_getsection_cache {
                   2855:     my ($udom,$unam,$courseid)=@_;
                   2856:     my $hashid="$udom:$unam:$courseid";
                   2857:     &devalidate_cache_new('getsection',$hashid);
                   2858: }
1.298     matthew  2859: 
1.815     albertel 2860: sub courseid_to_courseurl {
                   2861:     my ($courseid) = @_;
                   2862:     #already url style courseid
                   2863:     return $courseid if ($courseid =~ m{^/});
                   2864: 
                   2865:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2866: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2867: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2868: 	return "/$cdom/$cnum";
                   2869:     }
                   2870: 
                   2871:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2872:     if (exists($courseinfo{'num'})) {
                   2873: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2874:     }
                   2875: 
                   2876:     return undef;
                   2877: }
                   2878: 
1.298     matthew  2879: sub getsection {
                   2880:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2881:     my $cachetime=1800;
1.551     albertel 2882: 
                   2883:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2884:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2885:     if (defined($cached)) { return $result; }
                   2886: 
1.298     matthew  2887:     my %Pending; 
                   2888:     my %Expired;
                   2889:     #
                   2890:     # Each role can either have not started yet (pending), be active, 
                   2891:     #    or have expired.
                   2892:     #
                   2893:     # If there is an active role, we are done.
                   2894:     #
                   2895:     # If there is more than one role which has not started yet, 
                   2896:     #     choose the one which will start sooner
                   2897:     # If there is one role which has not started yet, return it.
                   2898:     #
                   2899:     # If there is more than one expired role, choose the one which ended last.
                   2900:     # If there is a role which has expired, return it.
                   2901:     #
1.815     albertel 2902:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2903:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2904:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2905:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2906:         my $section=$1;
                   2907:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2908:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2909:         my $now=time;
1.548     albertel 2910:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2911:             $Expired{$end}=$section;
                   2912:             next;
                   2913:         }
1.548     albertel 2914:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2915:             $Pending{$start}=$section;
                   2916:             next;
                   2917:         }
1.599     albertel 2918:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2919:     }
                   2920:     #
                   2921:     # Presumedly there will be few matching roles from the above
                   2922:     # loop and the sorting time will be negligible.
                   2923:     if (scalar(keys(%Pending))) {
                   2924:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2925:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2926:     } 
                   2927:     if (scalar(keys(%Expired))) {
                   2928:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2929:         my $time = pop(@sorted);
1.599     albertel 2930:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2931:     }
1.599     albertel 2932:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2933: }
1.70      www      2934: 
1.599     albertel 2935: sub save_cache {
                   2936:     &purge_remembered();
1.722     albertel 2937:     #&Apache::loncommon::validate_page();
1.620     albertel 2938:     undef(%env);
1.780     albertel 2939:     undef($env_loaded);
1.599     albertel 2940: }
1.452     albertel 2941: 
1.599     albertel 2942: my $to_remember=-1;
                   2943: my %remembered;
                   2944: my %accessed;
                   2945: my $kicks=0;
                   2946: my $hits=0;
1.849     albertel 2947: sub make_key {
                   2948:     my ($name,$id) = @_;
1.872     albertel 2949:     if (length($id) > 65 
                   2950: 	&& length(&escape($id)) > 200) {
                   2951: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2952:     }
1.849     albertel 2953:     return &escape($name.':'.$id);
                   2954: }
                   2955: 
1.599     albertel 2956: sub devalidate_cache_new {
                   2957:     my ($name,$id,$debug) = @_;
                   2958:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2959:     my $remembered_id=$name.':'.$id;
1.849     albertel 2960:     $id=&make_key($name,$id);
1.599     albertel 2961:     $memcache->delete($id);
1.1319    damieng  2962:     delete($remembered{$remembered_id});
                   2963:     delete($accessed{$remembered_id});
1.599     albertel 2964: }
                   2965: 
                   2966: sub is_cached_new {
                   2967:     my ($name,$id,$debug) = @_;
1.1319    damieng  2968:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2969:     if (exists($remembered{$remembered_id})) {
                   2970: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2971: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2972: 	$hits++;
1.1319    damieng  2973: 	return ($remembered{$remembered_id},1);
1.599     albertel 2974:     }
1.1319    damieng  2975:     $id=&make_key($name,$id);
1.599     albertel 2976:     my $value = $memcache->get($id);
                   2977:     if (!(defined($value))) {
                   2978: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2979: 	return (undef,undef);
1.416     albertel 2980:     }
1.599     albertel 2981:     if ($value eq '__undef__') {
                   2982: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2983: 	$value=undef;
                   2984:     }
1.1319    damieng  2985:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2986:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2987:     return ($value,1);
                   2988: }
                   2989: 
                   2990: sub do_cache_new {
                   2991:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2992:     my $remembered_id=$name.':'.$id;
1.849     albertel 2993:     $id=&make_key($name,$id);
1.599     albertel 2994:     my $setvalue=$value;
                   2995:     if (!defined($setvalue)) {
                   2996: 	$setvalue='__undef__';
                   2997:     }
1.623     albertel 2998:     if (!defined($time) ) {
                   2999: 	$time=600;
                   3000:     }
1.599     albertel 3001:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3002:     my $result = $memcache->set($id,$setvalue,$time);
                   3003:     if (! $result) {
1.872     albertel 3004: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3005: 	$memcache->disconnect_all();
1.872     albertel 3006:     }
1.600     albertel 3007:     # need to make a copy of $value
1.1319    damieng  3008:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3009:     return $value;
                   3010: }
                   3011: 
                   3012: sub make_room {
1.1319    damieng  3013:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3014: 
1.1319    damieng  3015:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3016:                                     : $value;
1.599     albertel 3017:     if ($to_remember<0) { return; }
1.1319    damieng  3018:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3019:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3020:     my $to_kick;
                   3021:     my $max_time=0;
                   3022:     foreach my $other (keys(%accessed)) {
                   3023: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3024: 	    $to_kick=$other;
                   3025: 	    $max_time=&tv_interval($accessed{$other});
                   3026: 	}
                   3027:     }
                   3028:     delete($remembered{$to_kick});
                   3029:     delete($accessed{$to_kick});
                   3030:     $kicks++;
                   3031:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3032:     return;
                   3033: }
                   3034: 
1.599     albertel 3035: sub purge_remembered {
1.604     albertel 3036:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3037:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3038:     undef(%remembered);
                   3039:     undef(%accessed);
1.428     albertel 3040: }
1.70      www      3041: # ------------------------------------- Read an entry from a user's environment
                   3042: 
                   3043: sub userenvironment {
                   3044:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3045:     my $items;
                   3046:     foreach my $item (@what) {
                   3047:         $items.=&escape($item).'&';
                   3048:     }
                   3049:     $items=~s/\&$//;
1.70      www      3050:     my %returnhash=();
1.1009    raeburn  3051:     my $uhome = &homeserver($unam,$udom);
                   3052:     unless ($uhome eq 'no_host') {
                   3053:         my @answer=split(/\&/, 
                   3054:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3055:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3056:             return %returnhash;
                   3057:         }
1.1009    raeburn  3058:         my $i;
                   3059:         for ($i=0;$i<=$#what;$i++) {
                   3060: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3061:         }
1.70      www      3062:     }
                   3063:     return %returnhash;
1.1       albertel 3064: }
                   3065: 
1.617     albertel 3066: # ---------------------------------------------------------- Get a studentphoto
                   3067: sub studentphoto {
                   3068:     my ($udom,$unam,$ext) = @_;
                   3069:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3070:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3071:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3072:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3073:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3074:             } else {
                   3075:                 my ($result,$perm_reqd)=
1.707     albertel 3076: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3077:                 if ($result eq 'ok') {
                   3078:                     if (!($perm_reqd eq 'yes')) {
                   3079:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3080:                     }
                   3081:                 }
                   3082:             }
                   3083:         }
                   3084:     } else {
                   3085:         my ($result,$perm_reqd) = 
1.707     albertel 3086: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3087:         if ($result eq 'ok') {
                   3088:             if (!($perm_reqd eq 'yes')) {
                   3089:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3090:             }
                   3091:         }
                   3092:     }
                   3093:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3094: }
                   3095: 
                   3096: sub retrievestudentphoto {
                   3097:     my ($udom,$unam,$ext,$type) = @_;
                   3098:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3099:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3100:     if ($ret eq 'ok') {
                   3101:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3102:         if ($type eq 'thumbnail') {
                   3103:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3104:         }
                   3105:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3106:         return $tokenurl;
                   3107:     } else {
                   3108:         if ($type eq 'thumbnail') {
                   3109:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3110:         } else { 
                   3111:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3112:         }
1.617     albertel 3113:     }
                   3114: }
                   3115: 
1.263     www      3116: # -------------------------------------------------------------------- New chat
                   3117: 
                   3118: sub chatsend {
1.724     raeburn  3119:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3120:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3121:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3122:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3123:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3124: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3125: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3126: }
                   3127: 
                   3128: # ------------------------------------------ Find current version of a resource
                   3129: 
                   3130: sub getversion {
                   3131:     my $fname=&clutter(shift);
1.1189    raeburn  3132:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3133:     return &currentversion(&filelocation('',$fname));
                   3134: }
                   3135: 
                   3136: sub currentversion {
                   3137:     my $fname=shift;
                   3138:     my $author=$fname;
                   3139:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3140:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3141:     my $home=&homeserver($uname,$udom);
1.292     www      3142:     if ($home eq 'no_host') { 
                   3143:         return -1; 
                   3144:     }
1.1112    www      3145:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3146:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3147: 	return -1;
                   3148:     }
1.1112    www      3149:     return $answer;
1.263     www      3150: }
                   3151: 
1.1111    www      3152: #
                   3153: # Return special version number of resource if set by override, empty otherwise
                   3154: #
                   3155: sub usedversion {
                   3156:     my $fname=shift;
                   3157:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3158:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3159:     if ($urlversion) { return $urlversion; }
                   3160:     return '';
                   3161: }
                   3162: 
1.1       albertel 3163: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3164: 
1.1       albertel 3165: sub subscribe {
                   3166:     my $fname=shift;
1.761     raeburn  3167:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3168:     $fname=~s/[\n\r]//g;
1.1       albertel 3169:     my $author=$fname;
                   3170:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3171:     my ($udom,$uname)=split(/\//,$author);
                   3172:     my $home=homeserver($uname,$udom);
1.335     albertel 3173:     if ($home eq 'no_host') {
                   3174:         return 'not_found';
1.1       albertel 3175:     }
                   3176:     my $answer=reply("sub:$fname",$home);
1.64      www      3177:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3178: 	$answer.=' by '.$home;
                   3179:     }
1.1       albertel 3180:     return $answer;
                   3181: }
                   3182:     
1.8       www      3183: # -------------------------------------------------------------- Replicate file
                   3184: 
                   3185: sub repcopy {
                   3186:     my $filename=shift;
1.23      www      3187:     $filename=~s/\/+/\//g;
1.1142    raeburn  3188:     my $londocroot = $perlvar{'lonDocRoot'};
                   3189:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3190:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3191:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3192: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3193: 	return &repcopy_userfile($filename);
                   3194:     }
1.532     albertel 3195:     $filename=~s/[\n\r]//g;
1.8       www      3196:     my $transname="$filename.in.transfer";
1.828     www      3197: # FIXME: this should flock
1.607     raeburn  3198:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3199:     my $remoteurl=subscribe($filename);
1.64      www      3200:     if ($remoteurl =~ /^con_lost by/) {
                   3201: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3202:            return 'unavailable';
1.8       www      3203:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3204: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3205: 	   return 'not_found';
1.64      www      3206:     } elsif ($remoteurl =~ /^rejected by/) {
                   3207: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3208:            return 'forbidden';
1.20      www      3209:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3210:            return 'ok';
1.8       www      3211:     } else {
1.290     www      3212:         my $author=$filename;
                   3213:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3214:         my ($udom,$uname)=split(/\//,$author);
                   3215:         my $home=homeserver($uname,$udom);
                   3216:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3217:            my @parts=split(/\//,$filename);
                   3218:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3219:            if ($path ne "$londocroot/res") {
1.8       www      3220:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3221: 	       return 'bad_request';
1.8       www      3222:            }
                   3223:            my $count;
                   3224:            for ($count=5;$count<$#parts;$count++) {
                   3225:                $path.="/$parts[$count]";
                   3226:                if ((-e $path)!=1) {
                   3227: 		   mkdir($path,0777);
                   3228:                }
                   3229:            }
                   3230:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3231:            my $response;
                   3232:            if ($remoteurl =~ m{/raw/}) {
                   3233:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3234:            } else {
                   3235:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3236:            }
1.8       www      3237:            if ($response->is_error()) {
                   3238: 	       unlink($transname);
                   3239:                my $message=$response->status_line;
1.672     albertel 3240:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3241:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3242:                return 'unavailable';
1.8       www      3243:            } else {
1.16      www      3244: 	       if ($remoteurl!~/\.meta$/) {
                   3245:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3246:                   my $mresponse;
                   3247:                   if ($remoteurl =~ m{/raw/}) {
                   3248:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3249:                   } else {
                   3250:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3251:                   }
1.16      www      3252:                   if ($mresponse->is_error()) {
                   3253: 		      unlink($filename.'.meta');
                   3254:                       &logthis(
1.672     albertel 3255:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3256:                   }
                   3257: 	       }
1.8       www      3258:                rename($transname,$filename);
1.607     raeburn  3259:                return 'ok';
1.8       www      3260:            }
1.290     www      3261:        }
1.8       www      3262:     }
1.330     www      3263: }
                   3264: 
                   3265: # ------------------------------------------------ Get server side include body
                   3266: sub ssi_body {
1.381     albertel 3267:     my ($filelink,%form)=@_;
1.606     matthew  3268:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3269:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3270:     }
1.953     www      3271:     my $output='';
                   3272:     my $response;
1.980     raeburn  3273:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3274:        ($output,$response)=&externalssi($filelink);
1.953     www      3275:     } else {
1.1004    droeschl 3276:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3277:        $filelink .= 'inhibitmenu=yes';
1.953     www      3278:        ($output,$response)=&ssi($filelink,%form);
                   3279:     }
1.778     albertel 3280:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3281:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3282:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3283:     if (wantarray) {
                   3284:         return ($output, $response);
                   3285:     } else {
                   3286:         return $output;
                   3287:     }
1.8       www      3288: }
                   3289: 
1.15      www      3290: # --------------------------------------------------------- Server Side Include
                   3291: 
1.782     albertel 3292: sub absolute_url {
                   3293:     my ($host_name) = @_;
                   3294:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3295:     if ($host_name eq '') {
                   3296: 	$host_name = $ENV{'SERVER_NAME'};
                   3297:     }
                   3298:     return $protocol.$host_name;
                   3299: }
                   3300: 
1.942     foxr     3301: #
                   3302: #   Server side include.
                   3303: # Parameters:
                   3304: #  fn     Possibly encrypted resource name/id.
                   3305: #  form   Hash that describes how the rendering should be done
                   3306: #         and other things.
1.944     foxr     3307: # Returns:
1.950     raeburn  3308: #   Scalar context: The content of the response.
                   3309: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3310: #     
1.15      www      3311: sub ssi {
                   3312: 
1.944     foxr     3313:     my ($fn,%form)=@_;
1.23      www      3314:     my $request;
1.711     albertel 3315: 
                   3316:     $form{'no_update_last_known'}=1;
1.895     albertel 3317:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3318:     if (%form) {
1.782     albertel 3319:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3320:       $request->content(join('&',map { 
                   3321:             my $name = escape($_);
                   3322:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3323:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3324:             : &escape($form{$_}) );    
                   3325:         } keys(%form)));
1.23      www      3326:     } else {
1.782     albertel 3327:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3328:     }
                   3329: 
1.15      www      3330:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3331:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3332:     my $islocal;
                   3333:     if (($env{'request.course.id'}) &&
                   3334:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3335:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3336:         ($form{'grade_symb'} ne '') &&
                   3337:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3338:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3339:         $islocal = 1;
                   3340:     }
1.1384    raeburn  3341:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3342:                                                 '','','',$islocal);
1.1182    foxr     3343: 
1.944     foxr     3344:     if (wantarray) {
1.1345    raeburn  3345: 	return ($response->content, $response);
1.944     foxr     3346:     } else {
1.1345    raeburn  3347: 	return $response->content;
1.942     foxr     3348:     }
1.324     www      3349: }
                   3350: 
                   3351: sub externalssi {
                   3352:     my ($url)=@_;
                   3353:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3354:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3355:     if (wantarray) {
                   3356:         return ($response->content, $response);
                   3357:     } else {
                   3358:         return $response->content;
                   3359:     }
1.15      www      3360: }
1.254     www      3361: 
1.1354    raeburn  3362: 
                   3363: # If the local copy of a replicated resource is outdated, trigger a  
                   3364: # connection from the homeserver to flush the delayed queue. If no update 
                   3365: # happens, remove local copies of outdated resource (and corresponding
                   3366: # metadata file).
                   3367: 
1.1352    raeburn  3368: sub remove_stale_resfile {
                   3369:     my ($url) = @_;
1.1354    raeburn  3370:     my $removed;
1.1352    raeburn  3371:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3372:         my $audom = $1;
                   3373:         my $auname = $2;
1.1353    raeburn  3374:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3375:             my $homeserver = &homeserver($auname,$audom);
                   3376:             unless (($homeserver eq 'no_host') ||
                   3377:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3378:                 my $fname = &filelocation('',$url);
                   3379:                 if (-e $fname) {
                   3380:                     my $hostname = &hostname($homeserver);
                   3381:                     if ($hostname) {
1.1397  ! raeburn  3382:                         my $protocol = $protocol{$homeserver};
        !          3383:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3384:                         my $uri = &declutter($url);
                   3385:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3386:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3387:                         if ($response->is_success()) {
                   3388:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3389:                             my $locmodtime = (stat($fname))[9];
                   3390:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3391:                                 my $stale;
                   3392:                                 my $answer = &reply('pong',$homeserver);
                   3393:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3394:                                     sleep(0.2);
                   3395:                                     $locmodtime = (stat($fname))[9];
                   3396:                                     if ($locmodtime < $remmodtime) {
                   3397:                                         my $posstransfer = $fname.'.in.transfer';
                   3398:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3399:                                             $removed = 1;
                   3400:                                         } else {
                   3401:                                             $stale = 1;
                   3402:                                         }
                   3403:                                     } else {
                   3404:                                         $removed = 1;
                   3405:                                     }
                   3406:                                 } else {
                   3407:                                     $stale = 1;
                   3408:                                 }
                   3409:                                 if ($stale) {
                   3410:                                     unlink($fname);
                   3411:                                     if ($uri!~/\.meta$/) {
                   3412:                                         unlink($fname.'.meta');
                   3413:                                     }
                   3414:                                     &reply("unsub:$fname",$homeserver);
                   3415:                                     $removed = 1;
1.1352    raeburn  3416:                                 }
                   3417:                             }
                   3418:                         }
                   3419:                     }
                   3420:                 }
                   3421:             }
                   3422:         }
                   3423:     }
1.1354    raeburn  3424:     return $removed;
1.1352    raeburn  3425: }
                   3426: 
1.492     albertel 3427: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3428: 
                   3429: sub allowuploaded {
                   3430:     my ($srcurl,$url)=@_;
                   3431:     $url=&clutter(&declutter($url));
                   3432:     my $dir=$url;
                   3433:     $dir=~s/\/[^\/]+$//;
                   3434:     my %httpref=();
                   3435:     my $httpurl=&hreflocation('',$url);
                   3436:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3437:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3438: }
1.477     raeburn  3439: 
1.1193    raeburn  3440: #
                   3441: # Determine if the current user should be able to edit a particular resource,
                   3442: # when viewing in course context.
                   3443: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3444: #     Functions.
                   3445: # (b) When displaying folder contents in course editor, used to determine if
                   3446: #     "Edit" link will be displayed alongside resource.
                   3447: #
1.1196    raeburn  3448: #  input: six args -- filename (decluttered), course number, course domain,
                   3449: #                   url, symb (if registered) and group (if this is a group
                   3450: #                   item -- e.g., bulletin board, group page etc.).
                   3451: #  output: array of five scalars -- 
1.1193    raeburn  3452: #          $cfile -- url for file editing if editable on current server
                   3453: #          $home -- homeserver of resource (i.e., for author if published,
                   3454: #                                           or course if uploaded.).
                   3455: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3456: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3457: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3458: #
                   3459: 
                   3460: sub can_edit_resource {
1.1194    raeburn  3461:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3462:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3463: #
                   3464: # For aboutme pages user can only edit his/her own.
                   3465: #
1.1199    raeburn  3466:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3467:         my ($sdom,$sname) = ($1,$2);
                   3468:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3469:             $home = $env{'user.home'};
                   3470:             $cfile = $resurl;
                   3471:             if ($env{'form.forceedit'}) {
                   3472:                 $forceview = 1;
                   3473:             } else {
                   3474:                 $forceedit = 1;
                   3475:             }
                   3476:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3477:         } else {
                   3478:             return;
                   3479:         }
                   3480:     }
                   3481: 
                   3482:     if ($env{'request.course.id'}) {
                   3483:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3484:         if ($group ne '') {
                   3485: # if this is a group homepage or group bulletin board, check group privs
                   3486:             my $allowed = 0;
1.1197    raeburn  3487:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3488:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3489:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3490:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3491:                     $allowed = 1;
                   3492:                 }
1.1197    raeburn  3493:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3494:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3495:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3496:                     $allowed = 1;
                   3497:                 }
                   3498:             }
                   3499:             if ($allowed) {
                   3500:                 $home=&homeserver($cnum,$cdom);
                   3501:                 if ($env{'form.forceedit'}) {
                   3502:                     $forceview = 1;
                   3503:                 } else {
                   3504:                     $forceedit = 1;
                   3505:                 }
                   3506:                 $cfile = $resurl;
                   3507:             } else {
                   3508:                 return;
                   3509:             }
                   3510:         } else {
1.1208    raeburn  3511:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3512:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3513:                     return;
                   3514:                 }
                   3515:             } elsif (!$crsedit) {
1.1194    raeburn  3516: #
                   3517: # No edit allowed where CC has switched to student role.
                   3518: #
                   3519:                 return;
                   3520:             }
                   3521:         }
                   3522:     }
                   3523: 
1.1193    raeburn  3524:     if ($file ne '') {
                   3525:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3526:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3527:                 $uploaded = 1;
                   3528:                 $incourse = 1;
1.1193    raeburn  3529:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3530:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3531:                     if ($env{'form.forceedit'}) {
                   3532:                         $forceview = 1;
                   3533:                     } else {
                   3534:                         $forceedit = 1;
                   3535:                     }
1.1194    raeburn  3536:                 }
                   3537:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3538:                 $incourse = 1;
                   3539:                 if ($env{'form.forceedit'}) {
                   3540:                     $forceview = 1;
                   3541:                 } else {
                   3542:                     $forceedit = 1;
                   3543:                 }
                   3544:                 $cfile = $resurl;
                   3545:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3546:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3547:                     $incourse = 1;
                   3548:                     if ($env{'form.forceedit'}) {
                   3549:                         $forceview = 1;
                   3550:                     } else {
                   3551:                         $forceedit = 1;
                   3552:                     }
                   3553:                     $cfile = $resurl;
1.1199    raeburn  3554:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3555:                     $incourse = 1;
                   3556:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3557:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3558:                     $incourse = 1;
1.1199    raeburn  3559:                     if ($env{'form.forceedit'}) {
                   3560:                         $forceview = 1;
                   3561:                     } else {
                   3562:                         $forceedit = 1;
                   3563:                     }
                   3564:                     $cfile = $resurl;
1.1343    raeburn  3565:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3566:                     $incourse = 1;
                   3567:                     if ($env{'form.forceedit'}) {
                   3568:                         $forceview = 1;
                   3569:                     } else {
                   3570:                         $forceedit = 1;
                   3571:                     }
                   3572:                     $cfile = $resurl;
1.1208    raeburn  3573:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3574:                     $incourse = 1;
                   3575:                     if ($env{'form.forceedit'}) {
                   3576:                         $forceview = 1;
                   3577:                     } else {
                   3578:                         $forceedit = 1;
                   3579:                     }
                   3580:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3581:                 }
                   3582:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3583:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3584:                 if (&is_on_map($template)) { 
                   3585:                     $incourse = 1;
                   3586:                     $forceview = 1;
                   3587:                     $cfile = $template;
1.1193    raeburn  3588:                 }
1.1199    raeburn  3589:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3590:                     $incourse = 1;
                   3591:                     if ($env{'form.forceedit'}) {
                   3592:                         $forceview = 1;
                   3593:                     } else {
                   3594:                         $forceedit = 1;
                   3595:                     }
                   3596:                     $cfile = $resurl;
1.1343    raeburn  3597:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3598:                 $incourse = 1;
                   3599:                 if ($env{'form.forceedit'}) {
                   3600:                     $forceview = 1;
                   3601:                 } else {
                   3602:                     $forceedit = 1;
                   3603:                 }
                   3604:                 $cfile = $resurl;
1.1199    raeburn  3605:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3606:                 $incourse = 1;
                   3607:                 $forceview = 1;
                   3608:                 if ($symb) {
                   3609:                     my ($map,$id,$res)=&decode_symb($symb);
                   3610:                     $env{'request.symb'} = $symb;
                   3611:                     $cfile = &clutter($res);
                   3612:                 } else {
                   3613:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3614:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3615:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3616:                         $cfile = '/adm/wrapper'.$escfile;
                   3617:                     } else {
                   3618:                         $escfile =~ s{^http://}{};
                   3619:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3620:                     }
1.1199    raeburn  3621:                 }
1.1234    raeburn  3622:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3623:                 if ($env{'form.forceedit'}) {
                   3624:                     $forceview = 1;
                   3625:                 } else {
                   3626:                     $forceedit = 1;
                   3627:                 }
                   3628:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3629:             }
                   3630:         }
1.1194    raeburn  3631:         if ($uploaded || $incourse) {
                   3632:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3633:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3634:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3635:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3636:             # Check that the user has permission to edit this resource
                   3637:             my $setpriv = 1;
                   3638:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3639:             if (defined($cfudom)) {
                   3640:                 $home=&homeserver($cfuname,$cfudom);
                   3641:                 $cfile=$file;
                   3642:             }
                   3643:         }
1.1194    raeburn  3644:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3645:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3646:             my @ids=&current_machine_ids();
                   3647:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3648:                 $switchserver=1;
                   3649:             }
                   3650:         }
                   3651:     }
1.1194    raeburn  3652:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3653: }
                   3654: 
                   3655: sub is_course_upload {
                   3656:     my ($file,$cnum,$cdom) = @_;
                   3657:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3658:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3659:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3660:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3661:         return 1;
                   3662:     }
                   3663:     return;
                   3664: }
                   3665: 
1.1194    raeburn  3666: sub in_course {
1.1195    raeburn  3667:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3668:     if ($hideprivileged) {
                   3669:         my $skipuser;
1.1219    raeburn  3670:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3671:         my @possdoms = ($cdom);  
                   3672:         if ($coursehash{'checkforpriv'}) { 
                   3673:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3674:         }
                   3675:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3676:             $skipuser = 1;
                   3677:             if ($coursehash{'nothideprivileged'}) {
                   3678:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3679:                     my $user;
                   3680:                     if ($item =~ /:/) {
                   3681:                         $user = $item;
                   3682:                     } else {
                   3683:                         $user = join(':',split(/[\@]/,$item));
                   3684:                     }
                   3685:                     if ($user eq $uname.':'.$udom) {
                   3686:                         undef($skipuser);
                   3687:                         last;
                   3688:                     }
                   3689:                 }
                   3690:             }
                   3691:             if ($skipuser) {
                   3692:                 return 0;
                   3693:             }
                   3694:         }
                   3695:     }
1.1194    raeburn  3696:     $type ||= 'any';
                   3697:     if (!defined($cdom) || !defined($cnum)) {
                   3698:         my $cid  = $env{'request.course.id'};
                   3699:         $cdom = $env{'course.'.$cid.'.domain'};
                   3700:         $cnum = $env{'course.'.$cid.'.num'};
                   3701:     }
                   3702:     my $typesref;
1.1195    raeburn  3703:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3704:         $typesref = ['active','previous','future'];
                   3705:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3706:         $typesref = [$type];
                   3707:     }
                   3708:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3709:                               $typesref,undef,[$cdom]);
                   3710:     my ($tmp) = keys(%roles);
                   3711:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3712:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3713:     if (@course_roles > 0) {
                   3714:         return 1;
                   3715:     }
                   3716:     return 0;
                   3717: }
                   3718: 
1.478     albertel 3719: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3720: # input: action, courseID, current domain, intended
1.637     raeburn  3721: #        path to file, source of file, instruction to parse file for objects,
                   3722: #        ref to hash for embedded objects,
                   3723: #        ref to hash for codebase of java objects.
1.1095    raeburn  3724: #        reference to scalar to accommodate mime type determined
                   3725: #          from File::MMagic if $parser = parse.
1.637     raeburn  3726: #
1.485     raeburn  3727: # output: url to file (if action was uploaddoc), 
                   3728: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3729: #
1.478     albertel 3730: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3731: # course.
1.477     raeburn  3732: #
1.478     albertel 3733: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3734: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3735: #          course's home server.
1.477     raeburn  3736: #
1.478     albertel 3737: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3738: #          be copied from $source (current location) to 
                   3739: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3740: #         and will then be copied to
                   3741: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3742: #         course's home server.
1.485     raeburn  3743: #
1.481     raeburn  3744: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3745: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3746: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3747: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3748: #         in course's home server.
1.637     raeburn  3749: #
1.477     raeburn  3750: 
                   3751: sub process_coursefile {
1.1095    raeburn  3752:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3753:         $mimetype)=@_;
1.477     raeburn  3754:     my $fetchresult;
1.638     albertel 3755:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3756:     if ($action eq 'propagate') {
1.638     albertel 3757:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3758: 			     $home);
1.481     raeburn  3759:     } else {
1.477     raeburn  3760:         my $fpath = '';
                   3761:         my $fname = $file;
1.478     albertel 3762:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3763:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3764:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3765:         if ($action eq 'copy') {
                   3766:             if ($source eq '') {
                   3767:                 $fetchresult = 'no source file';
                   3768:                 return $fetchresult;
                   3769:             } else {
                   3770:                 my $destination = $filepath.'/'.$fname;
                   3771:                 rename($source,$destination);
                   3772:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3773:                                  $home);
1.481     raeburn  3774:             }
                   3775:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3776:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3777:             print $fh $env{'form.'.$source};
1.481     raeburn  3778:             close($fh);
1.637     raeburn  3779:             if ($parser eq 'parse') {
1.1024    raeburn  3780:                 my $mm = new File::MMagic;
1.1095    raeburn  3781:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3782:                 if ($type eq 'text/html') {
1.1024    raeburn  3783:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3784:                     unless ($parse_result eq 'ok') {
                   3785:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3786:                     }
1.637     raeburn  3787:                 }
1.1095    raeburn  3788:                 if (ref($mimetype)) {
                   3789:                     $$mimetype = $type;
                   3790:                 } 
1.637     raeburn  3791:             }
1.477     raeburn  3792:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3793:                                  $home);
1.481     raeburn  3794:             if ($fetchresult eq 'ok') {
                   3795:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3796:             } else {
                   3797:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3798:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3799:                 return '/adm/notfound.html';
                   3800:             }
1.477     raeburn  3801:         }
                   3802:     }
1.485     raeburn  3803:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3804:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3805:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3806:     }
                   3807:     return $fetchresult;
                   3808: }
                   3809: 
1.637     raeburn  3810: sub build_filepath {
                   3811:     my ($fpath) = @_;
                   3812:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3813:     unless ($fpath eq '') {
                   3814:         my @parts=split('/',$fpath);
                   3815:         foreach my $part (@parts) {
                   3816:             $filepath.= '/'.$part;
                   3817:             if ((-e $filepath)!=1) {
                   3818:                 mkdir($filepath,0777);
                   3819:             }
                   3820:         }
                   3821:     }
                   3822:     return $filepath;
                   3823: }
                   3824: 
                   3825: sub store_edited_file {
1.638     albertel 3826:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3827:     my $file = $primary_url;
                   3828:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3829:     my $fpath = '';
                   3830:     my $fname = $file;
                   3831:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3832:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3833:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3834:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3835:     print $fh $content;
                   3836:     close($fh);
1.638     albertel 3837:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3838:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3839: 			  $home);
1.637     raeburn  3840:     if ($$fetchresult eq 'ok') {
                   3841:         return '/uploaded/'.$fpath.'/'.$fname;
                   3842:     } else {
1.638     albertel 3843:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3844: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3845:         return '/adm/notfound.html';
                   3846:     }
                   3847: }
                   3848: 
1.531     albertel 3849: sub clean_filename {
1.831     albertel 3850:     my ($fname,$args)=@_;
1.315     www      3851: # Replace Windows backslashes by forward slashes
1.257     www      3852:     $fname=~s/\\/\//g;
1.831     albertel 3853:     if (!$args->{'keep_path'}) {
                   3854:         # Get rid of everything but the actual filename
                   3855: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3856:     }
1.315     www      3857: # Replace spaces by underscores
                   3858:     $fname=~s/\s+/\_/g;
                   3859: # Replace all other weird characters by nothing
1.831     albertel 3860:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3861: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3862: # numbers
                   3863:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3864:     return $fname;
                   3865: }
1.1051    raeburn  3866: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3867: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3868: # image with the same aspect ratio as the original, but with dimensions which do 
                   3869: # not exceed $resizewidth and $resizeheight.
                   3870:  
1.984     neumanie 3871: sub resizeImage {
1.1051    raeburn  3872:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3873:     my $ima = Image::Magick->new;
                   3874:     my $resized;
                   3875:     if (-e $img_path) {
                   3876:         $ima->Read($img_path);
                   3877:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3878:             my $width = $ima->Get('width');
                   3879:             my $height = $ima->Get('height');
                   3880:             if ($width > $resizewidth) {
                   3881: 	        my $factor = $width/$resizewidth;
                   3882:                 my $newheight = $height/$factor;
                   3883:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3884:                 $resized = 1;
                   3885:             }
                   3886:         }
                   3887:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3888:             my $width = $ima->Get('width');
                   3889:             my $height = $ima->Get('height');
                   3890:             if ($height > $resizeheight) {
                   3891:                 my $factor = $height/$resizeheight;
                   3892:                 my $newwidth = $width/$factor;
                   3893:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3894:                 $resized = 1;
                   3895:             }
                   3896:         }
                   3897:         if ($resized) {
                   3898:             $ima->Write($img_path);
                   3899:         }
                   3900:     }
                   3901:     return;
1.977     amueller 3902: }
                   3903: 
1.608     albertel 3904: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3905: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3906: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3907: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3908: #                                    canceloverwrite, or ''. 
                   3909: #                   if 'coursedoc': upload to the current course
                   3910: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3911: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3912: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3913: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3914: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3915: #        $allfiles - reference to hash for embedded objects
                   3916: #        $codebase - reference to hash for codebase of java objects
                   3917: #        $desuname - username for permanent storage of uploaded file
                   3918: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3919: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3920: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3921: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3922: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3923: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3924: #                    from File::MMagic.
1.858     raeburn  3925: # 
1.686     albertel 3926: # output: url of file in userspace, or error: <message> 
                   3927: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3928: 
1.531     albertel 3929: sub userfileupload {
1.1090    raeburn  3930:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3931:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3932:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3933:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3934:     $fname=&clean_filename($fname);
1.1090    raeburn  3935:     # See if there is anything left
1.257     www      3936:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3937:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3938:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3939:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3940:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3941:         my $now = time;
1.1090    raeburn  3942:         my $filepath;
1.1095    raeburn  3943:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3944:              $filepath = 'tmp/helprequests/'.$now;
                   3945:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3946:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3947:                          '_'.$env{'user.domain'}.'/pending';
                   3948:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3949:             my ($docuname,$docudom);
1.1350    raeburn  3950:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3951:                 $docudom = $destudom;
                   3952:             } else {
                   3953:                 $docudom = $env{'user.domain'};
                   3954:             }
1.1350    raeburn  3955:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3956:                 $docuname = $destuname;
                   3957:             } else {
                   3958:                 $docuname = $env{'user.name'};
                   3959:             }
                   3960:             if (exists($env{'form.group'})) {
                   3961:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3962:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3963:             }
                   3964:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3965:             if ($context eq 'canceloverwrite') {
                   3966:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3967:                 if (-e  $tempfile) {
                   3968:                     my @info = stat($tempfile);
                   3969:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3970:                         unlink($tempfile);
                   3971:                     }
                   3972:                 }
                   3973:                 return;
1.523     raeburn  3974:             }
                   3975:         }
1.1090    raeburn  3976:         # Create the directory if not present
1.741     raeburn  3977:         my @parts=split(/\//,$filepath);
                   3978:         my $fullpath = $perlvar{'lonDaemons'};
                   3979:         for (my $i=0;$i<@parts;$i++) {
                   3980:             $fullpath .= '/'.$parts[$i];
                   3981:             if ((-e $fullpath)!=1) {
                   3982:                 mkdir($fullpath,0777);
                   3983:             }
                   3984:         }
1.1359    raeburn  3985:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3986:         print $fh $env{'form.'.$formname};
                   3987:         close($fh);
1.1090    raeburn  3988:         if ($context eq 'existingfile') {
                   3989:             my @info = stat($fullpath.'/'.$fname);
                   3990:             return ($fullpath.'/'.$fname,$info[9]);
                   3991:         } else {
                   3992:             return $fullpath.'/'.$fname;
                   3993:         }
1.523     raeburn  3994:     }
1.995     raeburn  3995:     if ($subdir eq 'scantron') {
                   3996:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3997:     } else {
1.995     raeburn  3998:         $fname="$subdir/$fname";
                   3999:     }
1.1090    raeburn  4000:     if ($context eq 'coursedoc') {
1.638     albertel 4001: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4002: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4003:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4004:             return &finishuserfileupload($docuname,$docudom,
                   4005: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4006: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4007:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4008:         } else {
1.1218    raeburn  4009:             if ($env{'form.folder'}) {
                   4010:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4011:             }
1.638     albertel 4012:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4013: 				       $fname,$formname,$parser,
1.1095    raeburn  4014: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4015:         }
1.719     banghart 4016:     } elsif (defined($destuname)) {
                   4017:         my $docuname=$destuname;
                   4018:         my $docudom=$destudom;
1.860     raeburn  4019: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4020: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4021:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4022:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4023:     } else {
1.638     albertel 4024:         my $docuname=$env{'user.name'};
                   4025:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4026:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4027:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4028:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4029:         }
1.860     raeburn  4030: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4031: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4032:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4033:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4034:     }
1.271     www      4035: }
                   4036: 
                   4037: sub finishuserfileupload {
1.860     raeburn  4038:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4039:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4040:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4041:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4042:   
1.860     raeburn  4043:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4044:     $file=$fname;
                   4045:     if ($fname=~m|/|) {
                   4046:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4047: 	$path.=$fnamepath.'/';
                   4048:     }
1.259     www      4049:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4050:     my $count;
                   4051:     for ($count=4;$count<=$#parts;$count++) {
                   4052:         $filepath.="/$parts[$count]";
                   4053:         if ((-e $filepath)!=1) {
                   4054: 	    mkdir($filepath,0777);
                   4055:         }
                   4056:     }
1.984     neumanie 4057: 
1.258     www      4058: # Save the file
                   4059:     {
1.1359    raeburn  4060: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4061: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4062: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4063: 	    return '/adm/notfound.html';
                   4064: 	}
1.1090    raeburn  4065:         if ($context eq 'overwrite') {
1.1117    foxr     4066:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4067:             my $target = $filepath.'/'.$file;
                   4068:             if (-e $source) {
                   4069:                 my @info = stat($source);
                   4070:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4071:                     unless (&File::Copy::move($source,$target)) {
                   4072:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4073:                         return "Moving from $source failed";
                   4074:                     }
                   4075:                 } else {
                   4076:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4077:                 }
                   4078:             } else {
                   4079:                 return "Temporary file: $source missing";
                   4080:             }
                   4081:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4082: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4083: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4084: 	    return '/adm/notfound.html';
                   4085: 	}
1.570     albertel 4086: 	close(FH);
1.1051    raeburn  4087:         if ($resizewidth && $resizeheight) {
                   4088:             my $mm = new File::MMagic;
                   4089:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4090:             if ($mime_type =~ m{^image/}) {
                   4091: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4092:             }  
1.977     amueller 4093: 	}
1.258     www      4094:     }
1.1152    raeburn  4095:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4096:         if (ref($mimetype)) {
                   4097:             if ($$mimetype eq '') {
                   4098:                 my $mm = new File::MMagic;
                   4099:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4100:                 $$mimetype = $type;
                   4101:             }
                   4102:         }
                   4103:     }
1.637     raeburn  4104:     if ($parser eq 'parse') {
1.1152    raeburn  4105:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4106:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4107:                                                        $allfiles,$codebase);
                   4108:             unless ($parse_result eq 'ok') {
                   4109:                 &logthis('Failed to parse '.$filepath.$file.
                   4110: 	   	         ' for embedded media: '.$parse_result); 
                   4111:             }
1.637     raeburn  4112:         }
                   4113:     }
1.860     raeburn  4114:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4115:         my $input = $filepath.'/'.$file;
                   4116:         my $output = $filepath.'/'.'tn-'.$file;
                   4117:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4118:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4119:         system({$args[0]} @args);
1.860     raeburn  4120:         if (-e $filepath.'/'.'tn-'.$file) {
                   4121:             $fetchthumb  = 1; 
                   4122:         }
                   4123:     }
1.858     raeburn  4124:  
1.259     www      4125: # Notify homeserver to grep it
                   4126: #
1.984     neumanie 4127:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4128:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4129:     if ($fetchresult eq 'ok') {
1.860     raeburn  4130:         if ($fetchthumb) {
                   4131:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4132:             if ($thumbresult ne 'ok') {
                   4133:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4134:                          $docuhome.': '.$thumbresult);
                   4135:             }
                   4136:         }
1.259     www      4137: #
1.258     www      4138: # Return the URL to it
1.494     albertel 4139:         return '/uploaded/'.$path.$file;
1.263     www      4140:     } else {
1.494     albertel 4141:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4142: 		 ': '.$fetchresult);
1.263     www      4143:         return '/adm/notfound.html';
1.858     raeburn  4144:     }
1.493     albertel 4145: }
                   4146: 
1.637     raeburn  4147: sub extract_embedded_items {
1.961     raeburn  4148:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4149:     my @state = ();
1.1164    raeburn  4150:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4151:     my %javafiles = (
                   4152:                       codebase => '',
                   4153:                       code => '',
                   4154:                       archive => ''
                   4155:                     );
                   4156:     my %mediafiles = (
                   4157:                       src => '',
                   4158:                       movie => '',
                   4159:                      );
1.648     raeburn  4160:     my $p;
                   4161:     if ($content) {
                   4162:         $p = HTML::LCParser->new($content);
                   4163:     } else {
1.961     raeburn  4164:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4165:     }
1.641     albertel 4166:     while (my $t=$p->get_token()) {
1.640     albertel 4167: 	if ($t->[0] eq 'S') {
                   4168: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4169: 	    push(@state, $tagname);
1.648     raeburn  4170:             if (lc($tagname) eq 'allow') {
                   4171:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4172:             }
1.640     albertel 4173: 	    if (lc($tagname) eq 'img') {
                   4174: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4175: 	    }
1.886     albertel 4176: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4177:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4178:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4179:                 }
1.886     albertel 4180: 	    }
1.645     raeburn  4181:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4182:                 my $src;
1.645     raeburn  4183:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4184:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4185:                 } else {
1.1164    raeburn  4186:                     if ($attr->{'src'} ne '') {
                   4187:                         $src = $attr->{'src'};
                   4188:                         &add_filetype($allfiles,$src,'src');
                   4189:                     }
                   4190:                 }
                   4191:                 my $text = $p->get_trimmed_text();
                   4192:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4193:                     my @swfargs = split(/,/,$1);
                   4194:                     foreach my $item (@swfargs) {
                   4195:                         $item =~ s/["']//g;
                   4196:                         $item =~ s/^\s+//;
                   4197:                         $item =~ s/\s+$//;
                   4198:                     }
                   4199:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4200:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4201:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4202:                         } else {
                   4203:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4204:                         }
                   4205:                     }
1.645     raeburn  4206:                 }
                   4207:             }
                   4208:             if (lc($tagname) eq 'link') {
                   4209:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4210:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4211:                 }
                   4212:             }
1.640     albertel 4213: 	    if (lc($tagname) eq 'object' ||
                   4214: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4215: 		foreach my $item (keys(%javafiles)) {
                   4216: 		    $javafiles{$item} = '';
                   4217: 		}
1.1164    raeburn  4218:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4219:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4220:                 }
1.640     albertel 4221: 	    }
                   4222: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4223: 		my $name = lc($attr->{'name'});
                   4224: 		foreach my $item (keys(%javafiles)) {
                   4225: 		    if ($name eq $item) {
                   4226: 			$javafiles{$item} = $attr->{'value'};
                   4227: 			last;
                   4228: 		    }
                   4229: 		}
1.1164    raeburn  4230:                 my $pathfrom;
1.640     albertel 4231: 		foreach my $item (keys(%mediafiles)) {
                   4232: 		    if ($name eq $item) {
1.1164    raeburn  4233:                         $pathfrom = $attr->{'value'};
                   4234:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4235: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4236: 			last;
                   4237: 		    }
                   4238: 		}
1.1164    raeburn  4239:                 if ($name eq 'flashvars') {
                   4240:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4241:                 }
                   4242:                 if ($pathfrom ne '') {
                   4243:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4244:                                          $pathfrom);
                   4245:                 }
1.640     albertel 4246: 	    }
                   4247: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4248: 		foreach my $item (keys(%javafiles)) {
                   4249: 		    if ($attr->{$item}) {
                   4250: 			$javafiles{$item} = $attr->{$item};
                   4251: 			last;
                   4252: 		    }
                   4253: 		}
                   4254: 		foreach my $item (keys(%mediafiles)) {
                   4255: 		    if ($attr->{$item}) {
                   4256: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4257: 			last;
                   4258: 		    }
                   4259: 		}
1.1164    raeburn  4260:                 if (lc($tagname) eq 'embed') {
                   4261:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4262:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4263:                                              $attr->{'src'});
                   4264:                     }
                   4265:                 }
1.640     albertel 4266: 	    }
1.1243    raeburn  4267:             if (lc($tagname) eq 'iframe') {
                   4268:                 my $src = $attr->{'src'} ;
                   4269:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4270:                     &add_filetype($allfiles,$src,'src');
                   4271:                 } elsif ($src =~ m{^/}) {
                   4272:                     if ($env{'request.course.id'}) {
                   4273:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4274:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4275:                         my $url = &hreflocation('',$fullpath);
                   4276:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4277:                             my $relpath = $1;
                   4278:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4279:                                 &add_filetype($allfiles,$1,'src');
                   4280:                             }
                   4281:                         }
                   4282:                     }
                   4283:                 }
                   4284:             }
1.1164    raeburn  4285:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4286:                 pop(@state);
1.1164    raeburn  4287:             }
1.640     albertel 4288: 	} elsif ($t->[0] eq 'E') {
                   4289: 	    my ($tagname) = ($t->[1]);
                   4290: 	    if ($javafiles{'codebase'} ne '') {
                   4291: 		$javafiles{'codebase'} .= '/';
                   4292: 	    }  
                   4293: 	    if (lc($tagname) eq 'applet' ||
                   4294: 		lc($tagname) eq 'object' ||
                   4295: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4296: 		) {
                   4297: 		foreach my $item (keys(%javafiles)) {
                   4298: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4299: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4300: 			&add_filetype($allfiles,$file,$item);
                   4301: 		    }
                   4302: 		}
                   4303: 	    } 
                   4304: 	    pop @state;
                   4305: 	}
                   4306:     }
1.1164    raeburn  4307:     foreach my $id (sort(keys(%flashvars))) {
                   4308:         if ($shockwave{$id} ne '') {
                   4309:             my @pairs = split(/\&/,$flashvars{$id});
                   4310:             foreach my $pair (@pairs) {
                   4311:                 my ($key,$value) = split(/\=/,$pair);
                   4312:                 if ($key eq 'thumb') {
                   4313:                     &add_filetype($allfiles,$value,$key);
                   4314:                 } elsif ($key eq 'content') {
                   4315:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4316:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4317:                     if ($ext ne '') {
                   4318:                         &add_filetype($allfiles,$path.$value,$ext);
                   4319:                     }
                   4320:                 }
                   4321:             }
                   4322:         }
                   4323:     }
1.637     raeburn  4324:     return 'ok';
                   4325: }
                   4326: 
1.639     albertel 4327: sub add_filetype {
                   4328:     my ($allfiles,$file,$type)=@_;
                   4329:     if (exists($allfiles->{$file})) {
                   4330: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4331: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4332: 	}
                   4333:     } else {
                   4334: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4335:     }
                   4336: }
                   4337: 
1.1164    raeburn  4338: sub embedded_dependency {
                   4339:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4340:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4341:         if (($identifier ne '') &&
                   4342:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4343:             ($pathfrom ne '')) {
                   4344:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4345:             foreach my $dep (@{$related->{$identifier}}) {
                   4346:                 &add_filetype($allfiles,$path.$dep,'object');
                   4347:             }
                   4348:         }
                   4349:     }
                   4350:     return;
                   4351: }
                   4352: 
1.493     albertel 4353: sub removeuploadedurl {
1.984     neumanie 4354:     my ($url)=@_;	
                   4355:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4356:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4357: }
                   4358: 
                   4359: sub removeuserfile {
                   4360:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4361:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4362:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4363:     if ($result eq 'ok') {	
1.798     raeburn  4364:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4365:             my $metafile = $fname.'.meta';
                   4366:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4367: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4368:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4369:             my $sqlresult = 
1.823     albertel 4370:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4371:                                         'portfolio_metadata',$group,
                   4372:                                         'delete');
1.798     raeburn  4373:         }
                   4374:     }
                   4375:     return $result;
1.257     www      4376: }
1.15      www      4377: 
1.530     albertel 4378: sub mkdiruserfile {
                   4379:     my ($docuname,$docudom,$dir)=@_;
                   4380:     my $home=&homeserver($docuname,$docudom);
                   4381:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4382: }
                   4383: 
1.531     albertel 4384: sub renameuserfile {
                   4385:     my ($docuname,$docudom,$old,$new)=@_;
                   4386:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4387:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4388:                         &escape("$old").':'.&escape("$new"),$home);
                   4389:     if ($result eq 'ok') {
                   4390:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4391:             my $oldmeta = $old.'.meta';
                   4392:             my $newmeta = $new.'.meta';
                   4393:             my $metaresult = 
                   4394:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4395: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4396:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4397:             my $sqlresult = 
1.823     albertel 4398:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4399:                                         'portfolio_metadata',$group,
                   4400:                                         'delete');
1.798     raeburn  4401:         }
                   4402:     }
                   4403:     return $result;
1.531     albertel 4404: }
                   4405: 
1.14      www      4406: # ------------------------------------------------------------------------- Log
                   4407: 
                   4408: sub log {
                   4409:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4410:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4411: }
                   4412: 
                   4413: # ------------------------------------------------------------------ Course Log
1.352     www      4414: #
                   4415: # This routine flushes several buffers of non-mission-critical nature
                   4416: #
1.157     www      4417: 
                   4418: sub flushcourselogs {
1.352     www      4419:     &logthis('Flushing log buffers');
                   4420: #
                   4421: # course logs
                   4422: # This is a log of all transactions in a course, which can be used
                   4423: # for data mining purposes
                   4424: #
                   4425: # It also collects the courseid database, which lists last transaction
                   4426: # times and course titles for all courseids
                   4427: #
                   4428:     my %courseidbuffer=();
1.921     raeburn  4429:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4430:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4431: 		          &escape($courselogs{$crsid}),
                   4432: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4433: 	    delete $courselogs{$crsid};
                   4434:         } else {
                   4435:             &logthis('Failed to flush log buffer for '.$crsid);
                   4436:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4437:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4438:                         " exceeded maximum size, deleting.</font>");
                   4439:                delete $courselogs{$crsid};
                   4440:             }
1.352     www      4441:         }
1.920     raeburn  4442:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4443:             'description' => $coursedescrbuf{$crsid},
                   4444:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4445:             'type'        => $coursetypebuf{$crsid},
                   4446:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4447:         };
1.191     harris41 4448:     }
1.352     www      4449: #
                   4450: # Write course id database (reverse lookup) to homeserver of courses 
                   4451: # Is used in pickcourse
                   4452: #
1.840     albertel 4453:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4454:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4455:                                     $courseidbuffer{$crs_home},
                   4456:                                     $crs_home,'timeonly');
1.352     www      4457:     }
                   4458: #
                   4459: # File accesses
                   4460: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4461: #
1.449     matthew  4462:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4463:         if ($entry =~ /___count$/) {
                   4464:             my ($dom,$name);
1.807     albertel 4465:             ($dom,$name,undef)=
1.811     albertel 4466: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4467:             if (! defined($dom) || $dom eq '' || 
                   4468:                 ! defined($name) || $name eq '') {
1.620     albertel 4469:                 my $cid = $env{'request.course.id'};
                   4470:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4471:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4472:             }
1.450     matthew  4473:             my $value = $accesshash{$entry};
                   4474:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4475:             my %temphash=($url => $value);
1.449     matthew  4476:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4477:             if ($result eq 'ok') {
                   4478:                 delete $accesshash{$entry};
                   4479:             }
                   4480:         } else {
1.811     albertel 4481:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4482:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4483:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4484:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4485:                 delete $accesshash{$entry};
                   4486:             }
1.185     www      4487:         }
1.191     harris41 4488:     }
1.352     www      4489: #
                   4490: # Roles
                   4491: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4492: #
1.800     albertel 4493:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4494:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4495: 	    split(/\:/,$entry);
                   4496:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4497:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4498:                 $rudom,$runame) eq 'ok') {
                   4499: 	    delete $userrolehash{$entry};
                   4500:         }
                   4501:     }
1.662     raeburn  4502: #
1.1334    raeburn  4503: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4504: #
                   4505:     my %domrolebuffer = ();
1.1000    raeburn  4506:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4507:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4508:         if ($domrolebuffer{$rudom}) {
                   4509:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4510:                       '='.&escape($domainrolehash{$entry});
                   4511:         } else {
                   4512:             $domrolebuffer{$rudom}.=&escape($entry).
                   4513:                       '='.&escape($domainrolehash{$entry});
                   4514:         }
                   4515:         delete $domainrolehash{$entry};
                   4516:     }
                   4517:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4518: 	my %servers;
                   4519: 	if (defined(&domain($dom,'primary'))) {
                   4520: 	    my $primary=&domain($dom,'primary');
                   4521: 	    my $hostname=&hostname($primary);
                   4522: 	    $servers{$primary} = $hostname;
                   4523: 	} else { 
                   4524: 	    %servers = &get_servers($dom,'library');
                   4525: 	}
1.841     albertel 4526: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4527: 	    if (&reply('domroleput:'.$dom.':'.
                   4528: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4529: 		last;
                   4530: 	    } else {  
1.841     albertel 4531: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4532: 	    }
1.662     raeburn  4533:         }
                   4534:     }
1.186     www      4535:     $dumpcount++;
1.157     www      4536: }
                   4537: 
                   4538: sub courselog {
                   4539:     my $what=shift;
1.158     www      4540:     $what=time.':'.$what;
1.620     albertel 4541:     unless ($env{'request.course.id'}) { return ''; }
                   4542:     $coursedombuf{$env{'request.course.id'}}=
                   4543:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4544:     $coursenumbuf{$env{'request.course.id'}}=
                   4545:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4546:     $coursehombuf{$env{'request.course.id'}}=
                   4547:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4548:     $coursedescrbuf{$env{'request.course.id'}}=
                   4549:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4550:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4551:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4552:     $courseownerbuf{$env{'request.course.id'}}=
                   4553:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4554:     $coursetypebuf{$env{'request.course.id'}}=
                   4555:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4556:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4557: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4558:     } else {
1.620     albertel 4559: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4560:     }
1.620     albertel 4561:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4562: 	&flushcourselogs();
                   4563:     }
1.158     www      4564: }
                   4565: 
                   4566: sub courseacclog {
                   4567:     my $fnsymb=shift;
1.620     albertel 4568:     unless ($env{'request.course.id'}) { return ''; }
                   4569:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4570:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4571:         $what.=':POST';
1.583     matthew  4572:         # FIXME: Probably ought to escape things....
1.800     albertel 4573: 	foreach my $key (keys(%env)) {
                   4574:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4575:                 my $formitem = $1;
                   4576:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4577:                     $what.=':'.$formitem.'='.$env{$key};
                   4578:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4579:                     $what.=':'.$formitem.'='.$env{$key};
                   4580:                 }
1.158     www      4581:             }
1.191     harris41 4582:         }
1.583     matthew  4583:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4584:         # FIXME: We should not be depending on a form parameter that someone
                   4585:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4586:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4587:             $what.= ':POST';
                   4588:             # FIXME: Probably ought to escape things....
                   4589:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4590:                                  'crsdiscuss') {
1.620     albertel 4591:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4592:             }
                   4593:         }
1.158     www      4594:     }
                   4595:     &courselog($what);
1.149     www      4596: }
                   4597: 
1.185     www      4598: sub countacc {
                   4599:     my $url=&declutter(shift);
1.458     matthew  4600:     return if (! defined($url) || $url eq '');
1.620     albertel 4601:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4602: #
                   4603: # Mark that this url was used in this course
                   4604: #
1.620     albertel 4605:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4606: #
                   4607: # Increase the access count for this resource in this child process
                   4608: #
1.281     www      4609:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4610:     $accesshash{$key}++;
1.185     www      4611: }
1.349     www      4612: 
1.361     www      4613: sub linklog {
                   4614:     my ($from,$to)=@_;
                   4615:     $from=&declutter($from);
                   4616:     $to=&declutter($to);
                   4617:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4618:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4619: }
1.1160    www      4620: 
                   4621: sub statslog {
                   4622:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4623:     if ($users<2) { return; }
                   4624:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4625:             'course'       => $env{'request.course.id'},
                   4626:             'sections'     => '"all"',
                   4627:             'num_students' => $users,
                   4628:             'part'         => $part,
                   4629:             'symb'         => $symb,
                   4630:             'mean_tries'   => $av_attempts,
                   4631:             'deg_of_diff'  => $degdiff});
                   4632:     foreach my $key (keys(%dynstore)) {
                   4633:         $accesshash{$key}=$dynstore{$key};
                   4634:     }
                   4635: }
1.361     www      4636:   
1.349     www      4637: sub userrolelog {
                   4638:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4639:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4640:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4641:        $userrolehash
                   4642:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4643:                     =$tend.':'.$tstart;
1.662     raeburn  4644:     }
1.1169    droeschl 4645:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4646:        $userrolehash
                   4647:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4648:                     =$tend.':'.$tstart;
                   4649:     }
1.1334    raeburn  4650:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4651:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4652:        $domainrolehash
                   4653:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4654:                     = $tend.':'.$tstart;
                   4655:     }
1.351     www      4656: }
                   4657: 
1.957     raeburn  4658: sub courserolelog {
                   4659:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4660:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4661:         my $cdom = $1;
                   4662:         my $cnum = $2;
                   4663:         my $sec = $3;
                   4664:         my $namespace = 'rolelog';
                   4665:         my %storehash = (
                   4666:                            role    => $trole,
                   4667:                            start   => $tstart,
                   4668:                            end     => $tend,
                   4669:                            selfenroll => $selfenroll,
                   4670:                            context    => $context,
                   4671:                         );
                   4672:         if ($trole eq 'gr') {
                   4673:             $namespace = 'groupslog';
                   4674:             $storehash{'group'} = $sec;
                   4675:         } else {
                   4676:             $storehash{'section'} = $sec;
                   4677:         }
1.1188    raeburn  4678:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4679:                    $domain,$cnum,$cdom);
1.1184    raeburn  4680:         if (($trole ne 'st') || ($sec ne '')) {
                   4681:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4682:         }
                   4683:     }
                   4684:     return;
                   4685: }
                   4686: 
1.1184    raeburn  4687: sub domainrolelog {
                   4688:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4689:     if ($area =~ m{^/($match_domain)/$}) {
                   4690:         my $cdom = $1;
                   4691:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4692:         my $namespace = 'rolelog';
                   4693:         my %storehash = (
                   4694:                            role    => $trole,
                   4695:                            start   => $tstart,
                   4696:                            end     => $tend,
                   4697:                            context => $context,
                   4698:                         );
1.1188    raeburn  4699:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4700:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4701:     }
                   4702:     return;
                   4703: 
                   4704: }
                   4705: 
                   4706: sub coauthorrolelog {
                   4707:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4708:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4709:         my $audom = $1;
                   4710:         my $auname = $2;
                   4711:         my $namespace = 'rolelog';
                   4712:         my %storehash = (
                   4713:                            role    => $trole,
                   4714:                            start   => $tstart,
                   4715:                            end     => $tend,
                   4716:                            context => $context,
                   4717:                         );
1.1188    raeburn  4718:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4719:                    $domain,$auname,$audom);
1.1184    raeburn  4720:     }
                   4721:     return;
                   4722: }
                   4723: 
1.351     www      4724: sub get_course_adv_roles {
1.948     raeburn  4725:     my ($cid,$codes) = @_;
1.620     albertel 4726:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4727:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4728:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4729:     my %nothide=();
1.800     albertel 4730:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4731:         if ($user !~ /:/) {
                   4732: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4733:         } else {
                   4734:             $nothide{$user}=1;
                   4735:         }
1.470     www      4736:     }
1.1219    raeburn  4737:     my @possdoms = ($coursehash{'domain'});
                   4738:     if ($coursehash{'checkforpriv'}) {
                   4739:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4740:     }
1.351     www      4741:     my %returnhash=();
                   4742:     my %dumphash=
                   4743:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4744:     my $now=time;
1.997     raeburn  4745:     my %privileged;
1.1000    raeburn  4746:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4747: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4748:         if (($tstart) && ($tstart<0)) { next; }
                   4749:         if (($tend) && ($tend<$now)) { next; }
                   4750:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4751:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4752: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4753:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4754:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4755: 	if ($role eq 'cr') { next; }
1.948     raeburn  4756:         if ($codes) {
                   4757:             if ($section) { $role .= ':'.$section; }
                   4758:             if ($returnhash{$role}) {
                   4759:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4760:             } else {
                   4761:                 $returnhash{$role}=$username.':'.$domain;
                   4762:             }
1.351     www      4763:         } else {
1.988     raeburn  4764:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4765:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4766:             if ($returnhash{$key}) {
                   4767: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4768:             } else {
                   4769:                 $returnhash{$key}=$username.':'.$domain;
                   4770:             }
1.351     www      4771:         }
1.948     raeburn  4772:     }
1.400     www      4773:     return %returnhash;
                   4774: }
                   4775: 
                   4776: sub get_my_roles {
1.937     raeburn  4777:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4778:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4779:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4780:     my (%dumphash,%nothide);
1.1086    raeburn  4781:     if ($context eq 'userroles') {
1.1166    raeburn  4782:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4783:     } else {
1.1219    raeburn  4784:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4785:         if ($hidepriv) {
                   4786:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4787:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4788:                 if ($user !~ /:/) {
                   4789:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4790:                 } else {
                   4791:                     $nothide{$user} = 1;
                   4792:                 }
                   4793:             }
                   4794:         }
1.858     raeburn  4795:     }
1.400     www      4796:     my %returnhash=();
                   4797:     my $now=time;
1.999     raeburn  4798:     my %privileged;
1.800     albertel 4799:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4800:         my ($role,$tend,$tstart);
                   4801:         if ($context eq 'userroles') {
1.1149    raeburn  4802:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4803: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4804:         } else {
                   4805:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4806:         }
1.400     www      4807:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4808:         my $status = 'active';
1.939     raeburn  4809:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4810:             $status = 'previous';
                   4811:         } 
                   4812:         if (($tstart) && ($now<$tstart)) {
                   4813:             $status = 'future';
                   4814:         }
                   4815:         if (ref($types) eq 'ARRAY') {
                   4816:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4817:                 next;
                   4818:             } 
                   4819:         } else {
                   4820:             if ($status ne 'active') {
                   4821:                 next;
                   4822:             }
                   4823:         }
1.867     raeburn  4824:         my ($rolecode,$username,$domain,$section,$area);
                   4825:         if ($context eq 'userroles') {
1.1186    raeburn  4826:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4827:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4828:         } else {
                   4829:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4830:         }
1.832     raeburn  4831:         if (ref($roledoms) eq 'ARRAY') {
                   4832:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4833:                 next;
                   4834:             }
                   4835:         }
                   4836:         if (ref($roles) eq 'ARRAY') {
                   4837:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4838:                 if ($role =~ /^cr\//) {
                   4839:                     if (!grep(/^cr$/,@{$roles})) {
                   4840:                         next;
                   4841:                     }
1.1104    raeburn  4842:                 } elsif ($role =~ /^gr\//) {
                   4843:                     if (!grep(/^gr$/,@{$roles})) {
                   4844:                         next;
                   4845:                     }
1.922     raeburn  4846:                 } else {
                   4847:                     next;
                   4848:                 }
1.832     raeburn  4849:             }
1.867     raeburn  4850:         }
1.937     raeburn  4851:         if ($hidepriv) {
1.1219    raeburn  4852:             my @privroles = ('dc','su');
1.999     raeburn  4853:             if ($context eq 'userroles') {
1.1219    raeburn  4854:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4855:             } else {
1.1219    raeburn  4856:                 my $possdoms = [$domain];
                   4857:                 if (ref($roledoms) eq 'ARRAY') {
                   4858:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4859:                 }
1.1219    raeburn  4860:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4861:                     if (!$nothide{$username.':'.$domain}) {
                   4862:                         next;
                   4863:                     }
                   4864:                 }
1.937     raeburn  4865:             }
                   4866:         }
1.933     raeburn  4867:         if ($withsec) {
                   4868:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4869:                 $tstart.':'.$tend;
                   4870:         } else {
                   4871:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4872:         }
1.832     raeburn  4873:     }
1.373     www      4874:     return %returnhash;
1.399     www      4875: }
                   4876: 
1.1333    raeburn  4877: sub get_all_adhocroles {
                   4878:     my ($dom) = @_;
                   4879:     my @roles_by_num = ();
                   4880:     my %domdefaults = &get_domain_defaults($dom);
                   4881:     my (%description,%access_in_dom,%access_info);
                   4882:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4883:         my $count = 0;
                   4884:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4885:         my %ordered;
                   4886:         foreach my $role (sort(keys(%domcurrent))) {
                   4887:             my ($order,$desc,$access_in_dom);
                   4888:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4889:                 $order = $domcurrent{$role}{'order'};
                   4890:                 $desc = $domcurrent{$role}{'desc'};
                   4891:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4892:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4893:             }
                   4894:             if ($order eq '') {
                   4895:                 $order = $count;
                   4896:             }
                   4897:             $ordered{$order} = $role;
                   4898:             if ($desc ne '') {
                   4899:                 $description{$role} = $desc;
                   4900:             } else {
                   4901:                 $description{$role}= $role;
                   4902:             }
                   4903:             $count++;
                   4904:         }
                   4905:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4906:             push(@roles_by_num,$ordered{$item});
                   4907:         }
                   4908:     }
                   4909:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4910: }
                   4911: 
1.1332    raeburn  4912: sub get_my_adhocroles {
1.1333    raeburn  4913:     my ($cid,$checkreg) = @_;
                   4914:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4915:     if ($env{'request.course.id'} eq $cid) {
                   4916:         $cdom = $env{'course.'.$cid.'.domain'};
                   4917:         $cnum = $env{'course.'.$cid.'.num'};
                   4918:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4919:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4920:         $cdom = $1;
                   4921:         $cnum = $2;
                   4922:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4923:                                      $cdom,$cnum);
                   4924:     }
                   4925:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4926:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4927:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4928:         if ($rosterhash{$user} ne '') {
                   4929:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4930:             return ([],{}) if ($type eq 'auto');
                   4931:         }
                   4932:     }
                   4933:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4934:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4935:             my $then=$env{'user.login.time'};
                   4936:             my $update=$env{'user.update.time'};
1.1335    raeburn  4937:             if (!$update) {
                   4938:                 $update = $then;
                   4939:             }
                   4940:             my @liveroles;
1.1334    raeburn  4941:             foreach my $role ('dh','da') {
                   4942:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4943:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4944:                     my $limit = $update;
                   4945:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4946:                         $limit = $then;
                   4947:                     }
1.1335    raeburn  4948:                     my $activerole = 1;
                   4949:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4950:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4951:                     if ($activerole) {
                   4952:                         push(@liveroles,$role);
                   4953:                     }
1.1334    raeburn  4954:                 }
1.1332    raeburn  4955:             }
1.1335    raeburn  4956:             if (@liveroles) {
1.1332    raeburn  4957:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4958:                     my ($accessref,$accessinfo,%access_in_dom);
                   4959:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4960:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4961:                         if (@{$roles_by_num}) {
1.1332    raeburn  4962:                             my %settings;
                   4963:                             if ($env{'request.course.id'} eq $cid) {
                   4964:                                 foreach my $envkey (keys(%env)) {
                   4965:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4966:                                         $settings{$1} = $env{$envkey};
                   4967:                                     }
                   4968:                                 }
                   4969:                             } else {
                   4970:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4971:                             }
                   4972:                             my %setincrs;
                   4973:                             if ($settings{'internal.adhocaccess'}) {
                   4974:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4975:                             }
                   4976:                             my @statuses;
                   4977:                             if ($env{'environment.inststatus'}) {
                   4978:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4979:                             }
                   4980:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4981:                             if (ref($accessref) eq 'HASH') {
                   4982:                                 %access_in_dom = %{$accessref};
                   4983:                             }
                   4984:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4985:                                 my ($curraccess,@okstatus,@personnel);
                   4986:                                 if ($setincrs{$role}) {
                   4987:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4988:                                     if ($curraccess eq 'status') {
                   4989:                                         @okstatus = split(/\&/,$rest);
                   4990:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4991:                                         @personnel = split(/\&/,$rest);
                   4992:                                     }
                   4993:                                 } else {
                   4994:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4995:                                     if (ref($accessinfo) eq 'HASH') {
                   4996:                                         if ($curraccess eq 'status') {
                   4997:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4998:                                                 @okstatus = @{$accessinfo->{$role}};
                   4999:                                             }
                   5000:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5001:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5002:                                                 @personnel = @{$accessinfo->{$role}};
                   5003:                                             }
1.1332    raeburn  5004:                                         }
                   5005:                                     }
                   5006:                                 }
                   5007:                                 if ($curraccess eq 'none') {
                   5008:                                     next;
                   5009:                                 } elsif ($curraccess eq 'all') {
                   5010:                                     push(@possroles,$role);
1.1336    raeburn  5011:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5012:                                     if (grep(/^dh$/,@liveroles)) {
                   5013:                                         push(@possroles,$role);
                   5014:                                     } else {
                   5015:                                         next;
                   5016:                                     }
1.1336    raeburn  5017:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5018:                                     if (grep(/^da$/,@liveroles)) {
                   5019:                                         push(@possroles,$role);
                   5020:                                     } else {
                   5021:                                         next;
                   5022:                                     }
1.1332    raeburn  5023:                                 } elsif ($curraccess eq 'status') {
                   5024:                                     if (@okstatus) {
                   5025:                                         if (!@statuses) {
                   5026:                                             if (grep(/^default$/,@okstatus)) {
                   5027:                                                 push(@possroles,$role);
                   5028:                                             }
                   5029:                                         } else {
                   5030:                                             foreach my $status (@okstatus) {
                   5031:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5032:                                                     push(@possroles,$role);
                   5033:                                                     last;
                   5034:                                                 }
                   5035:                                             }
                   5036:                                         }
                   5037:                                     }
                   5038:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5039:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5040:                                         if ($curraccess eq 'exc') {
                   5041:                                             push(@possroles,$role);
                   5042:                                         }
                   5043:                                     } elsif ($curraccess eq 'inc') {
                   5044:                                         push(@possroles,$role);
                   5045:                                     }
                   5046:                                 }
                   5047:                             }
                   5048:                         }
                   5049:                     }
                   5050:                 }
                   5051:             }
                   5052:         }
                   5053:     }
1.1333    raeburn  5054:     unless (ref($description) eq 'HASH') {
                   5055:         if (ref($roles_by_num) eq 'ARRAY') {
                   5056:             my %desc;
                   5057:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5058:             $description = \%desc;
                   5059:         } else {
                   5060:             $description = {};
                   5061:         }
                   5062:     }
                   5063:     return (\@possroles,$description);
1.1332    raeburn  5064: }
                   5065: 
1.399     www      5066: # ----------------------------------------------------- Frontpage Announcements
                   5067: #
                   5068: #
                   5069: 
                   5070: sub postannounce {
                   5071:     my ($server,$text)=@_;
1.844     albertel 5072:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5073:     unless ($text=~/\w/) { $text=''; }
                   5074:     return &reply('setannounce:'.&escape($text),$server);
                   5075: }
                   5076: 
                   5077: sub getannounce {
1.448     albertel 5078: 
1.1359    raeburn  5079:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5080: 	my $announcement='';
1.800     albertel 5081: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5082: 	close($fh);
1.399     www      5083: 	if ($announcement=~/\w/) { 
                   5084: 	    return 
                   5085:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5086:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5087: 	} else {
                   5088: 	    return '';
                   5089: 	}
                   5090:     } else {
                   5091: 	return '';
                   5092:     }
1.351     www      5093: }
1.353     www      5094: 
                   5095: # ---------------------------------------------------------- Course ID routines
                   5096: # Deal with domain's nohist_courseid.db files
                   5097: #
                   5098: 
                   5099: sub courseidput {
1.921     raeburn  5100:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5101:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5102:     my $outcome;
                   5103:     if ($caller eq 'timeonly') {
                   5104:         my $cids = '';
                   5105:         foreach my $item (keys(%$storehash)) {
                   5106:             $cids.=&escape($item).'&';
                   5107:         }
                   5108:         $cids=~s/\&$//;
                   5109:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5110:                           $coursehome);       
                   5111:     } else {
                   5112:         my $items = '';
                   5113:         foreach my $item (keys(%$storehash)) {
                   5114:             $items.= &escape($item).'='.
                   5115:                      &freeze_escape($$storehash{$item}).'&';
                   5116:         }
                   5117:         $items=~s/\&$//;
                   5118:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5119:                           $coursehome);
1.918     raeburn  5120:     }
                   5121:     if ($outcome eq 'unknown_cmd') {
                   5122:         my $what;
                   5123:         foreach my $cid (keys(%$storehash)) {
                   5124:             $what .= &escape($cid).'=';
1.921     raeburn  5125:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5126:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5127:             }
                   5128:             $what =~ s/\:$/&/;
                   5129:         }
                   5130:         $what =~ s/\&$//;  
                   5131:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5132:     } else {
                   5133:         return $outcome;
                   5134:     }
1.353     www      5135: }
                   5136: 
                   5137: sub courseiddump {
1.921     raeburn  5138:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5139:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5140:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5141:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5142:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5143:     my $as_hash = 1;
                   5144:     my %returnhash;
                   5145:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5146:     my %libserv = &all_library();
                   5147:     foreach my $tryserver (keys(%libserv)) {
                   5148:         if ( (  $hostidflag == 1 
                   5149: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5150: 	     || (!defined($hostidflag)) ) {
                   5151: 
1.918     raeburn  5152: 	    if (($domfilter eq '') ||
                   5153: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5154:                 my $rep;
                   5155:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5156:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5157:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5158:                                 &escape($descfilter), &escape($instcodefilter), 
                   5159:                                 &escape($ownerfilter), &escape($coursefilter),
                   5160:                                 &escape($typefilter), &escape($regexp_ok), 
                   5161:                                 $as_hash, &escape($selfenrollonly), 
                   5162:                                 &escape($catfilter), $showhidden, $caller, 
                   5163:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5164:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5165:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5166:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5167:                 } else {
                   5168:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5169:                              $sincefilter.':'.&escape($descfilter).':'.
                   5170:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5171:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5172:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5173:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5174:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5175:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5176:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5177:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5178:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5179:                 }
                   5180:                      
1.918     raeburn  5181:                 my @pairs=split(/\&/,$rep);
                   5182:                 foreach my $item (@pairs) {
                   5183:                     my ($key,$value)=split(/\=/,$item,2);
                   5184:                     $key = &unescape($key);
                   5185:                     next if ($key =~ /^error: 2 /);
                   5186:                     my $result = &thaw_unescape($value);
                   5187:                     if (ref($result) eq 'HASH') {
                   5188:                         $returnhash{$key}=$result;
                   5189:                     } else {
1.921     raeburn  5190:                         my @responses = split(/:/,$value);
                   5191:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5192:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5193:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5194:                         }
1.1008    raeburn  5195:                     }
1.353     www      5196:                 }
                   5197:             }
                   5198:         }
                   5199:     }
                   5200:     return %returnhash;
                   5201: }
                   5202: 
1.1055    raeburn  5203: sub courselastaccess {
                   5204:     my ($cdom,$cnum,$hostidref) = @_;
                   5205:     my %returnhash;
                   5206:     if ($cdom && $cnum) {
                   5207:         my $chome = &homeserver($cnum,$cdom);
                   5208:         if ($chome ne 'no_host') {
                   5209:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5210:             &extract_lastaccess(\%returnhash,$rep);
                   5211:         }
                   5212:     } else {
                   5213:         if (!$cdom) { $cdom=''; }
                   5214:         my %libserv = &all_library();
                   5215:         foreach my $tryserver (keys(%libserv)) {
                   5216:             if (ref($hostidref) eq 'ARRAY') {
                   5217:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5218:             } 
                   5219:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5220:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5221:                 &extract_lastaccess(\%returnhash,$rep);
                   5222:             }
                   5223:         }
                   5224:     }
                   5225:     return %returnhash;
                   5226: }
                   5227: 
                   5228: sub extract_lastaccess {
                   5229:     my ($returnhash,$rep) = @_;
                   5230:     if (ref($returnhash) eq 'HASH') {
                   5231:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5232:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5233:                  $rep eq '') {
                   5234:             my @pairs=split(/\&/,$rep);
                   5235:             foreach my $item (@pairs) {
                   5236:                 my ($key,$value)=split(/\=/,$item,2);
                   5237:                 $key = &unescape($key);
                   5238:                 next if ($key =~ /^error: 2 /);
                   5239:                 $returnhash->{$key} = &thaw_unescape($value);
                   5240:             }
                   5241:         }
                   5242:     }
                   5243:     return;
                   5244: }
                   5245: 
1.658     raeburn  5246: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5247: 
                   5248: sub dcmailput {
1.685     raeburn  5249:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5250:     my $status = &Apache::lonnet::critical(
1.740     www      5251:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5252:        &escape($message),$server);
1.662     raeburn  5253:     return $status;
                   5254: }
                   5255: 
1.658     raeburn  5256: sub dcmaildump {
                   5257:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5258:     my %returnhash=();
1.846     albertel 5259: 
                   5260:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5261:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5262:                                                          &escape($enddate).':';
                   5263: 	my @esc_senders=map { &escape($_)} @$senders;
                   5264: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5265: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5266:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5267:             if (($key) && ($value)) {
                   5268:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5269:             }
                   5270:         }
                   5271:     }
                   5272:     return %returnhash;
                   5273: }
1.662     raeburn  5274: # ---------------------------------------------------------- Domain roles
                   5275: 
                   5276: sub get_domain_roles {
                   5277:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5278:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5279:         $startdate = '.';
                   5280:     }
1.1018    raeburn  5281:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5282:         $enddate = '.';
                   5283:     }
1.922     raeburn  5284:     my $rolelist;
                   5285:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5286:         $rolelist = join('&',@{$roles});
1.922     raeburn  5287:     }
1.662     raeburn  5288:     my %personnel = ();
1.841     albertel 5289: 
                   5290:     my %servers = &get_servers($dom,'library');
                   5291:     foreach my $tryserver (keys(%servers)) {
                   5292: 	%{$personnel{$tryserver}}=();
                   5293: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5294: 					    &escape($startdate).':'.
                   5295: 					    &escape($enddate).':'.
                   5296: 					    &escape($rolelist), $tryserver))) {
                   5297: 	    my ($key,$value) = split(/\=/,$line,2);
                   5298: 	    if (($key) && ($value)) {
                   5299: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5300: 	    }
                   5301: 	}
1.662     raeburn  5302:     }
                   5303:     return %personnel;
                   5304: }
1.658     raeburn  5305: 
1.1332    raeburn  5306: sub get_active_domroles {
                   5307:     my ($dom,$roles) = @_;
                   5308:     return () unless (ref($roles) eq 'ARRAY');
                   5309:     my $now = time;
                   5310:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5311:     my %domroles;
                   5312:     foreach my $server (keys(%dompersonnel)) {
                   5313:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5314:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5315:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5316:         }
                   5317:     }
                   5318:     return %domroles;
                   5319: }
                   5320: 
1.1057    www      5321: # ----------------------------------------------------------- Interval timing 
1.149     www      5322: 
1.1153    www      5323: {
                   5324: # Caches needed for speedup of navmaps
                   5325: # We don't want to cache this for very long at all (5 seconds at most)
                   5326: # 
                   5327: # The user for whom we cache
                   5328: my $cachedkey='';
                   5329: # The cached times for this user
                   5330: my %cachedtimes=();
                   5331: # When this was last done
1.1282    raeburn  5332: my $cachedtime='';
1.1153    www      5333: 
                   5334: sub load_all_first_access {
1.1308    raeburn  5335:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5336:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5337:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5338:         (!$ignorecache)) {
1.1154    raeburn  5339:         return;
                   5340:     }
                   5341:     $cachedtime=time;
                   5342:     $cachedkey=$uname.':'.$udom;
                   5343:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5344: }
                   5345: 
1.504     albertel 5346: sub get_first_access {
1.1308    raeburn  5347:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5348:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5349:     if ($argsymb) { $symb=$argsymb; }
                   5350:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5351:     if ($argmap) { $map = $argmap; }
1.926     albertel 5352:     if ($type eq 'course') {
                   5353: 	$res='course';
                   5354:     } elsif ($type eq 'map') {
1.588     albertel 5355: 	$res=&symbread($map);
                   5356:     } else {
                   5357: 	$res=$symb;
                   5358:     }
1.1308    raeburn  5359:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5360:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5361: }
                   5362: 
                   5363: sub set_first_access {
1.1162    raeburn  5364:     my ($type,$interval)=@_;
1.790     albertel 5365:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5366:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5367:     if ($type eq 'course') {
                   5368: 	$res='course';
                   5369:     } elsif ($type eq 'map') {
1.588     albertel 5370: 	$res=&symbread($map);
                   5371:     } else {
                   5372: 	$res=$symb;
                   5373:     }
1.1153    www      5374:     $cachedkey='';
1.1162    raeburn  5375:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5376:     if ($firstaccess) {
                   5377:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5378:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5379:                  "in $courseid");
1.1386    raeburn  5380:         return 'already_set';
                   5381:     } else {
1.1162    raeburn  5382:         my $start = time;
                   5383: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5384:                           $udom,$uname);
                   5385:         if ($putres eq 'ok') {
                   5386:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5387:                  $udom,$uname); 
                   5388:             &appenv(
                   5389:                      {
                   5390:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5391:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5392:                      }
                   5393:                   );
1.1365    raeburn  5394:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5395:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5396:             }
1.1386    raeburn  5397:         } elsif ($putres ne 'refused') {
                   5398:             &logthis("Result: $putres when attempting to set first access time ".
                   5399:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5400:         }
                   5401:         return $putres;
1.505     albertel 5402:     }
                   5403:     return 'already_set';
1.504     albertel 5404: }
1.1153    www      5405: }
1.1282    raeburn  5406: 
1.110     www      5407: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5408: 
                   5409: sub expirespread {
                   5410:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5411:     my $cid=$env{'request.course.id'}; 
1.110     www      5412:     if ($cid) {
                   5413:        my $now=time;
                   5414:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5415:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5416:                             $env{'course.'.$cid.'.num'}.
1.110     www      5417: 	        	    ':nohist_expirationdates:'.
                   5418:                             &escape($key).'='.$now,
1.620     albertel 5419:                             $env{'course.'.$cid.'.home'})
1.110     www      5420:     }
                   5421:     return 'ok';
1.14      www      5422: }
                   5423: 
1.109     www      5424: # ----------------------------------------------------- Devalidate Spreadsheets
                   5425: 
                   5426: sub devalidate {
1.325     www      5427:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5428:     my $cid=$env{'request.course.id'}; 
1.109     www      5429:     if ($cid) {
1.391     matthew  5430:         # delete the stored spreadsheets for
                   5431:         # - the student level sheet of this user in course's homespace
                   5432:         # - the assessment level sheet for this resource 
                   5433:         #   for this user in user's homespace
1.553     albertel 5434: 	# - current conditional state info
1.325     www      5435: 	my $key=$uname.':'.$udom.':';
1.109     www      5436:         my $status=
1.299     matthew  5437: 	    &del('nohist_calculatedsheets',
1.391     matthew  5438: 		 [$key.'studentcalc:'],
1.620     albertel 5439: 		 $env{'course.'.$cid.'.domain'},
                   5440: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5441: 		.' '.
                   5442: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5443: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5444:         unless ($status eq 'ok ok') {
                   5445:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5446:                     $uname.' at '.$udom.' for '.
1.109     www      5447: 		    $symb.': '.$status);
1.133     albertel 5448:         }
1.553     albertel 5449: 	&delenv('user.state.'.$cid);
1.109     www      5450:     }
                   5451: }
                   5452: 
1.265     albertel 5453: sub get_scalar {
                   5454:     my ($string,$end) = @_;
                   5455:     my $value;
                   5456:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5457: 	$value = $1;
                   5458:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5459: 	$value = $1;
                   5460:     }
                   5461:     return &unescape($value);
                   5462: }
                   5463: 
                   5464: sub array2str {
                   5465:   my (@array) = @_;
                   5466:   my $result=&arrayref2str(\@array);
                   5467:   $result=~s/^__ARRAY_REF__//;
                   5468:   $result=~s/__END_ARRAY_REF__$//;
                   5469:   return $result;
                   5470: }
                   5471: 
1.204     albertel 5472: sub arrayref2str {
                   5473:   my ($arrayref) = @_;
1.265     albertel 5474:   my $result='__ARRAY_REF__';
1.204     albertel 5475:   foreach my $elem (@$arrayref) {
1.265     albertel 5476:     if(ref($elem) eq 'ARRAY') {
                   5477:       $result.=&arrayref2str($elem).'&';
                   5478:     } elsif(ref($elem) eq 'HASH') {
                   5479:       $result.=&hashref2str($elem).'&';
                   5480:     } elsif(ref($elem)) {
                   5481:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5482:     } else {
                   5483:       $result.=&escape($elem).'&';
                   5484:     }
                   5485:   }
                   5486:   $result=~s/\&$//;
1.265     albertel 5487:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5488:   return $result;
                   5489: }
                   5490: 
1.168     albertel 5491: sub hash2str {
1.204     albertel 5492:   my (%hash) = @_;
                   5493:   my $result=&hashref2str(\%hash);
1.265     albertel 5494:   $result=~s/^__HASH_REF__//;
                   5495:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5496:   return $result;
                   5497: }
                   5498: 
                   5499: sub hashref2str {
                   5500:   my ($hashref)=@_;
1.265     albertel 5501:   my $result='__HASH_REF__';
1.800     albertel 5502:   foreach my $key (sort(keys(%$hashref))) {
                   5503:     if (ref($key) eq 'ARRAY') {
                   5504:       $result.=&arrayref2str($key).'=';
                   5505:     } elsif (ref($key) eq 'HASH') {
                   5506:       $result.=&hashref2str($key).'=';
                   5507:     } elsif (ref($key)) {
1.265     albertel 5508:       $result.='=';
1.800     albertel 5509:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5510:     } else {
1.1132    raeburn  5511: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5512:     }
                   5513: 
1.800     albertel 5514:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5515:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5516:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5517:       $result.=&hashref2str($hashref->{$key}).'&';
                   5518:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5519:        $result.='&';
1.800     albertel 5520:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5521:     } else {
1.800     albertel 5522:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5523:     }
                   5524:   }
1.168     albertel 5525:   $result=~s/\&$//;
1.265     albertel 5526:   $result .= '__END_HASH_REF__';
1.168     albertel 5527:   return $result;
                   5528: }
                   5529: 
                   5530: sub str2hash {
1.265     albertel 5531:     my ($string)=@_;
                   5532:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5533:     return %$hash;
                   5534: }
                   5535: 
                   5536: sub str2hashref {
1.168     albertel 5537:   my ($string) = @_;
1.265     albertel 5538: 
                   5539:   my %hash;
                   5540: 
                   5541:   if($string !~ /^__HASH_REF__/) {
                   5542:       if (! ($string eq '' || !defined($string))) {
                   5543: 	  $hash{'error'}='Not hash reference';
                   5544:       }
                   5545:       return (\%hash, $string);
                   5546:   }
                   5547: 
                   5548:   $string =~ s/^__HASH_REF__//;
                   5549: 
                   5550:   while($string !~ /^__END_HASH_REF__/) {
                   5551:       #key
                   5552:       my $key='';
                   5553:       if($string =~ /^__HASH_REF__/) {
                   5554:           ($key, $string)=&str2hashref($string);
                   5555:           if(defined($key->{'error'})) {
                   5556:               $hash{'error'}='Bad data';
                   5557:               return (\%hash, $string);
                   5558:           }
                   5559:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5560:           ($key, $string)=&str2arrayref($string);
                   5561:           if($key->[0] eq 'Array reference error') {
                   5562:               $hash{'error'}='Bad data';
                   5563:               return (\%hash, $string);
                   5564:           }
                   5565:       } else {
                   5566:           $string =~ s/^(.*?)=//;
1.267     albertel 5567: 	  $key=&unescape($1);
1.265     albertel 5568:       }
                   5569:       $string =~ s/^=//;
                   5570: 
                   5571:       #value
                   5572:       my $value='';
                   5573:       if($string =~ /^__HASH_REF__/) {
                   5574:           ($value, $string)=&str2hashref($string);
                   5575:           if(defined($value->{'error'})) {
                   5576:               $hash{'error'}='Bad data';
                   5577:               return (\%hash, $string);
                   5578:           }
                   5579:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5580:           ($value, $string)=&str2arrayref($string);
                   5581:           if($value->[0] eq 'Array reference error') {
                   5582:               $hash{'error'}='Bad data';
                   5583:               return (\%hash, $string);
                   5584:           }
                   5585:       } else {
                   5586: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5587:       }
                   5588:       $string =~ s/^&//;
                   5589: 
                   5590:       $hash{$key}=$value;
1.204     albertel 5591:   }
1.265     albertel 5592: 
                   5593:   $string =~ s/^__END_HASH_REF__//;
                   5594: 
                   5595:   return (\%hash, $string);
1.204     albertel 5596: }
                   5597: 
                   5598: sub str2array {
1.265     albertel 5599:     my ($string)=@_;
                   5600:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5601:     return @$array;
                   5602: }
                   5603: 
                   5604: sub str2arrayref {
1.204     albertel 5605:   my ($string) = @_;
1.265     albertel 5606:   my @array;
                   5607: 
                   5608:   if($string !~ /^__ARRAY_REF__/) {
                   5609:       if (! ($string eq '' || !defined($string))) {
                   5610: 	  $array[0]='Array reference error';
                   5611:       }
                   5612:       return (\@array, $string);
                   5613:   }
                   5614: 
                   5615:   $string =~ s/^__ARRAY_REF__//;
                   5616: 
                   5617:   while($string !~ /^__END_ARRAY_REF__/) {
                   5618:       my $value='';
                   5619:       if($string =~ /^__HASH_REF__/) {
                   5620:           ($value, $string)=&str2hashref($string);
                   5621:           if(defined($value->{'error'})) {
                   5622:               $array[0] ='Array reference error';
                   5623:               return (\@array, $string);
                   5624:           }
                   5625:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5626:           ($value, $string)=&str2arrayref($string);
                   5627:           if($value->[0] eq 'Array reference error') {
                   5628:               $array[0] ='Array reference error';
                   5629:               return (\@array, $string);
                   5630:           }
                   5631:       } else {
                   5632: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5633:       }
                   5634:       $string =~ s/^&//;
                   5635: 
                   5636:       push(@array, $value);
1.191     harris41 5637:   }
1.265     albertel 5638: 
                   5639:   $string =~ s/^__END_ARRAY_REF__//;
                   5640: 
                   5641:   return (\@array, $string);
1.168     albertel 5642: }
                   5643: 
1.167     albertel 5644: # -------------------------------------------------------------------Temp Store
                   5645: 
1.168     albertel 5646: sub tmpreset {
                   5647:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5648:   if (!$symb) {
                   5649:     $symb=&symbread();
1.620     albertel 5650:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5651:   }
                   5652:   $symb=escape($symb);
                   5653: 
1.620     albertel 5654:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5655:   $namespace=~s/\//\_/g;
                   5656:   $namespace=~s/\W//g;
                   5657: 
1.620     albertel 5658:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5659:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5660:   if ($domain eq 'public' && $stuname eq 'public') {
                   5661:       $stuname=$ENV{'REMOTE_ADDR'};
                   5662:   }
1.1117    foxr     5663:   my $path=LONCAPA::tempdir();
1.168     albertel 5664:   my %hash;
                   5665:   if (tie(%hash,'GDBM_File',
                   5666: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5667: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5668:     foreach my $key (keys(%hash)) {
1.180     albertel 5669:       if ($key=~ /:$symb/) {
1.168     albertel 5670: 	delete($hash{$key});
                   5671:       }
                   5672:     }
                   5673:   }
                   5674: }
                   5675: 
1.167     albertel 5676: sub tmpstore {
1.168     albertel 5677:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5678: 
                   5679:   if (!$symb) {
                   5680:     $symb=&symbread();
1.620     albertel 5681:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5682:   }
                   5683:   $symb=escape($symb);
                   5684: 
                   5685:   if (!$namespace) {
                   5686:     # I don't think we would ever want to store this for a course.
                   5687:     # it seems this will only be used if we don't have a course.
1.620     albertel 5688:     #$namespace=$env{'request.course.id'};
1.168     albertel 5689:     #if (!$namespace) {
1.620     albertel 5690:       $namespace=$env{'request.state'};
1.168     albertel 5691:     #}
                   5692:   }
                   5693:   $namespace=~s/\//\_/g;
                   5694:   $namespace=~s/\W//g;
1.620     albertel 5695:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5696:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5697:   if ($domain eq 'public' && $stuname eq 'public') {
                   5698:       $stuname=$ENV{'REMOTE_ADDR'};
                   5699:   }
1.168     albertel 5700:   my $now=time;
                   5701:   my %hash;
1.1117    foxr     5702:   my $path=LONCAPA::tempdir();
1.168     albertel 5703:   if (tie(%hash,'GDBM_File',
                   5704: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5705: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5706:     $hash{"version:$symb"}++;
                   5707:     my $version=$hash{"version:$symb"};
                   5708:     my $allkeys=''; 
                   5709:     foreach my $key (keys(%$storehash)) {
                   5710:       $allkeys.=$key.':';
1.591     albertel 5711:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5712:     }
                   5713:     $hash{"$version:$symb:timestamp"}=$now;
                   5714:     $allkeys.='timestamp';
                   5715:     $hash{"$version:keys:$symb"}=$allkeys;
                   5716:     if (untie(%hash)) {
                   5717:       return 'ok';
                   5718:     } else {
                   5719:       return "error:$!";
                   5720:     }
                   5721:   } else {
                   5722:     return "error:$!";
                   5723:   }
                   5724: }
1.167     albertel 5725: 
1.168     albertel 5726: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5727: 
1.168     albertel 5728: sub tmprestore {
                   5729:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5730: 
1.168     albertel 5731:   if (!$symb) {
                   5732:     $symb=&symbread();
1.620     albertel 5733:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5734:   }
                   5735:   $symb=escape($symb);
                   5736: 
1.620     albertel 5737:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5738: 
1.620     albertel 5739:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5740:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5741:   if ($domain eq 'public' && $stuname eq 'public') {
                   5742:       $stuname=$ENV{'REMOTE_ADDR'};
                   5743:   }
1.168     albertel 5744:   my %returnhash;
                   5745:   $namespace=~s/\//\_/g;
                   5746:   $namespace=~s/\W//g;
                   5747:   my %hash;
1.1117    foxr     5748:   my $path=LONCAPA::tempdir();
1.168     albertel 5749:   if (tie(%hash,'GDBM_File',
                   5750: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5751: 	  &GDBM_READER(),0640)) {
1.168     albertel 5752:     my $version=$hash{"version:$symb"};
                   5753:     $returnhash{'version'}=$version;
                   5754:     my $scope;
                   5755:     for ($scope=1;$scope<=$version;$scope++) {
                   5756:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5757:       my @keys=split(/:/,$vkeys);
                   5758:       my $key;
                   5759:       $returnhash{"$scope:keys"}=$vkeys;
                   5760:       foreach $key (@keys) {
1.591     albertel 5761: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5762: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5763:       }
                   5764:     }
1.168     albertel 5765:     if (!(untie(%hash))) {
                   5766:       return "error:$!";
                   5767:     }
                   5768:   } else {
                   5769:     return "error:$!";
                   5770:   }
                   5771:   return %returnhash;
1.167     albertel 5772: }
                   5773: 
1.9       www      5774: # ----------------------------------------------------------------------- Store
                   5775: 
                   5776: sub store {
1.1269    raeburn  5777:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5778:     my $home='';
                   5779: 
1.168     albertel 5780:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5781: 
1.213     www      5782:     $symb=&symbclean($symb);
1.122     albertel 5783:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5784: 
1.620     albertel 5785:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5786:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5787: 
                   5788:     &devalidate($symb,$stuname,$domain);
1.109     www      5789: 
                   5790:     $symb=escape($symb);
1.187     www      5791:     if (!$namespace) { 
1.620     albertel 5792:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5793:           return ''; 
                   5794:        } 
                   5795:     }
1.620     albertel 5796:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5797: 
                   5798:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5799:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5800: 
1.12      www      5801:     my $namevalue='';
1.800     albertel 5802:     foreach my $key (keys(%$storehash)) {
                   5803:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5804:     }
1.12      www      5805:     $namevalue=~s/\&$//;
1.187     www      5806:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5807:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5808: }
                   5809: 
1.47      www      5810: # -------------------------------------------------------------- Critical Store
                   5811: 
                   5812: sub cstore {
1.1269    raeburn  5813:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5814:     my $home='';
                   5815: 
1.168     albertel 5816:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5817: 
1.213     www      5818:     $symb=&symbclean($symb);
1.122     albertel 5819:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5820: 
1.620     albertel 5821:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5822:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5823: 
                   5824:     &devalidate($symb,$stuname,$domain);
1.109     www      5825: 
                   5826:     $symb=escape($symb);
1.187     www      5827:     if (!$namespace) { 
1.620     albertel 5828:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5829:           return ''; 
                   5830:        } 
                   5831:     }
1.620     albertel 5832:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5833: 
                   5834:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5835:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5836: 
1.47      www      5837:     my $namevalue='';
1.800     albertel 5838:     foreach my $key (keys(%$storehash)) {
                   5839:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5840:     }
1.47      www      5841:     $namevalue=~s/\&$//;
1.187     www      5842:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5843:     return critical
1.1269    raeburn  5844:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5845: }
                   5846: 
1.9       www      5847: # --------------------------------------------------------------------- Restore
                   5848: 
                   5849: sub restore {
1.124     www      5850:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5851:     my $home='';
                   5852: 
1.168     albertel 5853:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5854: 
1.122     albertel 5855:     if (!$symb) {
1.1224    raeburn  5856:         return if ($namespace eq 'courserequests');
                   5857:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5858:     } else {
1.1224    raeburn  5859:         unless ($namespace eq 'courserequests') {
                   5860:             $symb=&escape(&symbclean($symb));
                   5861:         }
1.122     albertel 5862:     }
1.188     www      5863:     if (!$namespace) { 
1.620     albertel 5864:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5865:           return ''; 
                   5866:        } 
                   5867:     }
1.620     albertel 5868:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5869:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5870:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5871:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5872: 
1.12      www      5873:     my %returnhash=();
1.800     albertel 5874:     foreach my $line (split(/\&/,$answer)) {
                   5875: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5876:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5877:     }
1.75      www      5878:     my $version;
                   5879:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5880:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5881:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5882:        }
1.75      www      5883:     }
1.13      www      5884:     return %returnhash;
1.34      www      5885: }
                   5886: 
                   5887: # ---------------------------------------------------------- Course Description
1.1118    foxr     5888: #
                   5889: #  
1.34      www      5890: 
                   5891: sub coursedescription {
1.731     albertel 5892:     my ($courseid,$args)=@_;
1.34      www      5893:     $courseid=~s/^\///;
1.49      www      5894:     $courseid=~s/\_/\//g;
1.34      www      5895:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5896:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5897:     my $normalid=$cdomain.'_'.$cnum;
                   5898:     # need to always cache even if we get errors otherwise we keep 
                   5899:     # trying and trying and trying to get the course description.
                   5900:     my %envhash=();
                   5901:     my %returnhash=();
1.731     albertel 5902:     
                   5903:     my $expiretime=600;
                   5904:     if ($env{'request.course.id'} eq $normalid) {
                   5905: 	$expiretime=120;
                   5906:     }
                   5907: 
                   5908:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5909:     if (!$args->{'freshen_cache'}
                   5910: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5911: 	foreach my $key (keys(%env)) {
                   5912: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5913: 	    my ($setting) = $1;
                   5914: 	    $returnhash{$setting} = $env{$key};
                   5915: 	}
                   5916: 	return %returnhash;
                   5917:     }
                   5918: 
1.1118    foxr     5919:     # get the data again
                   5920: 
1.731     albertel 5921:     if (!$args->{'one_time'}) {
                   5922: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5923:     }
1.811     albertel 5924: 
1.34      www      5925:     if ($chome ne 'no_host') {
1.302     albertel 5926:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5927:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5928: 	   my $username = $env{'user.name'}; # Defult username
                   5929: 	   if(defined $args->{'user'}) {
                   5930: 	       $username = $args->{'user'};
                   5931: 	   }
1.129     albertel 5932:            $returnhash{'home'}= $chome;
                   5933: 	   $returnhash{'domain'} = $cdomain;
                   5934: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5935:            if (!defined($returnhash{'type'})) {
                   5936:                $returnhash{'type'} = 'Course';
                   5937:            }
1.130     albertel 5938:            while (my ($name,$value) = each %returnhash) {
1.53      www      5939:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5940:            }
1.270     www      5941:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5942:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5943: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5944:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5945:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5946:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5947:        }
                   5948:     }
1.731     albertel 5949:     if (!$args->{'one_time'}) {
1.949     raeburn  5950: 	&appenv(\%envhash);
1.731     albertel 5951:     }
1.302     albertel 5952:     return %returnhash;
1.461     www      5953: }
                   5954: 
1.1080    raeburn  5955: sub update_released_required {
                   5956:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5957:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5958:         $cid = $env{'request.course.id'};
                   5959:         $cdom = $env{'course.'.$cid.'.domain'};
                   5960:         $cnum = $env{'course.'.$cid.'.num'};
                   5961:         $chome = $env{'course.'.$cid.'.home'};
                   5962:     }
                   5963:     if ($needsrelease) {
                   5964:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5965:         my $needsupdate;
                   5966:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5967:             $needsupdate = 1;
                   5968:         } else {
                   5969:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5970:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5971:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5972:                 $needsupdate = 1;
                   5973:             }
                   5974:         }
                   5975:         if ($needsupdate) {
                   5976:             my %needshash = (
                   5977:                              'internal.releaserequired' => $needsrelease,
                   5978:                             );
                   5979:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5980:             if ($putresult eq 'ok') {
                   5981:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5982:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5983:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5984:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5985:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5986:                 }
                   5987:             }
                   5988:         }
                   5989:     }
                   5990:     return;
                   5991: }
                   5992: 
1.461     www      5993: # -------------------------------------------------See if a user is privileged
                   5994: 
                   5995: sub privileged {
1.1219    raeburn  5996:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5997:     my $now = time;
1.1219    raeburn  5998:     my $roles;
                   5999:     if (ref($possroles) eq 'ARRAY') {
                   6000:         $roles = $possroles; 
                   6001:     } else {
                   6002:         $roles = ['dc','su'];
                   6003:     }
                   6004:     if (ref($possdomains) eq 'ARRAY') {
                   6005:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6006:         foreach my $dom (@{$possdomains}) {
                   6007:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6008:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6009:                 foreach my $role (@{$roles}) {
                   6010:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6011:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6012:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6013:                             return 1 unless (($end && $end < $now) ||
                   6014:                                              ($start && $start > $now));
                   6015:                         }
                   6016:                     }
                   6017:                 }
                   6018:             }
                   6019:         }
                   6020:     } else {
                   6021:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6022:         my $now = time;
1.1170    droeschl 6023: 
1.1275    musolffc 6024:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6025:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6026:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6027:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6028:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6029:             }
1.1219    raeburn  6030:         }
                   6031:     }
                   6032:     return 0;
                   6033: }
1.1170    droeschl 6034: 
1.1219    raeburn  6035: sub privileged_by_domain {
                   6036:     my ($domains,$roles) = @_;
                   6037:     my %privileged = ();
                   6038:     my $cachetime = 60*60*24;
                   6039:     my $now = time;
                   6040:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6041:         return %privileged;
                   6042:     }
                   6043:     foreach my $dom (@{$domains}) {
                   6044:         next if (ref($privileged{$dom}) eq 'HASH');
                   6045:         my $needroles;
                   6046:         foreach my $role (@{$roles}) {
                   6047:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6048:             if (defined($cached)) {
                   6049:                 if (ref($result) eq 'HASH') {
                   6050:                     $privileged{$dom}{$role} = $result;
                   6051:                 }
                   6052:             } else {
                   6053:                 $needroles = 1;
                   6054:             }
                   6055:         }
                   6056:         if ($needroles) {
                   6057:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6058:             $privileged{$dom} = {};
                   6059:             foreach my $server (keys(%dompersonnel)) {
                   6060:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6061:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6062:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6063:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6064:                         next if ($end && $end < $now);
                   6065:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6066:                             $dompersonnel{$server}{$item};
                   6067:                     }
                   6068:                 }
                   6069:             }
                   6070:             if (ref($privileged{$dom}) eq 'HASH') {
                   6071:                 foreach my $role (@{$roles}) {
                   6072:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6073:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6074:                     } else {
                   6075:                         my %hash = ();
                   6076:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6077:                     }
                   6078:                 }
                   6079:             }
                   6080:         }
                   6081:     }
                   6082:     return %privileged;
1.9       www      6083: }
1.1       albertel 6084: 
1.103     harris41 6085: # -------------------------------------------------------- Get user privileges
1.11      www      6086: 
                   6087: sub rolesinit {
1.1169    droeschl 6088:     my ($domain, $username) = @_;
                   6089:     my %userroles = ('user.login.time' => time);
                   6090:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6091: 
                   6092:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6093:     # also, blocking can be triggered by an activating timer
                   6094:     # it's saved in the user's %env.
                   6095:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6096:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6097:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6098:         %timerintchk, %timerintenv);
                   6099: 
1.1162    raeburn  6100:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6101:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6102:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6103:     }
1.1169    droeschl 6104: 
1.1162    raeburn  6105:     foreach my $key (keys(%timerinterval)) {
                   6106:         my ($cid,$rest) = split(/\0/,$key);
                   6107:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6108:     }
1.1169    droeschl 6109: 
1.11      www      6110:     my %allroles=();
1.1162    raeburn  6111:     my %allgroups=();
1.11      www      6112: 
1.1274    raeburn  6113:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6114:         my $role = $rolesdump{$area};
                   6115:         $area =~ s/\_\w\w$//;
                   6116: 
                   6117:         my ($trole, $tend, $tstart, $group_privs);
                   6118: 
                   6119:         if ($role =~ /^cr/) {
                   6120:         # Custom role, defined by a user 
                   6121:         # e.g., user.role.cr/msu/smith/mynewrole
                   6122:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6123:                 $trole = $1;
                   6124:                 ($tend, $tstart) = split('_', $2);
                   6125:             } else {
                   6126:                 $trole = $role;
                   6127:             }
                   6128:         } elsif ($role =~ m|^gr/|) {
                   6129:         # Role of member in a group, defined within a course/community
                   6130:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6131:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6132:             next if $tstart eq '-1';
                   6133:             ($trole, $group_privs) = split(/\//, $trole);
                   6134:             $group_privs = &unescape($group_privs);
                   6135:         } else {
                   6136:         # Just a normal role, defined in roles.tab
                   6137:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6138:         }
                   6139: 
                   6140:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6141:                  $username);
                   6142:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6143: 
                   6144:         # role expired or not available yet?
                   6145:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6146:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6147: 
                   6148:         next if $area eq '' or $trole eq '';
                   6149: 
                   6150:         my $spec = "$trole.$area";
                   6151:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6152: 
                   6153:         if ($trole =~ /^cr\//) {
                   6154:         # Custom role, defined by a user
                   6155:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6156:         } elsif ($trole eq 'gr') {
                   6157:         # Role of a member in a group, defined within a course/community
                   6158:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6159:             next;
                   6160:         } else {
                   6161:         # Normal role, defined in roles.tab
                   6162:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6163:         }
                   6164: 
                   6165:         my $cid = $tdomain.'_'.$trest;
                   6166:         unless ($firstaccchk{$cid}) {
                   6167:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6168:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6169:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6170:                         $coursetimerstarts{$cid}{$item}; 
                   6171:                 }
                   6172:             }
                   6173:             $firstaccchk{$cid} = 1;
                   6174:         }
                   6175:         unless ($timerintchk{$cid}) {
                   6176:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6177:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6178:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6179:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6180:                 }
1.12      www      6181:             }
1.1169    droeschl 6182:             $timerintchk{$cid} = 1;
1.191     harris41 6183:         }
1.11      www      6184:     }
1.1169    droeschl 6185: 
1.1341    raeburn  6186:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6187:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6188:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6189:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6190: 
1.1162    raeburn  6191:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6192: }
                   6193: 
1.567     raeburn  6194: sub set_arearole {
1.1215    raeburn  6195:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6196:     unless ($nolog) {
1.567     raeburn  6197: # log the associated role with the area
1.1215    raeburn  6198:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6199:     }
1.743     albertel 6200:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6201: }
                   6202: 
                   6203: sub custom_roleprivs {
                   6204:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6205:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6206:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6207:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6208:         my ($rdummy,$roledef)=
                   6209:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6210:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6211:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6212:             if (defined($syspriv)) {
1.1043    raeburn  6213:                 if ($trest =~ /^$match_community$/) {
                   6214:                     $syspriv =~ s/bre\&S//; 
                   6215:                 }
1.567     raeburn  6216:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6217:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6218:             }
                   6219:             if ($tdomain ne '') {
                   6220:                 if (defined($dompriv)) {
                   6221:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6222:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6223:                 }
                   6224:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6225:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6226:                         my $rolename = $1;
                   6227:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6228:                     }
1.567     raeburn  6229:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6230:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6231:                 }
                   6232:             }
                   6233:         }
                   6234:     }
                   6235: }
                   6236: 
1.1332    raeburn  6237: sub course_adhocrole_privs {
                   6238:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6239:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6240:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6241:         my (%currprivs,%storeprivs);
                   6242:         foreach my $item (split(/:/,$coursepriv)) {
                   6243:             my ($priv,$restrict) = split(/\&/,$item);
                   6244:             $currprivs{$priv} = $restrict;
                   6245:         }
                   6246:         my (%possadd,%possremove,%full);
                   6247:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6248:             my ($priv,$restrict)=split(/\&/,$item);
                   6249:             $full{$priv} = $restrict;
                   6250:         }
                   6251:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6252:              next if ($item eq '');
                   6253:              my ($rule,$rest) = split(/=/,$item);
                   6254:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6255:              foreach my $priv (split(/:/,$rest)) {
                   6256:                  if ($priv ne '') {
                   6257:                      if ($rule eq 'off') {
                   6258:                          $possremove{$priv} = 1;
                   6259:                      } else {
                   6260:                          $possadd{$priv} = 1;
                   6261:                      }
                   6262:                  }
                   6263:              }
                   6264:          }
                   6265:          foreach my $priv (sort(keys(%full))) {
                   6266:              if (exists($currprivs{$priv})) {
                   6267:                  unless (exists($possremove{$priv})) {
                   6268:                      $storeprivs{$priv} = $currprivs{$priv};
                   6269:                  }
                   6270:              } elsif (exists($possadd{$priv})) {
                   6271:                  $storeprivs{$priv} = $full{$priv};
                   6272:              }
                   6273:          }
                   6274:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6275:      }
                   6276:      return $coursepriv;
                   6277: }
                   6278: 
1.678     raeburn  6279: sub group_roleprivs {
                   6280:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6281:     my $access = 1;
                   6282:     my $now = time;
                   6283:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6284:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6285:     if ($access) {
1.811     albertel 6286:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6287:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6288:     }
                   6289: }
1.567     raeburn  6290: 
                   6291: sub standard_roleprivs {
                   6292:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6293:     if (defined($pr{$trole.':s'})) {
                   6294:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6295:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6296:     }
                   6297:     if ($tdomain ne '') {
                   6298:         if (defined($pr{$trole.':d'})) {
                   6299:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6300:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6301:         }
                   6302:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6303:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6304:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6305:         }
                   6306:     }
                   6307: }
                   6308: 
                   6309: sub set_userprivs {
1.1064    raeburn  6310:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6311:     my $author=0;
                   6312:     my $adv=0;
1.1341    raeburn  6313:     my $rar=0;
1.678     raeburn  6314:     my %grouproles = ();
                   6315:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6316:         my @groupkeys; 
1.1000    raeburn  6317:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6318:             push(@groupkeys,$role);
                   6319:         }
                   6320:         if (ref($groups_roles) eq 'HASH') {
                   6321:             foreach my $key (keys(%{$groups_roles})) {
                   6322:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6323:                     push(@groupkeys,$key);
                   6324:                 }
                   6325:             }
                   6326:         }
                   6327:         if (@groupkeys > 0) {
                   6328:             foreach my $role (@groupkeys) {
                   6329:                 my ($trole,$area,$sec,$extendedarea);
                   6330:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6331:                     $trole = $1;
                   6332:                     $area = $2;
                   6333:                     $sec = $3;
                   6334:                     $extendedarea = $area.$sec;
                   6335:                     if (exists($$allgroups{$area})) {
                   6336:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6337:                             my $spec = $trole.'.'.$extendedarea;
                   6338:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6339:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6340:                         }
1.678     raeburn  6341:                     }
                   6342:                 }
                   6343:             }
                   6344:         }
                   6345:     }
1.800     albertel 6346:     foreach my $group (keys(%grouproles)) {
                   6347:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6348:     }
1.800     albertel 6349:     foreach my $role (keys(%{$allroles})) {
                   6350:         my %thesepriv;
1.941     raeburn  6351:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6352:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6353:             if ($item ne '') {
                   6354:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6355:                 if ($restrictions eq '') {
                   6356:                     $thesepriv{$privilege}='F';
                   6357:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6358:                     $thesepriv{$privilege}.=$restrictions;
                   6359:                 }
                   6360:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6361:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6362:             }
                   6363:         }
                   6364:         my $thesestr='';
1.1104    raeburn  6365:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6366: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6367: 	}
                   6368:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6369:     }
1.1341    raeburn  6370:     return ($author,$adv,$rar);
1.567     raeburn  6371: }
                   6372: 
1.994     raeburn  6373: sub role_status {
1.1104    raeburn  6374:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6375:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6376:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6377:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6378:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6379:             $$where = '/'.$two;
1.994     raeburn  6380:             $$trolecode=$$role.'.'.$$where;
                   6381:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6382:             $$tstatus='is';
1.1104    raeburn  6383:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6384:                 $$tstatus='future';
1.1034    raeburn  6385:                 if ($$tstart<$now) {
                   6386:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6387:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6388:                             my (%allroles,%allgroups,$group_privs,
                   6389:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6390:                             my %userroles = (
                   6391:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6392:                             );
1.1064    raeburn  6393:                             @rolecodes = ('cm'); 
1.1002    raeburn  6394:                             my $spec=$$role.'.'.$$where;
                   6395:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6396:                             if ($$role =~ /^cr\//) {
                   6397:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6398:                                 push(@rolecodes,'cr');
1.1002    raeburn  6399:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6400:                                 push(@rolecodes,$$role);
1.1002    raeburn  6401:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6402:                                                     $env{'user.name'});
1.1064    raeburn  6403:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6404:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6405:                                 $group_privs = &unescape($group_privs);
                   6406:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6407:                                 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  6408:                                 &get_groups_roles($tdomain,$trest,
                   6409:                                                   \%course_roles,\@rolecodes,
                   6410:                                                   \%groups_roles);
1.1002    raeburn  6411:                             } else {
1.1064    raeburn  6412:                                 push(@rolecodes,$$role);
1.1002    raeburn  6413:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6414:                             }
1.1341    raeburn  6415:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6416:                                                                    \%groups_roles);
1.1064    raeburn  6417:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6418:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6419:                         }
                   6420:                     }
1.1034    raeburn  6421:                     $$tstatus = 'is';
1.1002    raeburn  6422:                 }
1.994     raeburn  6423:             }
                   6424:             if ($$tend) {
1.1104    raeburn  6425:                 if ($$tend<$update) {
1.994     raeburn  6426:                     $$tstatus='expired';
                   6427:                 } elsif ($$tend<$now) {
                   6428:                     $$tstatus='will_not';
                   6429:                 }
                   6430:             }
                   6431:         }
                   6432:     }
                   6433: }
                   6434: 
1.1104    raeburn  6435: sub get_groups_roles {
                   6436:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6437:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6438:                   (ref($rolecodes) eq 'ARRAY') && 
                   6439:                   (ref($groups_roles) eq 'HASH')); 
                   6440:     if (keys(%{$cdom_courseroles}) > 0) {
                   6441:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6442:         if ($cdom ne '' && $cnum ne '') {
                   6443:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6444:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6445:                     my $crsrole = $1;
                   6446:                     my $crssec = $2;
                   6447:                     if ($crsrole =~ /^cr/) {
                   6448:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6449:                             push(@{$rolecodes},'cr');
                   6450:                         }
                   6451:                     } else {
                   6452:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6453:                             push(@{$rolecodes},$crsrole);
                   6454:                         }
                   6455:                     }
                   6456:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6457:                     if ($crssec ne '') {
                   6458:                         $rolekey .= "/$crssec";
                   6459:                     }
                   6460:                     $rolekey .= './';
                   6461:                     $groups_roles->{$rolekey} = $rolecodes;
                   6462:                 }
                   6463:             }
                   6464:         }
                   6465:     }
                   6466:     return;
                   6467: }
                   6468: 
                   6469: sub delete_env_groupprivs {
                   6470:     my ($where,$courseroles,$possroles) = @_;
                   6471:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6472:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6473:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6474:         %{$courseroles->{$udom}} =
                   6475:             &get_my_roles('','','userroles',['active'],
                   6476:                           $possroles,[$udom],1);
                   6477:     }
                   6478:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6479:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6480:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6481:             my $area = '/'.$cdom.'/'.$cnum;
                   6482:             my $privkey = "user.priv.$crsrole.$area";
                   6483:             if ($crssec ne '') {
                   6484:                 $privkey .= '/'.$crssec;
                   6485:             }
                   6486:             $privkey .= ".$area/$group";
                   6487:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6488:         }
                   6489:     }
                   6490:     return;
                   6491: }
                   6492: 
1.994     raeburn  6493: sub check_adhoc_privs {
1.1329    raeburn  6494:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6495:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6496:     if ($sec) {
                   6497:         $cckey .= '/'.$sec;
                   6498:     } 
1.1185    raeburn  6499:     my $setprivs;
1.994     raeburn  6500:     if ($env{$cckey}) {
                   6501:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6502:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6503:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6504:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6505:             $setprivs = 1;
1.994     raeburn  6506:         }
                   6507:     } else {
1.1330    raeburn  6508:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6509:         $setprivs = 1;
1.994     raeburn  6510:     }
1.1185    raeburn  6511:     return $setprivs;
1.994     raeburn  6512: }
                   6513: 
                   6514: sub set_adhoc_privileges {
1.1326    raeburn  6515: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6516:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6517:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6518:     if ($sec ne '') {
                   6519:         $area .= '/'.$sec;
                   6520:     }
1.994     raeburn  6521:     my $spec = $role.'.'.$area;
                   6522:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6523:                                   $env{'user.name'},1);
1.1326    raeburn  6524:     my %rolehash = ();
1.1332    raeburn  6525:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6526:         my $rolename = $1;
1.1326    raeburn  6527:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6528:         my %domdef = &get_domain_defaults($dcdom);
                   6529:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6530:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6531:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6532:             }
                   6533:         }
1.1326    raeburn  6534:     } else {
                   6535:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6536:     }
1.1341    raeburn  6537:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6538:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6539:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6540:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6541:         &appenv( {'request.role'        => $spec,
                   6542:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6543:                   'request.course.sec'  => $sec,
1.1088    raeburn  6544:                  }
                   6545:                );
                   6546:         my $tadv=0;
                   6547:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6548:         &appenv({'request.role.adv'    => $tadv});
                   6549:     }
1.994     raeburn  6550: }
                   6551: 
1.12      www      6552: # --------------------------------------------------------------- get interface
                   6553: 
                   6554: sub get {
1.131     albertel 6555:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6556:    my $items='';
1.800     albertel 6557:    foreach my $item (@$storearr) {
                   6558:        $items.=&escape($item).'&';
1.191     harris41 6559:    }
1.12      www      6560:    $items=~s/\&$//;
1.620     albertel 6561:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6562:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6563:    my $uhome=&homeserver($uname,$udomain);
                   6564: 
1.133     albertel 6565:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6566:    my @pairs=split(/\&/,$rep);
1.273     albertel 6567:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6568:      return @pairs;
                   6569:    }
1.15      www      6570:    my %returnhash=();
1.42      www      6571:    my $i=0;
1.800     albertel 6572:    foreach my $item (@$storearr) {
                   6573:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6574:       $i++;
1.191     harris41 6575:    }
1.15      www      6576:    return %returnhash;
1.27      www      6577: }
                   6578: 
                   6579: # --------------------------------------------------------------- del interface
                   6580: 
                   6581: sub del {
1.133     albertel 6582:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6583:    my $items='';
1.800     albertel 6584:    foreach my $item (@$storearr) {
                   6585:        $items.=&escape($item).'&';
1.191     harris41 6586:    }
1.984     neumanie 6587: 
1.27      www      6588:    $items=~s/\&$//;
1.620     albertel 6589:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6590:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6591:    my $uhome=&homeserver($uname,$udomain);
                   6592:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6593: }
                   6594: 
                   6595: # -------------------------------------------------------------- dump interface
                   6596: 
1.1180    droeschl 6597: sub unserialize {
                   6598:     my ($rep, $escapedkeys) = @_;
                   6599: 
                   6600:     return {} if $rep =~ /^error/;
                   6601: 
                   6602:     my %returnhash=();
1.1252    raeburn  6603: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6604: 	    my ($key, $value) = split(/=/, $item, 2);
                   6605: 	    $key = unescape($key) unless $escapedkeys;
                   6606: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6607: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6608: 	}
                   6609:     #return %returnhash;
                   6610:     return \%returnhash;
                   6611: }        
                   6612: 
                   6613: # see Lond::dump_with_regexp
                   6614: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6615: sub dump {
1.1180    droeschl 6616:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6617:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6618:     if (!$uname) { $uname=$env{'user.name'}; }
                   6619:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6620: 
1.1266    raeburn  6621:     if ($regexp) {
                   6622:         $regexp=&escape($regexp);
                   6623:     } else {
                   6624:         $regexp='.';
                   6625:     }
1.1180    droeschl 6626:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6627:         # user is hosted on this machine
1.1266    raeburn  6628:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6629:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6630:         return %{unserialize($reply, $escapedkeys)};
                   6631:     }
1.1166    raeburn  6632:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6633:     my @pairs=split(/\&/,$rep);
                   6634:     my %returnhash=();
1.1098    foxr     6635:     if (!($rep =~ /^error/ )) {
                   6636: 	foreach my $item (@pairs) {
                   6637: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6638:         $key = unescape($key) unless $escapedkeys;
                   6639:         #$key = &unescape($key);
1.1098    foxr     6640: 	    next if ($key =~ /^error: 2 /);
                   6641: 	    $returnhash{$key}=&thaw_unescape($value);
                   6642: 	}
1.755     albertel 6643:     }
                   6644:     return %returnhash;
1.407     www      6645: }
                   6646: 
1.1098    foxr     6647: 
1.717     albertel 6648: # --------------------------------------------------------- dumpstore interface
                   6649: 
                   6650: sub dumpstore {
                   6651:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6652:    # same as dump but keys must be escaped. They may contain colon separated
                   6653:    # lists of values that may themself contain colons (e.g. symbs).
                   6654:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6655: }
                   6656: 
1.407     www      6657: # -------------------------------------------------------------- keys interface
                   6658: 
                   6659: sub getkeys {
                   6660:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6661:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6662:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6663:    my $uhome=&homeserver($uname,$udomain);
                   6664:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6665:    my @keyarray=();
1.800     albertel 6666:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6667:       next if ($key =~ /^error: 2 /);
1.800     albertel 6668:       push(@keyarray,&unescape($key));
1.407     www      6669:    }
                   6670:    return @keyarray;
1.318     matthew  6671: }
                   6672: 
1.319     matthew  6673: # --------------------------------------------------------------- currentdump
                   6674: sub currentdump {
1.328     matthew  6675:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6676:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6677:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6678:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6679:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6680:    my $rep;
                   6681: 
                   6682:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6683:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6684:                    $courseid)));
                   6685:    } else {
                   6686:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6687:    }
                   6688: 
1.318     matthew  6689:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6690:    #
1.318     matthew  6691:    my %returnhash=();
1.319     matthew  6692:    #
1.1343    raeburn  6693:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6694:        # an old lond will not know currentdump
                   6695:        # Do a dump and make it look like a currentdump
1.822     albertel 6696:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6697:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6698:        my %hash = @tmp;
                   6699:        @tmp=();
1.424     matthew  6700:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6701:    } else {
                   6702:        my @pairs=split(/\&/,$rep);
1.800     albertel 6703:        foreach my $pair (@pairs) {
                   6704:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6705:            my ($symb,$param) = split(/:/,$key);
                   6706:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6707:                                                         &thaw_unescape($value);
1.319     matthew  6708:        }
1.191     harris41 6709:    }
1.12      www      6710:    return %returnhash;
1.424     matthew  6711: }
                   6712: 
                   6713: sub convert_dump_to_currentdump{
                   6714:     my %hash = %{shift()};
                   6715:     my %returnhash;
                   6716:     # Code ripped from lond, essentially.  The only difference
                   6717:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6718:     # we might run in to problems with parameter names =~ /^v\./
                   6719:     while (my ($key,$value) = each(%hash)) {
                   6720:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6721: 	$symb  = &unescape($symb);
                   6722: 	$param = &unescape($param);
1.424     matthew  6723:         next if ($v eq 'version' || $symb eq 'keys');
                   6724:         next if (exists($returnhash{$symb}) &&
                   6725:                  exists($returnhash{$symb}->{$param}) &&
                   6726:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6727:         $returnhash{$symb}->{$param}=$value;
                   6728:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6729:     }
                   6730:     #
                   6731:     # Remove all of the keys in the hashes which keep track of
                   6732:     # the version of the parameter.
                   6733:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6734:         # use a foreach because we are going to delete from the hash.
                   6735:         foreach my $key (keys(%$param_hash)) {
                   6736:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6737:         }
                   6738:     }
                   6739:     return \%returnhash;
1.12      www      6740: }
                   6741: 
1.627     albertel 6742: # ------------------------------------------------------ critical inc interface
                   6743: 
                   6744: sub cinc {
                   6745:     return &inc(@_,'critical');
                   6746: }
                   6747: 
1.449     matthew  6748: # --------------------------------------------------------------- inc interface
                   6749: 
                   6750: sub inc {
1.627     albertel 6751:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6752:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6753:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6754:     my $uhome=&homeserver($uname,$udomain);
                   6755:     my $items='';
                   6756:     if (! ref($store)) {
                   6757:         # got a single value, so use that instead
                   6758:         $items = &escape($store).'=&';
                   6759:     } elsif (ref($store) eq 'SCALAR') {
                   6760:         $items = &escape($$store).'=&';        
                   6761:     } elsif (ref($store) eq 'ARRAY') {
                   6762:         $items = join('=&',map {&escape($_);} @{$store});
                   6763:     } elsif (ref($store) eq 'HASH') {
                   6764:         while (my($key,$value) = each(%{$store})) {
                   6765:             $items.= &escape($key).'='.&escape($value).'&';
                   6766:         }
                   6767:     }
                   6768:     $items=~s/\&$//;
1.627     albertel 6769:     if ($critical) {
                   6770: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6771:     } else {
                   6772: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6773:     }
1.449     matthew  6774: }
                   6775: 
1.12      www      6776: # --------------------------------------------------------------- put interface
                   6777: 
                   6778: sub put {
1.134     albertel 6779:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6780:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6781:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6782:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6783:    my $items='';
1.800     albertel 6784:    foreach my $item (keys(%$storehash)) {
                   6785:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6786:    }
1.12      www      6787:    $items=~s/\&$//;
1.134     albertel 6788:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6789: }
                   6790: 
1.631     albertel 6791: # ------------------------------------------------------------ newput interface
                   6792: 
                   6793: sub newput {
                   6794:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6795:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6796:    if (!$uname) { $uname=$env{'user.name'}; }
                   6797:    my $uhome=&homeserver($uname,$udomain);
                   6798:    my $items='';
                   6799:    foreach my $key (keys(%$storehash)) {
                   6800:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6801:    }
                   6802:    $items=~s/\&$//;
                   6803:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6804: }
                   6805: 
                   6806: # ---------------------------------------------------------  putstore interface
                   6807: 
1.524     raeburn  6808: sub putstore {
1.1269    raeburn  6809:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6810:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6811:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6812:    my $uhome=&homeserver($uname,$udomain);
                   6813:    my $items='';
1.715     albertel 6814:    foreach my $key (keys(%$storehash)) {
                   6815:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6816:    }
1.715     albertel 6817:    $items=~s/\&$//;
1.716     albertel 6818:    my $esc_symb=&escape($symb);
                   6819:    my $esc_v=&escape($version);
1.715     albertel 6820:    my $reply =
1.716     albertel 6821:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6822: 	      $uhome);
1.1269    raeburn  6823:    if (($tolog) && ($reply eq 'ok')) {
                   6824:        my $namevalue='';
                   6825:        foreach my $key (keys(%{$storehash})) {
                   6826:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6827:        }
                   6828:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6829:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6830:                      '&version='.$esc_v.
                   6831:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6832:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6833:    }
1.715     albertel 6834:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6835:        # gfall back to way things use to be done
1.715     albertel 6836:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6837: 			    $uname);
1.524     raeburn  6838:    }
1.715     albertel 6839:    return $reply;
                   6840: }
                   6841: 
                   6842: sub old_putstore {
1.716     albertel 6843:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6844:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6845:     if (!$uname) { $uname=$env{'user.name'}; }
                   6846:     my $uhome=&homeserver($uname,$udomain);
                   6847:     my %newstorehash;
1.800     albertel 6848:     foreach my $item (keys(%$storehash)) {
                   6849: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6850: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6851:     }
                   6852:     my $items='';
                   6853:     my %allitems = ();
1.800     albertel 6854:     foreach my $item (keys(%newstorehash)) {
                   6855: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6856: 	    my $key = $1.':keys:'.$2;
                   6857: 	    $allitems{$key} .= $3.':';
                   6858: 	}
1.800     albertel 6859: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6860:     }
1.800     albertel 6861:     foreach my $item (keys(%allitems)) {
                   6862: 	$allitems{$item} =~ s/\:$//;
                   6863: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6864:     }
                   6865:     $items=~s/\&$//;
                   6866:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6867: }
                   6868: 
1.47      www      6869: # ------------------------------------------------------ critical put interface
                   6870: 
                   6871: sub cput {
1.134     albertel 6872:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6873:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6874:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6875:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6876:    my $items='';
1.800     albertel 6877:    foreach my $item (keys(%$storehash)) {
                   6878:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6879:    }
1.47      www      6880:    $items=~s/\&$//;
1.134     albertel 6881:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6882: }
                   6883: 
                   6884: # -------------------------------------------------------------- eget interface
                   6885: 
                   6886: sub eget {
1.133     albertel 6887:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6888:    my $items='';
1.800     albertel 6889:    foreach my $item (@$storearr) {
                   6890:        $items.=&escape($item).'&';
1.191     harris41 6891:    }
1.12      www      6892:    $items=~s/\&$//;
1.620     albertel 6893:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6894:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6895:    my $uhome=&homeserver($uname,$udomain);
                   6896:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6897:    my @pairs=split(/\&/,$rep);
                   6898:    my %returnhash=();
1.42      www      6899:    my $i=0;
1.800     albertel 6900:    foreach my $item (@$storearr) {
                   6901:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6902:       $i++;
1.191     harris41 6903:    }
1.12      www      6904:    return %returnhash;
                   6905: }
                   6906: 
1.667     albertel 6907: # ------------------------------------------------------------ tmpput interface
                   6908: sub tmpput {
1.802     raeburn  6909:     my ($storehash,$server,$context)=@_;
1.667     albertel 6910:     my $items='';
1.800     albertel 6911:     foreach my $item (keys(%$storehash)) {
                   6912: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6913:     }
                   6914:     $items=~s/\&$//;
1.802     raeburn  6915:     if (defined($context)) {
                   6916:         $items .= ':'.&escape($context);
                   6917:     }
1.667     albertel 6918:     return &reply("tmpput:$items",$server);
                   6919: }
                   6920: 
                   6921: # ------------------------------------------------------------ tmpget interface
                   6922: sub tmpget {
1.688     albertel 6923:     my ($token,$server)=@_;
                   6924:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6925:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6926:     my %returnhash;
1.1328    raeburn  6927:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6928:         return %returnhash;
                   6929:     }
1.667     albertel 6930:     foreach my $item (split(/\&/,$rep)) {
                   6931: 	my ($key,$value)=split(/=/,$item);
                   6932: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6933:     }
                   6934:     return %returnhash;
                   6935: }
                   6936: 
1.1113    raeburn  6937: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6938: sub tmpdel {
                   6939:     my ($token,$server)=@_;
                   6940:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6941:     return &reply("tmpdel:$token",$server);
                   6942: }
                   6943: 
1.1198    raeburn  6944: # ------------------------------------------------------------ get_timebased_id 
                   6945: 
                   6946: sub get_timebased_id {
                   6947:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6948:         $maxtries) = @_;
                   6949:     my ($newid,$error,$dellock);
                   6950:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6951:         return ('','ok','invalid call to get suffix');
                   6952:     }
                   6953: 
                   6954: # set defaults for any optional args for which values were not supplied
                   6955:     if ($who eq '') {
                   6956:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6957:     }
                   6958:     if (!$locktries) {
                   6959:         $locktries = 3;
                   6960:     }
                   6961:     if (!$maxtries) {
                   6962:         $maxtries = 10;
                   6963:     }
                   6964:     
                   6965:     if (($cdom eq '') || ($cnum eq '')) {
                   6966:         if ($env{'request.course.id'}) {
                   6967:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6968:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6969:         }
                   6970:         if (($cdom eq '') || ($cnum eq '')) {
                   6971:             return ('','ok','call to get suffix not in course context');
                   6972:         }
                   6973:     }
                   6974: 
                   6975: # construct locking item
                   6976:     my $lockhash = {
                   6977:                       $prefix."\0".'locked_'.$keyid => $who,
                   6978:                    };
                   6979:     my $tries = 0;
                   6980: 
                   6981: # attempt to get lock on nohist_$namespace file
                   6982:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6983:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6984:         $tries ++;
                   6985:         sleep 1;
                   6986:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6987:     }
                   6988: 
                   6989: # attempt to get unique identifier, based on current timestamp
                   6990:     if ($gotlock eq 'ok') {
                   6991:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6992:         my $id = time;
                   6993:         $newid = $id;
1.1268    raeburn  6994:         if ($idtype eq 'addcode') {
                   6995:             $newid .= &sixnum_code();
                   6996:         }
1.1198    raeburn  6997:         my $idtries = 0;
                   6998:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6999:             if ($idtype eq 'concat') {
                   7000:                 $newid = $id.$idtries;
1.1268    raeburn  7001:             } elsif ($idtype eq 'addcode') {
                   7002:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7003:             } else {
                   7004:                 $newid ++;
                   7005:             }
                   7006:             $idtries ++;
                   7007:         }
                   7008:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7009:             my %new_item =  (
                   7010:                               $prefix."\0".$newid => $who,
                   7011:                             );
                   7012:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7013:                                                  $cdom,$cnum);
                   7014:             if ($putresult ne 'ok') {
                   7015:                 undef($newid);
                   7016:                 $error = 'error saving new item: '.$putresult;
                   7017:             }
                   7018:         } else {
1.1268    raeburn  7019:              undef($newid);
1.1198    raeburn  7020:              $error = ('error: no unique suffix available for the new item ');
                   7021:         }
                   7022: #  remove lock
                   7023:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7024:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7025:     } else {
                   7026:         $error = "error: could not obtain lockfile\n";
                   7027:         $dellock = 'ok';
1.1276    raeburn  7028:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7029:             $dellock = 'nolock';
                   7030:         }
1.1198    raeburn  7031:     }
                   7032:     return ($newid,$dellock,$error);
                   7033: }
                   7034: 
1.1268    raeburn  7035: sub sixnum_code {
                   7036:     my $code;
                   7037:     for (0..6) {
                   7038:         $code .= int( rand(9) );
                   7039:     }
                   7040:     return $code;
                   7041: }
                   7042: 
1.765     albertel 7043: # -------------------------------------------------- portfolio access checking
                   7044: 
                   7045: sub portfolio_access {
1.1270    raeburn  7046:     my ($requrl,$clientip) = @_;
1.765     albertel 7047:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7048:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7049:     if ($result) {
                   7050:         my %setters;
                   7051:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7052:             my ($startblock,$endblock) =
                   7053:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7054:             if ($startblock && $endblock) {
                   7055:                 return 'B';
                   7056:             }
                   7057:         } else {
                   7058:             my ($startblock,$endblock) =
                   7059:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7060:             if ($startblock && $endblock) {
                   7061:                 return 'B';
                   7062:             }
                   7063:         }
                   7064:     }
1.765     albertel 7065:     if ($result eq 'ok') {
1.766     albertel 7066:        return 'F';
1.765     albertel 7067:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7068:        return 'A';
1.765     albertel 7069:     }
1.766     albertel 7070:     return '';
1.765     albertel 7071: }
                   7072: 
                   7073: sub get_portfolio_access {
1.1270    raeburn  7074:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7075: 
                   7076:     if (!ref($access_hash)) {
                   7077: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7078: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7079: 						   $file_name);
                   7080: 	$access_hash = $access_controls{$file_name};
                   7081:     }
                   7082: 
1.1270    raeburn  7083:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7084:     my $now = time;
                   7085:     if (ref($access_hash) eq 'HASH') {
                   7086:         foreach my $key (keys(%{$access_hash})) {
                   7087:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7088:             if ($start > $now) {
                   7089:                 next;
                   7090:             }
                   7091:             if ($end && $end<$now) {
                   7092:                 next;
                   7093:             }
                   7094:             if ($scope eq 'public') {
                   7095:                 $public = $key;
                   7096:                 last;
                   7097:             } elsif ($scope eq 'guest') {
                   7098:                 $guest = $key;
                   7099:             } elsif ($scope eq 'domains') {
                   7100:                 push(@domains,$key);
                   7101:             } elsif ($scope eq 'users') {
                   7102:                 push(@users,$key);
                   7103:             } elsif ($scope eq 'course') {
                   7104:                 push(@courses,$key);
                   7105:             } elsif ($scope eq 'group') {
                   7106:                 push(@groups,$key);
1.1270    raeburn  7107:             } elsif ($scope eq 'ip') {
                   7108:                 push(@ips,$key);
1.765     albertel 7109:             }
                   7110:         }
                   7111:         if ($public) {
                   7112:             return 'ok';
1.1270    raeburn  7113:         } elsif (@ips > 0) {
                   7114:             my $allowed;
                   7115:             foreach my $ipkey (@ips) {
                   7116:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7117:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7118:                         $allowed = 1;
                   7119:                         last; 
                   7120:                     }
                   7121:                 }
                   7122:             }
                   7123:             if ($allowed) {
                   7124:                 return 'ok';
                   7125:             }
1.765     albertel 7126:         }
                   7127:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7128:             if ($guest) {
                   7129:                 return $guest;
                   7130:             }
                   7131:         } else {
                   7132:             if (@domains > 0) {
                   7133:                 foreach my $domkey (@domains) {
                   7134:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7135:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7136:                             return 'ok';
                   7137:                         }
                   7138:                     }
                   7139:                 }
                   7140:             }
                   7141:             if (@users > 0) {
                   7142:                 foreach my $userkey (@users) {
1.865     raeburn  7143:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7144:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7145:                             if (ref($item) eq 'HASH') {
                   7146:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7147:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7148:                                     return 'ok';
                   7149:                                 }
                   7150:                             }
                   7151:                         }
                   7152:                     } 
1.765     albertel 7153:                 }
                   7154:             }
                   7155:             my %roleshash;
                   7156:             my @courses_and_groups = @courses;
                   7157:             push(@courses_and_groups,@groups); 
                   7158:             if (@courses_and_groups > 0) {
                   7159:                 my (%allgroups,%allroles); 
                   7160:                 my ($start,$end,$role,$sec,$group);
                   7161:                 foreach my $envkey (%env) {
1.1060    raeburn  7162:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7163:                         my $cid = $2.'_'.$3; 
                   7164:                         if ($1 eq 'gr') {
                   7165:                             $group = $4;
                   7166:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7167:                         } else {
                   7168:                             if ($4 eq '') {
                   7169:                                 $sec = 'none';
                   7170:                             } else {
                   7171:                                 $sec = $4;
                   7172:                             }
                   7173:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7174:                         }
1.811     albertel 7175:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7176:                         my $cid = $2.'_'.$3;
                   7177:                         if ($4 eq '') {
                   7178:                             $sec = 'none';
                   7179:                         } else {
                   7180:                             $sec = $4;
                   7181:                         }
                   7182:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7183:                     }
                   7184:                 }
                   7185:                 if (keys(%allroles) == 0) {
                   7186:                     return;
                   7187:                 }
                   7188:                 foreach my $key (@courses_and_groups) {
                   7189:                     my %content = %{$$access_hash{$key}};
                   7190:                     my $cnum = $content{'number'};
                   7191:                     my $cdom = $content{'domain'};
                   7192:                     my $cid = $cdom.'_'.$cnum;
                   7193:                     if (!exists($allroles{$cid})) {
                   7194:                         next;
                   7195:                     }    
                   7196:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7197:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7198:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7199:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7200:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7201:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7202:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7203:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7204:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7205:                                         if (grep/^all$/,@sections) {
                   7206:                                             return 'ok';
                   7207:                                         } else {
                   7208:                                             if (grep/^$sec$/,@sections) {
                   7209:                                                 return 'ok';
                   7210:                                             }
                   7211:                                         }
                   7212:                                     }
                   7213:                                 }
                   7214:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7215:                                     if (grep/^none$/,@groups) {
                   7216:                                         return 'ok';
                   7217:                                     }
                   7218:                                 } else {
                   7219:                                     if (grep/^all$/,@groups) {
                   7220:                                         return 'ok';
                   7221:                                     } 
                   7222:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7223:                                         if (grep/^$group$/,@groups) {
                   7224:                                             return 'ok';
                   7225:                                         }
                   7226:                                     }
                   7227:                                 } 
                   7228:                             }
                   7229:                         }
                   7230:                     }
                   7231:                 }
                   7232:             }
                   7233:             if ($guest) {
                   7234:                 return $guest;
                   7235:             }
                   7236:         }
                   7237:     }
                   7238:     return;
                   7239: }
                   7240: 
                   7241: sub course_group_datechecker {
                   7242:     my ($dates,$now,$status) = @_;
                   7243:     my ($start,$end) = split(/\./,$dates);
                   7244:     if (!$start && !$end) {
                   7245:         return 'ok';
                   7246:     }
                   7247:     if (grep/^active$/,@{$status}) {
                   7248:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7249:             return 'ok';
                   7250:         }
                   7251:     }
                   7252:     if (grep/^previous$/,@{$status}) {
                   7253:         if ($end > $now ) {
                   7254:             return 'ok';
                   7255:         }
                   7256:     }
                   7257:     if (grep/^future$/,@{$status}) {
                   7258:         if ($start > $now) {
                   7259:             return 'ok';
                   7260:         }
                   7261:     }
                   7262:     return; 
                   7263: }
                   7264: 
                   7265: sub parse_portfolio_url {
                   7266:     my ($url) = @_;
                   7267: 
                   7268:     my ($type,$udom,$unum,$group,$file_name);
                   7269:     
1.823     albertel 7270:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7271: 	$type = 1;
                   7272:         $udom = $1;
                   7273:         $unum = $2;
                   7274:         $file_name = $3;
1.823     albertel 7275:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7276: 	$type = 2;
                   7277:         $udom = $1;
                   7278:         $unum = $2;
                   7279:         $group = $3;
                   7280:         $file_name = $3.'/'.$4;
                   7281:     }
                   7282:     if (wantarray) {
                   7283: 	return ($type,$udom,$unum,$file_name,$group);
                   7284:     }
                   7285:     return $type;
                   7286: }
                   7287: 
                   7288: sub is_portfolio_url {
                   7289:     my ($url) = @_;
                   7290:     return scalar(&parse_portfolio_url($url));
                   7291: }
                   7292: 
1.798     raeburn  7293: sub is_portfolio_file {
                   7294:     my ($file) = @_;
1.820     raeburn  7295:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7296:         return 1;
                   7297:     }
                   7298:     return;
                   7299: }
                   7300: 
1.976     raeburn  7301: sub usertools_access {
1.1084    raeburn  7302:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7303:     my ($access,%tools);
                   7304:     if ($context eq '') {
                   7305:         $context = 'tools';
                   7306:     }
                   7307:     if ($context eq 'requestcourses') {
                   7308:         %tools = (
                   7309:                       official   => 1,
                   7310:                       unofficial => 1,
1.1006    raeburn  7311:                       community  => 1,
1.1246    raeburn  7312:                       textbook   => 1,
1.1305    raeburn  7313:                       placement  => 1,
1.1368    raeburn  7314:                       lti        => 1,
1.985     raeburn  7315:                  );
1.1183    raeburn  7316:     } elsif ($context eq 'requestauthor') {
                   7317:         %tools = (
                   7318:                       requestauthor => 1,
                   7319:                  );
1.985     raeburn  7320:     } else {
                   7321:         %tools = (
                   7322:                       aboutme   => 1,
                   7323:                       blog      => 1,
1.1177    raeburn  7324:                       webdav    => 1,
1.985     raeburn  7325:                       portfolio => 1,
                   7326:                  );
                   7327:     }
1.976     raeburn  7328:     return if (!defined($tools{$tool}));
                   7329: 
1.1242    raeburn  7330:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7331:         $udom = $env{'user.domain'};
                   7332:         $uname = $env{'user.name'};
                   7333:     }
                   7334: 
1.978     raeburn  7335:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7336:         if ($action ne 'reload') {
1.985     raeburn  7337:             if ($context eq 'requestcourses') {
                   7338:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7339:             } elsif ($context eq 'requestauthor') {
                   7340:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7341:             } else {
                   7342:                 return $env{'environment.availabletools.'.$tool};
                   7343:             }
                   7344:         }
1.976     raeburn  7345:     }
                   7346: 
1.1183    raeburn  7347:     my ($toolstatus,$inststatus,$envkey);
                   7348:     if ($context eq 'requestauthor') {
                   7349:         $envkey = $context; 
                   7350:     } else {
                   7351:         $envkey = $context.'.'.$tool;
                   7352:     }
1.976     raeburn  7353: 
1.985     raeburn  7354:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7355:          ($action ne 'reload')) {
1.1183    raeburn  7356:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7357:         $inststatus = $env{'environment.inststatus'};
                   7358:     } else {
1.1084    raeburn  7359:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7360:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7361:             $inststatus = $userenvref->{'inststatus'};
                   7362:         } else {
1.1183    raeburn  7363:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7364:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7365:             $inststatus = $userenv{'inststatus'};
                   7366:         }
1.976     raeburn  7367:     }
                   7368: 
                   7369:     if ($toolstatus ne '') {
                   7370:         if ($toolstatus) {
                   7371:             $access = 1;
                   7372:         } else {
                   7373:             $access = 0;
                   7374:         }
                   7375:         return $access;
                   7376:     }
                   7377: 
1.1084    raeburn  7378:     my ($is_adv,%domdef);
                   7379:     if (ref($is_advref) eq 'HASH') {
                   7380:         $is_adv = $is_advref->{'is_adv'};
                   7381:     } else {
                   7382:         $is_adv = &is_advanced_user($udom,$uname);
                   7383:     }
                   7384:     if (ref($domdefref) eq 'HASH') {
                   7385:         %domdef = %{$domdefref};
                   7386:     } else {
                   7387:         %domdef = &get_domain_defaults($udom);
                   7388:     }
1.976     raeburn  7389:     if (ref($domdef{$tool}) eq 'HASH') {
                   7390:         if ($is_adv) {
                   7391:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7392:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7393:                     $access = 1;
                   7394:                 } else {
                   7395:                     $access = 0;
                   7396:                 }
                   7397:                 return $access;
                   7398:             }
                   7399:         }
                   7400:         if ($inststatus ne '') {
                   7401:             my ($hasaccess,$hasnoaccess);
                   7402:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7403:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7404:                     if ($domdef{$tool}{$affiliation}) {
                   7405:                         $hasaccess = 1;
                   7406:                     } else {
                   7407:                         $hasnoaccess = 1;
                   7408:                     }
                   7409:                 }
                   7410:             }
                   7411:             if ($hasaccess || $hasnoaccess) {
                   7412:                 if ($hasaccess) {
                   7413:                     $access = 1;
                   7414:                 } elsif ($hasnoaccess) {
                   7415:                     $access = 0; 
                   7416:                 }
                   7417:                 return $access;
                   7418:             }
                   7419:         } else {
                   7420:             if ($domdef{$tool}{'default'} ne '') {
                   7421:                 if ($domdef{$tool}{'default'}) {
                   7422:                     $access = 1;
                   7423:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7424:                     $access = 0;
                   7425:                 }
                   7426:                 return $access;
                   7427:             }
                   7428:         }
                   7429:     } else {
1.1177    raeburn  7430:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7431:             $access = 1;
                   7432:         } else {
                   7433:             $access = 0;
                   7434:         }
1.976     raeburn  7435:         return $access;
                   7436:     }
                   7437: }
                   7438: 
1.1050    raeburn  7439: sub is_course_owner {
                   7440:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7441:     if (($udom eq '') || ($uname eq '')) {
                   7442:         $udom = $env{'user.domain'};
                   7443:         $uname = $env{'user.name'};
                   7444:     }
                   7445:     unless (($udom eq '') || ($uname eq '')) {
                   7446:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7447:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7448:                 return 1;
                   7449:             } else {
                   7450:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7451:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7452:                     return 1;
                   7453:                 }
                   7454:             }
                   7455:         }
                   7456:     }
                   7457:     return;
                   7458: }
                   7459: 
1.976     raeburn  7460: sub is_advanced_user {
                   7461:     my ($udom,$uname) = @_;
1.1085    raeburn  7462:     if ($udom ne '' && $uname ne '') {
                   7463:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7464:             if (wantarray) {
                   7465:                 return ($env{'user.adv'},$env{'user.author'});
                   7466:             } else {
                   7467:                 return $env{'user.adv'};
                   7468:             }
1.1085    raeburn  7469:         }
                   7470:     }
1.976     raeburn  7471:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7472:     my %allroles;
1.1128    raeburn  7473:     my ($is_adv,$is_author);
1.976     raeburn  7474:     foreach my $role (keys(%roleshash)) {
                   7475:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7476:         my $area = '/'.$tdomain.'/'.$trest;
                   7477:         if ($sec ne '') {
                   7478:             $area .= '/'.$sec;
                   7479:         }
                   7480:         if (($area ne '') && ($trole ne '')) {
                   7481:             my $spec=$trole.'.'.$area;
                   7482:             if ($trole =~ /^cr\//) {
                   7483:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7484:             } elsif ($trole ne 'gr') {
                   7485:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7486:             }
1.1128    raeburn  7487:             if ($trole eq 'au') {
                   7488:                 $is_author = 1;
                   7489:             }
1.976     raeburn  7490:         }
                   7491:     }
                   7492:     foreach my $role (keys(%allroles)) {
                   7493:         last if ($is_adv);
                   7494:         foreach my $item (split(/:/,$allroles{$role})) {
                   7495:             if ($item ne '') {
                   7496:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7497:                 if ($privilege eq 'adv') {
                   7498:                     $is_adv = 1;
                   7499:                     last;
                   7500:                 }
                   7501:             }
                   7502:         }
                   7503:     }
1.1128    raeburn  7504:     if (wantarray) {
                   7505:         return ($is_adv,$is_author);
                   7506:     }
1.976     raeburn  7507:     return $is_adv;
                   7508: }
1.798     raeburn  7509: 
1.1035    raeburn  7510: sub check_can_request {
1.1368    raeburn  7511:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7512:     my $canreq = 0;
1.1368    raeburn  7513:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7514:         $uname = $env{'user.name'};
                   7515:         $udom = $env{'user.domain'};
                   7516:     }
1.1035    raeburn  7517:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7518:     my @options = ('approval','validate','autolimit');
                   7519:     my $optregex = join('|',@options);
                   7520:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7521:         foreach my $type (@{$types}) {
1.1368    raeburn  7522:             if (&usertools_access($uname,$udom,$type,undef,
                   7523:                                   'requestcourses')) {
1.1035    raeburn  7524:                 $canreq ++;
1.1036    raeburn  7525:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7526:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7527:                 }
1.1368    raeburn  7528:                 if ($dom eq $udom) {
1.1035    raeburn  7529:                     $can_request->{$type} = 1;
                   7530:                 }
                   7531:             }
1.1368    raeburn  7532:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7533:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7534:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7535:                 if (@curr > 0) {
1.1036    raeburn  7536:                     foreach my $item (@curr) {
                   7537:                         if (ref($request_domains) eq 'HASH') {
                   7538:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7539:                             if ($otherdom ne '') {
                   7540:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7541:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7542:                                         push(@{$request_domains->{$type}},$otherdom);
                   7543:                                     }
                   7544:                                 } else {
                   7545:                                     push(@{$request_domains->{$type}},$otherdom);
                   7546:                                 }
                   7547:                             }
                   7548:                         }
                   7549:                     }
1.1368    raeburn  7550:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7551:                         $canreq ++;
1.1035    raeburn  7552:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7553:                             $can_request->{$type} = 1;
                   7554:                         }
                   7555:                     }
                   7556:                 }
                   7557:             }
                   7558:         }
                   7559:     }
                   7560:     return $canreq;
                   7561: }
                   7562: 
1.341     www      7563: # ---------------------------------------------- Custom access rule evaluation
                   7564: 
                   7565: sub customaccess {
                   7566:     my ($priv,$uri)=@_;
1.807     albertel 7567:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7568:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7569:     $udom = &LONCAPA::clean_domain($udom);
                   7570:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7571:     my $access=0;
1.800     albertel 7572:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7573: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7574: 	if ($type eq 'user') {
                   7575: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7576: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7577: 		if ($tdom) {
                   7578: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7579: 		}
1.896     albertel 7580: 		if ($tuname) {
                   7581: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7582: 		}
                   7583: 		$access=($effect eq 'allow');
                   7584: 		last;
                   7585: 	    }
                   7586: 	} else {
                   7587: 	    if ($role) {
                   7588: 		if ($role ne $urole) { next; }
                   7589: 	    }
                   7590: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7591: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7592: 		if ($tdom) {
                   7593: 		    if ($tdom ne $udom) { next; }
                   7594: 		}
                   7595: 		if ($tcrs) {
                   7596: 		    if ($tcrs ne $ucrs) { next; }
                   7597: 		}
                   7598: 		if ($tsec) {
                   7599: 		    if ($tsec ne $usec) { next; }
                   7600: 		}
                   7601: 		$access=($effect eq 'allow');
                   7602: 		last;
                   7603: 	    }
                   7604: 	    if ($realm eq '' && $role eq '') {
                   7605: 		$access=($effect eq 'allow');
                   7606: 	    }
1.402     bowersj2 7607: 	}
1.341     www      7608:     }
                   7609:     return $access;
                   7610: }
                   7611: 
1.103     harris41 7612: # ------------------------------------------------- Check for a user privilege
1.12      www      7613: 
                   7614: sub allowed {
1.1281    raeburn  7615:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7616:     my $ver_orguri=$uri;
1.439     www      7617:     $uri=&deversion($uri);
1.152     www      7618:     my $orguri=$uri;
1.52      www      7619:     $uri=&declutter($uri);
1.809     raeburn  7620: 
1.810     raeburn  7621:     if ($priv eq 'evb') {
                   7622: # Evade communication block restrictions for specified role in a course
                   7623:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7624:             return $1;
                   7625:         } else {
                   7626:             return;
                   7627:         }
                   7628:     }
                   7629: 
1.620     albertel 7630:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7631: # Free bre access to adm and meta resources
1.1343    raeburn  7632:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7633: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7634: 	&& ($priv eq 'bre')) {
1.14      www      7635: 	return 'F';
1.159     www      7636:     }
                   7637: 
1.545     banghart 7638: # Free bre access to user's own portfolio contents
1.714     raeburn  7639:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7640:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7641: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7642:         my %setters;
                   7643:         my ($startblock,$endblock) = 
                   7644:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7645:         if ($startblock && $endblock) {
                   7646:             return 'B';
                   7647:         } else {
                   7648:             return 'F';
                   7649:         }
1.545     banghart 7650:     }
                   7651: 
1.762     raeburn  7652: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7653:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7654:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7655:         if (exists($env{'request.course.id'})) {
                   7656:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7657:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7658:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7659:                 my $courseprivid=$env{'request.course.id'};
                   7660:                 $courseprivid=~s/\_/\//;
                   7661:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7662:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7663:                     return $1; 
1.762     raeburn  7664:                 } else {
                   7665:                     if ($env{'request.course.sec'}) {
                   7666:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7667:                     }
                   7668:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7669:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7670:                         return $2;
                   7671:                     }
1.714     raeburn  7672:                 }
                   7673:             }
                   7674:         }
                   7675:     }
                   7676: 
1.159     www      7677: # Free bre to public access
                   7678: 
                   7679:     if ($priv eq 'bre') {
1.1362    raeburn  7680:         my $copyright;
                   7681:         unless ($uri =~ /ext\.tool/) {
                   7682:             $copyright=&metadata($uri,'copyright');
                   7683:         }
1.620     albertel 7684: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7685:            return 'F'; 
                   7686:         }
1.238     www      7687:         if ($copyright eq 'priv') {
                   7688:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7689: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7690: 		return '';
                   7691:             }
                   7692:         }
                   7693:         if ($copyright eq 'domain') {
                   7694:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7695: 	    unless (($env{'user.domain'} eq $1) ||
                   7696:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7697: 		return '';
                   7698:             }
1.262     matthew  7699:         }
1.620     albertel 7700:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7701:             # Library role, so allow browsing of resources in this domain.
                   7702:             return 'F';
1.238     www      7703:         }
1.341     www      7704:         if ($copyright eq 'custom') {
                   7705: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7706:         }
1.14      www      7707:     }
1.264     matthew  7708:     # Domain coordinator is trying to create a course
1.620     albertel 7709:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7710:         # uri is the requested domain in this case.
                   7711:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7712:         # a role of dc for the domain in question.
1.620     albertel 7713:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7714:     }
1.29      www      7715: 
1.52      www      7716:     my $thisallowed='';
                   7717:     my $statecond=0;
                   7718:     my $courseprivid='';
                   7719: 
1.1039    raeburn  7720:     my $ownaccess;
1.1043    raeburn  7721:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7722:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7723:         if ($uri eq '') {
                   7724:             $ownaccess = 1;
                   7725:         } else {
                   7726:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7727:                 my $udom = $env{'user.domain'};
                   7728:                 my $uname = $env{'user.name'};
                   7729:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7730:                     $ownaccess = 1;
1.1040    raeburn  7731:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7732:                     unless ($uri =~ m{\.\./}) {
                   7733:                         $ownaccess = 1;
                   7734:                     }
                   7735:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7736:                     my $now = time;
                   7737:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7738:                         my $adom = $1;
                   7739:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7740:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7741:                                 my ($start,$end) = split('.',$env{$key});
                   7742:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7743:                                     $ownaccess = 1;
                   7744:                                     last;
                   7745:                                 }
                   7746:                             }
                   7747:                         }
                   7748:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7749:                         my $adom = $1;
                   7750:                         my $aname = $2;
1.1042    raeburn  7751:                         foreach my $role ('ca','aa') { 
                   7752:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7753:                                 my ($start,$end) =
                   7754:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7755:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7756:                                     $ownaccess = 1;
                   7757:                                     last;
                   7758:                                 }
1.1039    raeburn  7759:                             }
                   7760:                         }
                   7761:                     }
                   7762:                 }
                   7763:             }
                   7764:         }
                   7765:     }
                   7766: 
1.52      www      7767: # Course
                   7768: 
1.620     albertel 7769:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7770:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7771:             $thisallowed.=$1;
                   7772:         }
1.52      www      7773:     }
1.29      www      7774: 
1.52      www      7775: # Domain
                   7776: 
1.620     albertel 7777:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7778:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7779:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7780:             $thisallowed.=$1;
                   7781:         }
1.12      www      7782:     }
1.52      www      7783: 
1.1141    raeburn  7784: # User who is not author or co-author might still be able to edit
                   7785: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7786:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7787:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7788:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7789:             $thisallowed.=$1;
                   7790:         }
                   7791:     }
                   7792: 
1.52      www      7793: # Course: uri itself is a course
1.66      www      7794:     my $courseuri=$uri;
                   7795:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7796:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7797: 
1.620     albertel 7798:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7799:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7800:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7801:             $thisallowed.=$1;
                   7802:         }
1.12      www      7803:     }
1.29      www      7804: 
1.665     albertel 7805: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7806: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7807:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7808: 	$thisallowed='';
1.671     raeburn  7809:         my ($match)=&is_on_map($uri);
                   7810:         if ($match) {
                   7811:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7812:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7813:                 my $value = $1;
                   7814:                 if ($noblockcheck) {
                   7815:                     $thisallowed.=$value;
1.1162    raeburn  7816:                 } else {
1.1281    raeburn  7817:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7818:                     if (@blockers > 0) {
                   7819:                         $thisallowed = 'B';
                   7820:                     } else {
                   7821:                         $thisallowed.=$value;
                   7822:                     }
1.1162    raeburn  7823:                 }
1.671     raeburn  7824:             }
                   7825:         } else {
1.705     albertel 7826:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7827:             if ($refuri) {
                   7828:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7829:                     $thisallowed='F';
1.671     raeburn  7830:                 } else {
                   7831:                     $refuri=&declutter($refuri);
                   7832:                     my ($match) = &is_on_map($refuri);
                   7833:                     if ($match) {
1.1281    raeburn  7834:                         if ($noblockcheck) {
                   7835:                             $thisallowed='F';
1.1162    raeburn  7836:                         } else {
1.1281    raeburn  7837:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7838:                             if (@blockers > 0) {
                   7839:                                 $thisallowed = 'B';
                   7840:                             } else {
                   7841:                                 $thisallowed='F';
                   7842:                             }
1.1162    raeburn  7843:                         }
1.671     raeburn  7844:                     }
1.669     raeburn  7845:                 }
1.671     raeburn  7846:             }
                   7847:         }
1.314     www      7848:     }
1.492     albertel 7849: 
1.766     albertel 7850:     if ($priv eq 'bre'
                   7851: 	&& $thisallowed ne 'F' 
                   7852: 	&& $thisallowed ne '2'
                   7853: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7854: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7855:     }
1.1250    raeburn  7856: 
1.52      www      7857: # Full access at system, domain or course-wide level? Exit.
1.29      www      7858:     if ($thisallowed=~/F/) {
                   7859: 	return 'F';
                   7860:     }
                   7861: 
1.52      www      7862: # If this is generating or modifying users, exit with special codes
1.29      www      7863: 
1.643     www      7864:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7865: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7866: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7867: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7868: 	    unless ($auname) { return $thisallowed; }
                   7869: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7870: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7871: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7872: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7873: 	}
1.52      www      7874: 	return $thisallowed;
                   7875:     }
                   7876: #
1.103     harris41 7877: # Gathered so far: system, domain and course wide privileges
1.52      www      7878: #
                   7879: # Course: See if uri or referer is an individual resource that is part of 
                   7880: # the course
                   7881: 
1.620     albertel 7882:     if ($env{'request.course.id'}) {
1.232     www      7883: 
1.620     albertel 7884:        $courseprivid=$env{'request.course.id'};
                   7885:        if ($env{'request.course.sec'}) {
                   7886:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7887:        }
                   7888:        $courseprivid=~s/\_/\//;
                   7889:        my $checkreferer=1;
1.232     www      7890:        my ($match,$cond)=&is_on_map($uri);
                   7891:        if ($match) {
                   7892:            $statecond=$cond;
1.620     albertel 7893:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7894:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7895:                my $value = $1;
                   7896:                if ($priv eq 'bre') {
1.1281    raeburn  7897:                    if ($noblockcheck) {
                   7898:                        $thisallowed.=$value;
1.1162    raeburn  7899:                    } else {
1.1281    raeburn  7900:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7901:                        if (@blockers > 0) {
                   7902:                            $thisallowed = 'B';
                   7903:                        } else {
                   7904:                            $thisallowed.=$value;
                   7905:                        }
1.1162    raeburn  7906:                    }
                   7907:                } else {
                   7908:                    $thisallowed.=$value;
                   7909:                }
1.52      www      7910:                $checkreferer=0;
                   7911:            }
1.29      www      7912:        }
1.83      www      7913:        
1.148     www      7914:        if ($checkreferer) {
1.620     albertel 7915: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7916:             unless ($refuri) {
1.800     albertel 7917:                 foreach my $key (keys(%env)) {
                   7918: 		    if ($key=~/^httpref\..*\*/) {
                   7919: 			my $pattern=$key;
1.156     www      7920:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7921:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7922:                         $pattern=~s/\//\\\//g;
1.152     www      7923:                         if ($orguri=~/$pattern/) {
1.800     albertel 7924: 			    $refuri=$env{$key};
1.148     www      7925:                         }
                   7926:                     }
1.191     harris41 7927:                 }
1.148     www      7928:             }
1.232     www      7929: 
1.148     www      7930:          if ($refuri) { 
1.152     www      7931: 	  $refuri=&declutter($refuri);
1.232     www      7932:           my ($match,$cond)=&is_on_map($refuri);
                   7933:             if ($match) {
                   7934:               my $refstatecond=$cond;
1.620     albertel 7935:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7936:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7937:                   my $value = $1;
                   7938:                   if ($priv eq 'bre') {
1.1281    raeburn  7939:                       if ($noblockcheck) {
                   7940:                           $thisallowed.=$value;
1.1162    raeburn  7941:                       } else {
1.1281    raeburn  7942:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7943:                           if (@blockers > 0) {
                   7944:                               $thisallowed = 'B';
                   7945:                           } else {
                   7946:                               $thisallowed.=$value;
                   7947:                           }
1.1162    raeburn  7948:                       }
                   7949:                   } else {
                   7950:                       $thisallowed.=$value;
                   7951:                   }
1.53      www      7952:                   $uri=$refuri;
                   7953:                   $statecond=$refstatecond;
1.52      www      7954:               }
                   7955:           }
1.148     www      7956:         }
1.29      www      7957:        }
1.52      www      7958:    }
1.29      www      7959: 
1.52      www      7960: #
1.103     harris41 7961: # Gathered now: all privileges that could apply, and condition number
1.52      www      7962: # 
                   7963: #
                   7964: # Full or no access?
                   7965: #
1.29      www      7966: 
1.52      www      7967:     if ($thisallowed=~/F/) {
                   7968: 	return 'F';
                   7969:     }
1.29      www      7970: 
1.52      www      7971:     unless ($thisallowed) {
                   7972:         return '';
                   7973:     }
1.29      www      7974: 
1.52      www      7975: # Restrictions exist, deal with them
                   7976: #
                   7977: #   C:according to course preferences
                   7978: #   R:according to resource settings
                   7979: #   L:unless locked
                   7980: #   X:according to user session state
                   7981: #
                   7982: 
                   7983: # Possibly locked functionality, check all courses
1.54      www      7984: # Locks might take effect only after 10 minutes cache expiration for other
                   7985: # courses, and 2 minutes for current course
1.52      www      7986: 
                   7987:     my $envkey;
                   7988:     if ($thisallowed=~/L/) {
1.1000    raeburn  7989:         foreach $envkey (keys(%env)) {
1.54      www      7990:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7991:                my $courseid=$2;
                   7992:                my $roleid=$1.'.'.$2;
1.92      www      7993:                $courseid=~s/^\///;
1.54      www      7994:                my $expiretime=600;
1.620     albertel 7995:                if ($env{'request.role'} eq $roleid) {
1.54      www      7996: 		  $expiretime=120;
                   7997:                }
                   7998: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7999:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8000:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8001: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8002:                }
1.620     albertel 8003:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8004:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8005: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8006:                        &log($env{'user.domain'},$env{'user.name'},
                   8007:                             $env{'user.home'},
1.57      www      8008:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8009:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8010:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8011: 		       return '';
                   8012:                    }
                   8013:                }
1.620     albertel 8014:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8015:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8016: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8017:                        &log($env{'user.domain'},$env{'user.name'},
                   8018:                             $env{'user.home'},
1.57      www      8019:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8020:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8021:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8022: 		       return '';
                   8023:                    }
                   8024:                }
                   8025: 	   }
1.29      www      8026:        }
1.52      www      8027:     }
                   8028:    
                   8029: #
                   8030: # Rest of the restrictions depend on selected course
                   8031: #
                   8032: 
1.620     albertel 8033:     unless ($env{'request.course.id'}) {
1.766     albertel 8034: 	if ($thisallowed eq 'A') {
                   8035: 	    return 'A';
1.814     raeburn  8036:         } elsif ($thisallowed eq 'B') {
                   8037:             return 'B';
1.766     albertel 8038: 	} else {
                   8039: 	    return '1';
                   8040: 	}
1.52      www      8041:     }
1.29      www      8042: 
1.52      www      8043: #
                   8044: # Now user is definitely in a course
                   8045: #
1.53      www      8046: 
                   8047: 
                   8048: # Course preferences
                   8049: 
                   8050:    if ($thisallowed=~/C/) {
1.620     albertel 8051:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8052:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8053:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8054: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8055: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8056: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8057: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8058: 			$env{'request.course.id'});
                   8059: 	   }
1.237     www      8060:            return '';
                   8061:        }
                   8062: 
1.620     albertel 8063:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8064: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8065: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8066: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8067: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8068: 			$env{'request.course.id'});
                   8069: 	   }
1.54      www      8070:            return '';
                   8071:        }
1.53      www      8072:    }
                   8073: 
                   8074: # Resource preferences
                   8075: 
                   8076:    if ($thisallowed=~/R/) {
1.620     albertel 8077:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8078:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8079: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8080: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8081: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8082: 	   }
                   8083: 	   return '';
1.54      www      8084:        }
1.53      www      8085:    }
1.30      www      8086: 
1.246     www      8087: # Restricted by state or randomout?
1.30      www      8088: 
1.52      www      8089:    if ($thisallowed=~/X/) {
1.620     albertel 8090:       if ($env{'acc.randomout'}) {
1.579     albertel 8091: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8092:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8093:             return ''; 
                   8094:          }
1.247     www      8095:       }
                   8096:       if (&condval($statecond)) {
1.52      www      8097: 	 return '2';
                   8098:       } else {
                   8099:          return '';
                   8100:       }
                   8101:    }
1.30      www      8102: 
1.766     albertel 8103:     if ($thisallowed eq 'A') {
                   8104: 	return 'A';
1.814     raeburn  8105:     } elsif ($thisallowed eq 'B') {
                   8106:         return 'B';
1.766     albertel 8107:     }
1.52      www      8108:    return 'F';
1.232     www      8109: }
1.1162    raeburn  8110: 
1.1192    raeburn  8111: # ------------------------------------------- Check construction space access
                   8112: 
                   8113: sub constructaccess {
                   8114:     my ($url,$setpriv)=@_;
                   8115: 
                   8116: # We do not allow editing of previous versions of files
                   8117:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8118: 
                   8119: # Get username and domain from URL
                   8120:     my ($ownername,$ownerdomain,$ownerhome);
                   8121: 
                   8122:     ($ownerdomain,$ownername) =
1.1325    raeburn  8123:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8124: 
                   8125: # The URL does not really point to any authorspace, forget it
                   8126:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8127: 
                   8128: # Now we need to see if the user has access to the authorspace of
                   8129: # $ownername at $ownerdomain
                   8130: 
                   8131:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8132: # Real author for this?
                   8133:        $ownerhome = $env{'user.home'};
                   8134:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8135:           return ($ownername,$ownerdomain,$ownerhome);
                   8136:        }
                   8137:     } else {
                   8138: # Co-author for this?
                   8139:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8140:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8141:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8142:             return ($ownername,$ownerdomain,$ownerhome);
                   8143:         }
1.1312    raeburn  8144:         if ($env{'request.course.id'}) {
                   8145:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8146:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8147:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8148:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8149:                     return ($ownername,$ownerdomain,$ownerhome);
                   8150:                 }
                   8151:             }
                   8152:         }
1.1192    raeburn  8153:     }
                   8154: 
                   8155: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8156: # we might as well leave
                   8157:    unless ($setpriv) { return ''; }
                   8158: 
                   8159: # Backdoor access?
                   8160:     my $allowed=&allowed('eco',$ownerdomain);
                   8161: # Nope
                   8162:     unless ($allowed) { return ''; }
                   8163: # Looks like we may have access, but could be locked by the owner of the construction space
                   8164:     if ($allowed eq 'U') {
                   8165:         my %blocked=&get('environment',['domcoord.author'],
                   8166:                          $ownerdomain,$ownername);
                   8167: # Is blocked by owner
                   8168:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8169:     }
                   8170:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8171: # Grant temporary access
                   8172:         my $then=$env{'user.login.time'};
1.1209    raeburn  8173:         my $update=$env{'user.update.time'};
1.1192    raeburn  8174:         if (!$update) { $update = $then; }
                   8175:         my $refresh=$env{'user.refresh.time'};
                   8176:         if (!$refresh) { $refresh = $update; }
                   8177:         my $now = time;
                   8178:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8179:                            $now,'ca','constructaccess');
                   8180:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8181:         return($ownername,$ownerdomain,$ownerhome);
                   8182:     }
                   8183: # No business here
                   8184:     return '';
                   8185: }
                   8186: 
1.1282    raeburn  8187: # ----------------------------------------------------------- Content Blocking
                   8188: 
                   8189: {
                   8190: # Caches for faster Course Contents display where content blocking
                   8191: # is in operation (i.e., interval param set) for timed quiz.
                   8192: #
                   8193: # User for whom data are being temporarily cached.
                   8194: my $cacheduser='';
                   8195: # Cached blockers for this user (a hash of blocking items). 
                   8196: my %cachedblockers=();
                   8197: # When the data were last cached.
                   8198: my $cachedlast='';
                   8199: 
                   8200: sub load_all_blockers {
                   8201:     my ($uname,$udom,$blocks)=@_;
                   8202:     if (($uname ne '') && ($udom ne '')) { 
                   8203:         if (($cacheduser eq $uname.':'.$udom) &&
                   8204:             (abs($cachedlast-time)<5)) {
                   8205:             return;
                   8206:         }
                   8207:     }
                   8208:     $cachedlast=time;
                   8209:     $cacheduser=$uname.':'.$udom;
                   8210:     %cachedblockers = &get_commblock_resources($blocks);
                   8211: }
                   8212: 
1.1162    raeburn  8213: sub get_comm_blocks {
                   8214:     my ($cdom,$cnum) = @_;
                   8215:     if ($cdom eq '' || $cnum eq '') {
                   8216:         return unless ($env{'request.course.id'});
                   8217:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8218:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8219:     }
                   8220:     my %commblocks;
                   8221:     my $hashid=$cdom.'_'.$cnum;
                   8222:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8223:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8224:         %commblocks = %{$blocksref};
                   8225:     } else {
                   8226:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8227:         my $cachetime = 600;
                   8228:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8229:     }
                   8230:     return %commblocks;
                   8231: }
                   8232: 
1.1282    raeburn  8233: sub get_commblock_resources {
                   8234:     my ($blocks) = @_;
                   8235:     my %blockers = ();
                   8236:     return %blockers unless ($env{'request.course.id'});
                   8237:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8238:     my %commblocks;
                   8239:     if (ref($blocks) eq 'HASH') {
                   8240:         %commblocks = %{$blocks};
                   8241:     } else {
                   8242:         %commblocks = &get_comm_blocks();
                   8243:     }
1.1282    raeburn  8244:     return %blockers unless (keys(%commblocks) > 0); 
                   8245:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8246:     return %blockers unless (ref($navmap));
1.1162    raeburn  8247:     my $now = time;
                   8248:     foreach my $block (keys(%commblocks)) {
                   8249:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8250:             my ($start,$end) = ($1,$2);
                   8251:             if ($start <= $now && $end >= $now) {
                   8252:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8253:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8254:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8255:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8256:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8257:                             }
                   8258:                         }
                   8259:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8260:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8261:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8262:                             }
                   8263:                         }
                   8264:                     }
                   8265:                 }
                   8266:             }
                   8267:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8268:             my $item = $1;
1.1163    raeburn  8269:             my @to_test;
1.1162    raeburn  8270:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8271:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8272:                     my @interval;
                   8273:                     my $type = 'map';
                   8274:                     if ($item eq 'course') {
                   8275:                         $type = 'course';
                   8276:                         @interval=&EXT("resource.0.interval");
                   8277:                     } else {
                   8278:                         if ($item =~ /___\d+___/) {
                   8279:                             $type = 'resource';
                   8280:                             @interval=&EXT("resource.0.interval",$item);
                   8281:                             if (ref($navmap)) {                        
                   8282:                                 my $res = $navmap->getBySymb($item); 
                   8283:                                 push(@to_test,$res);
                   8284:                             }
1.1162    raeburn  8285:                         } else {
1.1282    raeburn  8286:                             my $mapsymb = &symbread($item,1);
                   8287:                             if ($mapsymb) {
                   8288:                                 if (ref($navmap)) {
                   8289:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8290:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8291:                                     foreach my $res (@to_test) {
                   8292:                                         my $symb = $res->symb();
                   8293:                                         next if ($symb eq $mapsymb);
                   8294:                                         if ($symb ne '') {
                   8295:                                             @interval=&EXT("resource.0.interval",$symb);
                   8296:                                             if ($interval[1] eq 'map') {
                   8297:                                                 last;
1.1162    raeburn  8298:                                             }
                   8299:                                         }
                   8300:                                     }
                   8301:                                 }
                   8302:                             }
                   8303:                         }
1.1282    raeburn  8304:                     }
1.1310    raeburn  8305:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8306:                         my $timelimit = $1; 
1.1282    raeburn  8307:                         my $first_access;
                   8308:                         if ($type eq 'resource') {
                   8309:                             $first_access=&get_first_access($interval[1],$item);
                   8310:                         } elsif ($type eq 'map') {
                   8311:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8312:                         } else {
                   8313:                             $first_access=&get_first_access($interval[1]);
                   8314:                         }
                   8315:                         if ($first_access) {
1.1292    raeburn  8316:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8317:                             if ($timesup > $now) {
                   8318:                                 my $activeblock;
                   8319:                                 foreach my $res (@to_test) {
1.1283    raeburn  8320:                                     if ($res->answerable()) {
1.1282    raeburn  8321:                                         $activeblock = 1;
                   8322:                                         last;
                   8323:                                     }
                   8324:                                 }
                   8325:                                 if ($activeblock) {
                   8326:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8327:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8328:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8329:                                          }
                   8330:                                     }
                   8331:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8332:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8333:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8334:                                         }
1.1162    raeburn  8335:                                     }
                   8336:                                 }
                   8337:                             }
                   8338:                         }
                   8339:                     }
                   8340:                 }
                   8341:             }
                   8342:         }
                   8343:     }
1.1282    raeburn  8344:     return %blockers;
1.1162    raeburn  8345: }
                   8346: 
1.1282    raeburn  8347: sub has_comm_blocking {
                   8348:     my ($priv,$symb,$uri,$blocks) = @_;
                   8349:     my @blockers;
                   8350:     return unless ($env{'request.course.id'});
                   8351:     return unless ($priv eq 'bre');
                   8352:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8353:     return if ($env{'request.state'} eq 'construct');
                   8354:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8355:     return unless (keys(%cachedblockers) > 0);
                   8356:     my (%possibles,@symbs);
                   8357:     if (!$symb) {
                   8358:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8359:     }
1.1282    raeburn  8360:     if ($symb) {
                   8361:         @symbs = ($symb);
                   8362:     } elsif (keys(%possibles)) { 
                   8363:         @symbs = keys(%possibles);
                   8364:     }
                   8365:     my $noblock;
                   8366:     foreach my $symb (@symbs) {
                   8367:         last if ($noblock);
                   8368:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8369:         foreach my $block (keys(%cachedblockers)) {
                   8370:             if ($block =~ /^firstaccess____(.+)$/) {
                   8371:                 my $item = $1;
                   8372:                 if (($item eq $map) || ($item eq $symb)) {
                   8373:                     $noblock = 1;
                   8374:                     last;
                   8375:                 }
                   8376:             }
                   8377:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8378:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8379:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8380:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8381:                             push(@blockers,$block);
                   8382:                         }
                   8383:                     }
                   8384:                 }
1.1162    raeburn  8385:             }
1.1282    raeburn  8386:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8387:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8388:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8389:                         push(@blockers,$block);
                   8390:                     }
                   8391:                 }
1.1162    raeburn  8392:             }
                   8393:         }
                   8394:     }
1.1282    raeburn  8395:     return if ($noblock);
                   8396:     return @blockers;
                   8397: }
1.1162    raeburn  8398: }
                   8399: 
1.1282    raeburn  8400: # -------------------------------- Deversion and split uri into path an filename   
                   8401: 
1.1133    foxr     8402: #
1.1282    raeburn  8403: #   Removes the version from a URI and
1.1133    foxr     8404: #   splits it in to its filename and path to the filename.
                   8405: #   Seems like File::Basename could have done this more clearly.
                   8406: #   Parameters:
                   8407: #      $uri   - input URI
                   8408: #   Returns:
                   8409: #     Two element list consisting of 
                   8410: #     $pathname  - the URI up to and excluding the trailing /
                   8411: #     $filename  - The part of the URI following the last /
                   8412: #  NOTE:
                   8413: #    Another realization of this is simply:
                   8414: #    use File::Basename;
                   8415: #    ...
                   8416: #    $uri = shift;
                   8417: #    $filename = basename($uri);
                   8418: #    $path     = dirname($uri);
                   8419: #    return ($filename, $path);
                   8420: #
                   8421: #     The implementation below is probably faster however.
                   8422: #
1.710     albertel 8423: sub split_uri_for_cond {
                   8424:     my $uri=&deversion(&declutter(shift));
                   8425:     my @uriparts=split(/\//,$uri);
                   8426:     my $filename=pop(@uriparts);
                   8427:     my $pathname=join('/',@uriparts);
                   8428:     return ($pathname,$filename);
                   8429: }
1.232     www      8430: # --------------------------------------------------- Is a resource on the map?
                   8431: 
                   8432: sub is_on_map {
1.710     albertel 8433:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8434:     #Trying to find the conditional for the file
1.620     albertel 8435:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8436: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8437:     if ($match) {
1.289     bowersj2 8438: 	return (1,$1);
                   8439:     } else {
1.434     www      8440: 	return (0,0);
1.289     bowersj2 8441:     }
1.12      www      8442: }
                   8443: 
1.427     www      8444: # --------------------------------------------------------- Get symb from alias
                   8445: 
                   8446: sub get_symb_from_alias {
                   8447:     my $symb=shift;
                   8448:     my ($map,$resid,$url)=&decode_symb($symb);
                   8449: # Already is a symb
                   8450:     if ($url) { return $symb; }
                   8451: # Must be an alias
                   8452:     my $aliassymb='';
                   8453:     my %bighash;
1.620     albertel 8454:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8455:                             &GDBM_READER(),0640)) {
                   8456:         my $rid=$bighash{'mapalias_'.$symb};
                   8457: 	if ($rid) {
                   8458: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8459: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8460: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8461: 	}
                   8462:         untie %bighash;
                   8463:     }
                   8464:     return $aliassymb;
                   8465: }
                   8466: 
1.12      www      8467: # ----------------------------------------------------------------- Define Role
                   8468: 
                   8469: sub definerole {
                   8470:   if (allowed('mcr','/')) {
1.1326    raeburn  8471:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8472:     foreach my $role (split(':',$sysrole)) {
                   8473: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8474:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8475:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8476: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8477:                return "refused:s:$crole&$cqual"; 
                   8478:             }
                   8479:         }
1.191     harris41 8480:     }
1.800     albertel 8481:     foreach my $role (split(':',$domrole)) {
                   8482: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8483:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8484:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8485: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8486:                return "refused:d:$crole&$cqual"; 
                   8487:             }
                   8488:         }
1.191     harris41 8489:     }
1.800     albertel 8490:     foreach my $role (split(':',$courole)) {
                   8491: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8492:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8493:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8494: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8495:                return "refused:c:$crole&$cqual"; 
                   8496:             }
                   8497:         }
1.191     harris41 8498:     }
1.1326    raeburn  8499:     my $uhome;
                   8500:     if (($uname ne '') && ($udom ne '')) {
                   8501:         $uhome = &homeserver($uname,$udom);
                   8502:         return $uhome if ($uhome eq 'no_host');
                   8503:     } else {
                   8504:         $uname = $env{'user.name'};
                   8505:         $udom = $env{'user.domain'};
                   8506:         $uhome = $env{'user.home'};
                   8507:     }
1.620     albertel 8508:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8509:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8510:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8511:     return reply($command,$uhome);
1.12      www      8512:   } else {
                   8513:     return 'refused';
                   8514:   }
1.105     harris41 8515: }
                   8516: 
                   8517: # ---------------- Make a metadata query against the network of library servers
                   8518: 
                   8519: sub metadata_query {
1.1237    raeburn  8520:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8521:     my %rhash;
1.845     albertel 8522:     my %libserv = &all_library();
1.244     matthew  8523:     my @server_list = (defined($server_array) ? @$server_array
                   8524:                                               : keys(%libserv) );
                   8525:     for my $server (@server_list) {
1.1237    raeburn  8526:         my $domains = ''; 
                   8527:         if (ref($domains_hash) eq 'HASH') {
                   8528:             $domains = $domains_hash->{$server}; 
                   8529:         }
1.118     harris41 8530: 	unless ($custom or $customshow) {
1.1237    raeburn  8531: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8532: 	    $rhash{$server}=$reply;
                   8533: 	}
                   8534: 	else {
                   8535: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8536: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8537: 			     $server);
                   8538: 	    $rhash{$server}=$reply;
                   8539: 	}
1.112     harris41 8540:     }
1.118     harris41 8541:     return \%rhash;
1.240     www      8542: }
                   8543: 
                   8544: # ----------------------------------------- Send log queries and wait for reply
                   8545: 
                   8546: sub log_query {
                   8547:     my ($uname,$udom,$query,%filters)=@_;
                   8548:     my $uhome=&homeserver($uname,$udom);
                   8549:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8550:     my $uhost=&hostname($uhome);
1.800     albertel 8551:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8552:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8553:                        $uhome);
1.479     albertel 8554:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8555:     return get_query_reply($queryid);
                   8556: }
                   8557: 
1.818     raeburn  8558: # -------------------------- Update MySQL table for portfolio file
                   8559: 
                   8560: sub update_portfolio_table {
1.821     raeburn  8561:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8562:     if ($group ne '') {
                   8563:         $file_name =~s /^\Q$group\E//;
                   8564:     }
1.818     raeburn  8565:     my $homeserver = &homeserver($uname,$udom);
                   8566:     my $queryid=
1.821     raeburn  8567:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8568:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8569:     my $reply = &get_query_reply($queryid);
                   8570:     return $reply;
                   8571: }
                   8572: 
1.899     raeburn  8573: # -------------------------- Update MySQL allusers table
                   8574: 
                   8575: sub update_allusers_table {
                   8576:     my ($uname,$udom,$names) = @_;
                   8577:     my $homeserver = &homeserver($uname,$udom);
                   8578:     my $queryid=
                   8579:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8580:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8581:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8582:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8583:                'generation='.&escape($names->{'generation'}).'%%'.
                   8584:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8585:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8586:     return;
1.899     raeburn  8587: }
                   8588: 
1.508     raeburn  8589: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8590: 
                   8591: sub fetch_enrollment_query {
1.511     raeburn  8592:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8593:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8594:     my $maxtries = 1;
1.508     raeburn  8595:     if ($context eq 'automated') {
                   8596:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8597:         $sleep = 2;
                   8598:         $loopmax = 100;
1.547     raeburn  8599:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8600:     } else {
                   8601:         $homeserver = &homeserver($cnum,$dom);
                   8602:     }
1.838     albertel 8603:     my $host=&hostname($homeserver);
1.506     raeburn  8604:     my $cmd = '';
1.1000    raeburn  8605:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8606:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8607:     }
                   8608:     $cmd =~ s/%%$//;
                   8609:     $cmd = &escape($cmd);
                   8610:     my $query = 'fetchenrollment';
1.620     albertel 8611:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8612:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8613:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8614:         return 'error: '.$queryid;
                   8615:     }
1.1317    raeburn  8616:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8617:     my $tries = 1;
                   8618:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8619:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8620:         $tries ++;
                   8621:     }
1.526     raeburn  8622:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8623:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8624:     } else {
1.901     albertel 8625:         my @responses = split(/:/,$reply);
1.1322    raeburn  8626:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8627:             foreach my $line (@responses) {
                   8628:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8629:                 $$replyref{$key} = $value;
                   8630:             }
                   8631:         } else {
1.1117    foxr     8632:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8633:             foreach my $line (@responses) {
                   8634:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8635:                 $$replyref{$key} = $value;
                   8636:                 if ($value > 0) {
1.800     albertel 8637:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8638:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8639:                         my $destname = $pathname.'/'.$filename;
                   8640:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8641:                         if ($xml_classlist =~ /^error/) {
                   8642:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8643:                         } else {
1.1359    raeburn  8644:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8645:                                 print FILE &unescape($xml_classlist);
                   8646:                                 close(FILE);
1.526     raeburn  8647:                             } else {
                   8648:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8649:                             }
                   8650:                         }
                   8651:                     }
                   8652:                 }
                   8653:             }
                   8654:         }
                   8655:         return 'ok';
                   8656:     }
                   8657:     return 'error';
                   8658: }
                   8659: 
1.242     www      8660: sub get_query_reply {
1.1317    raeburn  8661:     my ($queryid,$sleep,$loopmax) = @_;;
                   8662:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8663:         $sleep = 0.2;
                   8664:     }
                   8665:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8666:         $loopmax = 100;
                   8667:     }
1.1117    foxr     8668:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8669:     my $reply='';
1.1317    raeburn  8670:     for (1..$loopmax) {
                   8671: 	sleep($sleep);
1.240     www      8672:         if (-e $replyfile.'.end') {
1.1359    raeburn  8673: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8674: 		$reply = join('',<$fh>);
                   8675: 		close($fh);
1.240     www      8676: 	   } else { return 'error: reply_file_error'; }
1.242     www      8677:            return &unescape($reply);
                   8678: 	}
1.240     www      8679:     }
1.242     www      8680:     return 'timeout:'.$queryid;
1.240     www      8681: }
                   8682: 
                   8683: sub courselog_query {
1.241     www      8684: #
                   8685: # possible filters:
                   8686: # url: url or symb
                   8687: # username
                   8688: # domain
                   8689: # action: view, submit, grade
                   8690: # start: timestamp
                   8691: # end: timestamp
                   8692: #
1.240     www      8693:     my (%filters)=@_;
1.620     albertel 8694:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8695:     if ($filters{'url'}) {
                   8696: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8697:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8698:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8699:     }
1.620     albertel 8700:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8701:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8702:     return &log_query($cname,$cdom,'courselog',%filters);
                   8703: }
                   8704: 
                   8705: sub userlog_query {
1.858     raeburn  8706: #
                   8707: # possible filters:
                   8708: # action: log check role
                   8709: # start: timestamp
                   8710: # end: timestamp
                   8711: #
1.240     www      8712:     my ($uname,$udom,%filters)=@_;
                   8713:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8714: }
                   8715: 
1.506     raeburn  8716: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8717: 
                   8718: sub auto_run {
1.508     raeburn  8719:     my ($cnum,$cdom) = @_;
1.876     raeburn  8720:     my $response = 0;
                   8721:     my $settings;
                   8722:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8723:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8724:         $settings = $domconfig{'autoenroll'};
                   8725:         if ($settings->{'run'} eq '1') {
                   8726:             $response = 1;
                   8727:         }
                   8728:     } else {
1.934     raeburn  8729:         my $homeserver;
                   8730:         if (&is_course($cdom,$cnum)) {
                   8731:             $homeserver = &homeserver($cnum,$cdom);
                   8732:         } else {
                   8733:             $homeserver = &domain($cdom,'primary');
                   8734:         }
                   8735:         if ($homeserver ne 'no_host') {
                   8736:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8737:         }
1.876     raeburn  8738:     }
1.506     raeburn  8739:     return $response;
                   8740: }
1.776     albertel 8741: 
1.506     raeburn  8742: sub auto_get_sections {
1.508     raeburn  8743:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8744:     my $homeserver;
                   8745:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8746:         $homeserver = &homeserver($cnum,$cdom);
                   8747:     }
                   8748:     if (!defined($homeserver)) { 
                   8749:         if ($cdom =~ /^$match_domain$/) {
                   8750:             $homeserver = &domain($cdom,'primary');
                   8751:         }
                   8752:     }
                   8753:     my @secs;
                   8754:     if (defined($homeserver)) {
                   8755:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8756:         unless ($response eq 'refused') {
                   8757:             @secs = split(/:/,$response);
                   8758:         }
1.506     raeburn  8759:     }
                   8760:     return @secs;
                   8761: }
1.776     albertel 8762: 
1.506     raeburn  8763: sub auto_new_course {
1.1099    raeburn  8764:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8765:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8766:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8767:     return $response;
                   8768: }
1.776     albertel 8769: 
1.506     raeburn  8770: sub auto_validate_courseID {
1.508     raeburn  8771:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8772:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8773:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8774:     return $response;
                   8775: }
1.776     albertel 8776: 
1.1007    raeburn  8777: sub auto_validate_instcode {
1.1020    raeburn  8778:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8779:     my ($homeserver,$response);
                   8780:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8781:         $homeserver = &homeserver($cnum,$cdom);
                   8782:     }
                   8783:     if (!defined($homeserver)) {
                   8784:         if ($cdom =~ /^$match_domain$/) {
                   8785:             $homeserver = &domain($cdom,'primary');
                   8786:         }
                   8787:     }
1.1065    raeburn  8788:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8789:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8790:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8791:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8792: }
                   8793: 
1.506     raeburn  8794: sub auto_create_password {
1.873     raeburn  8795:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8796:     my ($homeserver,$response);
1.506     raeburn  8797:     my $create_passwd = 0;
                   8798:     my $authchk = '';
1.873     raeburn  8799:     if ($udom =~ /^$match_domain$/) {
                   8800:         $homeserver = &domain($udom,'primary');
                   8801:     }
                   8802:     if ($homeserver eq '') {
                   8803:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8804:             $homeserver = &homeserver($cnum,$cdom);
                   8805:         }
                   8806:     }
                   8807:     if ($homeserver eq '') {
                   8808:         $authchk = 'nodomain';
1.506     raeburn  8809:     } else {
1.873     raeburn  8810:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8811:         if ($response eq 'refused') {
                   8812:             $authchk = 'refused';
                   8813:         } else {
1.901     albertel 8814:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8815:         }
1.506     raeburn  8816:     }
                   8817:     return ($authparam,$create_passwd,$authchk);
                   8818: }
                   8819: 
1.706     raeburn  8820: sub auto_photo_permission {
                   8821:     my ($cnum,$cdom,$students) = @_;
                   8822:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8823:     my ($outcome,$perm_reqd,$conditions) = 
                   8824: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8825:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8826: 	return (undef,undef);
                   8827:     }
1.706     raeburn  8828:     return ($outcome,$perm_reqd,$conditions);
                   8829: }
                   8830: 
                   8831: sub auto_checkphotos {
                   8832:     my ($uname,$udom,$pid) = @_;
                   8833:     my $homeserver = &homeserver($uname,$udom);
                   8834:     my ($result,$resulttype);
                   8835:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8836: 				   &escape($uname).':'.&escape($pid),
                   8837: 				   $homeserver));
1.709     albertel 8838:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8839: 	return (undef,undef);
                   8840:     }
1.706     raeburn  8841:     if ($outcome) {
                   8842:         ($result,$resulttype) = split(/:/,$outcome);
                   8843:     } 
                   8844:     return ($result,$resulttype);
                   8845: }
                   8846: 
                   8847: sub auto_photochoice {
                   8848:     my ($cnum,$cdom) = @_;
                   8849:     my $homeserver = &homeserver($cnum,$cdom);
                   8850:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8851: 						       &escape($cdom),
                   8852: 						       $homeserver)));
1.709     albertel 8853:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8854: 	return (undef,undef);
                   8855:     }
1.706     raeburn  8856:     return ($update,$comment);
                   8857: }
                   8858: 
                   8859: sub auto_photoupdate {
                   8860:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8861:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8862:     my $host=&hostname($homeserver);
1.706     raeburn  8863:     my $cmd = '';
                   8864:     my $maxtries = 1;
1.800     albertel 8865:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8866:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8867:     }
                   8868:     $cmd =~ s/%%$//;
                   8869:     $cmd = &escape($cmd);
                   8870:     my $query = 'institutionalphotos';
                   8871:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8872:     unless ($queryid=~/^\Q$host\E\_/) {
                   8873:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8874:         return 'error: '.$queryid;
                   8875:     }
                   8876:     my $reply = &get_query_reply($queryid);
                   8877:     my $tries = 1;
                   8878:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8879:         $reply = &get_query_reply($queryid);
                   8880:         $tries ++;
                   8881:     }
                   8882:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8883:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8884:     } else {
                   8885:         my @responses = split(/:/,$reply);
                   8886:         my $outcome = shift(@responses); 
                   8887:         foreach my $item (@responses) {
                   8888:             my ($key,$value) = split(/=/,$item);
                   8889:             $$photo{$key} = $value;
                   8890:         }
                   8891:         return $outcome;
                   8892:     }
                   8893:     return 'error';
                   8894: }
                   8895: 
1.521     raeburn  8896: sub auto_instcode_format {
1.793     albertel 8897:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8898: 	$cat_order) = @_;
1.521     raeburn  8899:     my $courses = '';
1.772     raeburn  8900:     my @homeservers;
1.521     raeburn  8901:     if ($caller eq 'global') {
1.841     albertel 8902: 	my %servers = &get_servers($codedom,'library');
                   8903: 	foreach my $tryserver (keys(%servers)) {
                   8904: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8905: 		push(@homeservers,$tryserver);
                   8906: 	    }
1.584     raeburn  8907:         }
1.1022    raeburn  8908:     } elsif ($caller eq 'requests') {
                   8909:         if ($codedom =~ /^$match_domain$/) {
                   8910:             my $chome = &domain($codedom,'primary');
                   8911:             unless ($chome eq 'no_host') {
                   8912:                 push(@homeservers,$chome);
                   8913:             }
                   8914:         }
1.521     raeburn  8915:     } else {
1.772     raeburn  8916:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8917:     }
1.793     albertel 8918:     foreach my $code (keys(%{$instcodes})) {
                   8919:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8920:     }
                   8921:     chop($courses);
1.772     raeburn  8922:     my $ok_response = 0;
                   8923:     my $response;
                   8924:     while (@homeservers > 0 && $ok_response == 0) {
                   8925:         my $server = shift(@homeservers); 
                   8926:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8927:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8928:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8929: 		split(/:/,$response);
1.772     raeburn  8930:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8931:             push(@{$codetitles},&str2array($codetitles_str));
                   8932:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8933:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8934:             $ok_response = 1;
                   8935:         }
                   8936:     }
                   8937:     if ($ok_response) {
1.521     raeburn  8938:         return 'ok';
1.772     raeburn  8939:     } else {
                   8940:         return $response;
1.521     raeburn  8941:     }
                   8942: }
                   8943: 
1.792     raeburn  8944: sub auto_instcode_defaults {
                   8945:     my ($domain,$returnhash,$code_order) = @_;
                   8946:     my @homeservers;
1.841     albertel 8947: 
                   8948:     my %servers = &get_servers($domain,'library');
                   8949:     foreach my $tryserver (keys(%servers)) {
                   8950: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8951: 	    push(@homeservers,$tryserver);
                   8952: 	}
1.792     raeburn  8953:     }
1.841     albertel 8954: 
1.792     raeburn  8955:     my $response;
1.841     albertel 8956:     foreach my $server (@homeservers) {
1.792     raeburn  8957:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8958:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8959: 	
                   8960: 	foreach my $pair (split(/\&/,$response)) {
                   8961: 	    my ($name,$value)=split(/\=/,$pair);
                   8962: 	    if ($name eq 'code_order') {
                   8963: 		@{$code_order} = split(/\&/,&unescape($value));
                   8964: 	    } else {
                   8965: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8966: 	    }
                   8967: 	}
                   8968: 	return 'ok';
1.792     raeburn  8969:     }
1.841     albertel 8970: 
                   8971:     return $response;
1.1003    raeburn  8972: }
                   8973: 
                   8974: sub auto_possible_instcodes {
1.1007    raeburn  8975:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8976:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8977:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8978:         return;
                   8979:     }
1.1003    raeburn  8980:     my (@homeservers,$uhome);
                   8981:     if (defined(&domain($domain,'primary'))) {
                   8982:         $uhome=&domain($domain,'primary');
                   8983:         push(@homeservers,&domain($domain,'primary'));
                   8984:     } else {
                   8985:         my %servers = &get_servers($domain,'library');
                   8986:         foreach my $tryserver (keys(%servers)) {
                   8987:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8988:                 push(@homeservers,$tryserver);
                   8989:             }
                   8990:         }
                   8991:     }
                   8992:     my $response;
                   8993:     foreach my $server (@homeservers) {
                   8994:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8995:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8996:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8997:             split(':',$response);
                   8998:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8999:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9000:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9001:             my ($name,$value)=split('=',$item);
                   9002:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9003:         }
                   9004:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9005:             my ($name,$value)=split('=',$item);
                   9006:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9007:         }
                   9008:         return 'ok';
                   9009:     }
                   9010:     return $response;
                   9011: }
1.792     raeburn  9012: 
1.1010    raeburn  9013: sub auto_courserequest_checks {
                   9014:     my ($dom) = @_;
1.1020    raeburn  9015:     my ($homeserver,%validations);
                   9016:     if ($dom =~ /^$match_domain$/) {
                   9017:         $homeserver = &domain($dom,'primary');
                   9018:     }
                   9019:     unless ($homeserver eq 'no_host') {
                   9020:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9021:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9022:             my @items = split(/&/,$response);
                   9023:             foreach my $item (@items) {
                   9024:                 my ($key,$value) = split('=',$item);
                   9025:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9026:             }
                   9027:         }
                   9028:     }
1.1010    raeburn  9029:     return %validations; 
                   9030: }
                   9031: 
1.1020    raeburn  9032: sub auto_courserequest_validation {
1.1255    raeburn  9033:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9034:     my ($homeserver,$response);
                   9035:     if ($dom =~ /^$match_domain$/) {
                   9036:         $homeserver = &domain($dom,'primary');
                   9037:     }
1.1255    raeburn  9038:     unless ($homeserver eq 'no_host') {
                   9039:         my $customdata;
                   9040:         if (ref($custominfo) eq 'HASH') {
                   9041:             $customdata = &freeze_escape($custominfo);
                   9042:         }
1.1020    raeburn  9043:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9044:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9045:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9046:                                     $customdata,$homeserver));
1.1020    raeburn  9047:     }
                   9048:     return $response;
                   9049: }
                   9050: 
1.777     albertel 9051: sub auto_validate_class_sec {
1.918     raeburn  9052:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9053:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9054:     my $ownerlist;
                   9055:     if (ref($owners) eq 'ARRAY') {
                   9056:         $ownerlist = join(',',@{$owners});
                   9057:     } else {
                   9058:         $ownerlist = $owners;
                   9059:     }
1.773     raeburn  9060:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9061:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9062:     return $response;
                   9063: }
                   9064: 
1.1367    raeburn  9065: sub auto_validate_instclasses {
                   9066:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9067:     my ($homeserver,%validations);
                   9068:     $homeserver = &homeserver($cnum,$cdom);
                   9069:     unless ($homeserver eq 'no_host') {
                   9070:         my $ownerlist;
                   9071:         if (ref($owners) eq 'ARRAY') {
                   9072:             $ownerlist = join(',',@{$owners});
                   9073:         } else {
                   9074:             $ownerlist = $owners;
                   9075:         }
                   9076:         if (ref($classesref) eq 'HASH') {
                   9077:             my $classes = &freeze_escape($classesref);
                   9078:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9079:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9080:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9081:                 my @items = split(/&/,$response);
                   9082:                 foreach my $item (@items) {
                   9083:                     my ($key,$value) = split('=',$item);
                   9084:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9085:                 }
                   9086:             }
                   9087:         }
                   9088:     }
                   9089:     return %validations;
                   9090: }
                   9091: 
1.1248    raeburn  9092: sub auto_crsreq_update {
                   9093:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9094:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9095:     my ($homeserver,%crsreqresponse);
                   9096:     if ($cdom =~ /^$match_domain$/) {
                   9097:         $homeserver = &domain($cdom,'primary');
                   9098:     }
                   9099:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9100:         my $info;
                   9101:         if (ref($inbound) eq 'HASH') {
                   9102:             $info = &freeze_escape($inbound);
                   9103:         }
                   9104:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9105:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9106:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9107:                             &escape($title).':'.&escape($code).':'.
                   9108:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9109:                             $homeserver);
1.1248    raeburn  9110:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9111:             my @items = split(/&/,$response);
                   9112:             foreach my $item (@items) {
                   9113:                 my ($key,$value) = split('=',$item);
                   9114:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9115:             }
                   9116:         }
                   9117:     }
                   9118:     return \%crsreqresponse;
                   9119: }
                   9120: 
1.1305    raeburn  9121: sub auto_export_grades {
1.1309    raeburn  9122:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9123:     my ($homeserver,%exportresponse);
                   9124:     if ($cdom =~ /^$match_domain$/) {
                   9125:         $homeserver = &domain($cdom,'primary');
                   9126:     }
                   9127:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9128:         my $info;
                   9129:         if (ref($inforef) eq 'HASH') {
                   9130:             $info = &freeze_escape($inforef);
                   9131:         }
                   9132:         if (ref($gradesref) eq 'HASH') {
                   9133:             my $grades = &freeze_escape($gradesref);
                   9134:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9135:                                 $info.':'.$grades,$homeserver);
                   9136:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9137:                 my @items = split(/&/,$response);
                   9138:                 foreach my $item (@items) {
                   9139:                     my ($key,$value) = split('=',$item);
                   9140:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9141:                 }
                   9142:             }
                   9143:         }
                   9144:     }
                   9145:     return \%exportresponse;
1.1305    raeburn  9146: }
                   9147: 
1.1287    raeburn  9148: sub check_instcode_cloning {
                   9149:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9150:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9151:         return;
                   9152:     }
                   9153:     my $canclone;
                   9154:     if (@{$code_order} > 0) {
                   9155:         my $instcoderegexp ='^';
                   9156:         my @clonecodes = split(/\&/,$cloner);
                   9157:         foreach my $item (@{$code_order}) {
                   9158:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9159:                 foreach my $pair (@clonecodes) {
                   9160:                     my ($key,$val) = split(/\=/,$pair,2);
                   9161:                     $val = &unescape($val);
                   9162:                     if ($key eq $item) {
                   9163:                         $instcoderegexp .= '('.$val.')';
                   9164:                         last;
                   9165:                     }
                   9166:                 }
                   9167:             } else {
                   9168:                 $instcoderegexp .= $codedefaults->{$item};
                   9169:             }
                   9170:         }
                   9171:         $instcoderegexp .= '$';
                   9172:         my (@from,@to);
                   9173:         eval {
                   9174:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9175:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9176:         };
                   9177:         if ((@from > 0) && (@to > 0)) {
                   9178:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9179:             if (!@diffs) {
                   9180:                 $canclone = 1;
                   9181:             }
                   9182:         }
                   9183:     }
                   9184:     return $canclone;
                   9185: }
                   9186: 
                   9187: sub default_instcode_cloning {
                   9188:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9189:     my (%codedefaults,@code_order,$canclone);
                   9190:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9191:         %codedefaults = %{$codedefaultsref};
                   9192:         @code_order = @{$codeorderref};
                   9193:     } elsif ($clonedom) {
                   9194:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9195:     }
                   9196:     if (($domdefclone) && (@code_order)) {
                   9197:         my @clonecodes = split(/\+/,$domdefclone);
                   9198:         my $instcoderegexp ='^';
                   9199:         foreach my $item (@code_order) {
                   9200:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9201:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9202:             } else {
                   9203:                 $instcoderegexp .= $codedefaults{$item};
                   9204:             }
                   9205:         }
                   9206:         $instcoderegexp .= '$';
                   9207:         my (@from,@to);
                   9208:         eval {
                   9209:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9210:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9211:         };
                   9212:         if ((@from > 0) && (@to > 0)) {
                   9213:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9214:             if (!@diffs) {
                   9215:                 $canclone = 1;
                   9216:             }
                   9217:         }
                   9218:     }
                   9219:     return $canclone;
                   9220: }
                   9221: 
1.679     raeburn  9222: # ------------------------------------------------------- Course Group routines
                   9223: 
                   9224: sub get_coursegroups {
1.809     raeburn  9225:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9226:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9227: }
                   9228: 
1.679     raeburn  9229: sub modify_coursegroup {
                   9230:     my ($cdom,$cnum,$groupsettings) = @_;
                   9231:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9232: }
                   9233: 
1.809     raeburn  9234: sub toggle_coursegroup_status {
                   9235:     my ($cdom,$cnum,$group,$action) = @_;
                   9236:     my ($from_namespace,$to_namespace);
                   9237:     if ($action eq 'delete') {
                   9238:         $from_namespace = 'coursegroups';
                   9239:         $to_namespace = 'deleted_groups';
                   9240:     } else {
                   9241:         $from_namespace = 'deleted_groups';
                   9242:         $to_namespace = 'coursegroups';
                   9243:     }
                   9244:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9245:     if (my $tmp = &error(%curr_group)) {
                   9246:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9247:         return ('read error',$tmp);
                   9248:     } else {
                   9249:         my %savedsettings = %curr_group; 
1.809     raeburn  9250:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9251:         my $deloutcome;
                   9252:         if ($result eq 'ok') {
1.809     raeburn  9253:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9254:         } else {
                   9255:             return ('write error',$result);
                   9256:         }
                   9257:         if ($deloutcome eq 'ok') {
                   9258:             return 'ok';
                   9259:         } else {
                   9260:             return ('delete error',$deloutcome);
                   9261:         }
                   9262:     }
                   9263: }
                   9264: 
1.679     raeburn  9265: sub modify_group_roles {
1.957     raeburn  9266:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9267:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9268:     my $role = 'gr/'.&escape($userprivs);
                   9269:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9270:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9271:     if ($result eq 'ok') {
                   9272:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9273:     }
1.679     raeburn  9274:     return $result;
                   9275: }
                   9276: 
                   9277: sub modify_coursegroup_membership {
                   9278:     my ($cdom,$cnum,$membership) = @_;
                   9279:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9280:     return $result;
                   9281: }
                   9282: 
1.682     raeburn  9283: sub get_active_groups {
                   9284:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9285:     my $now = time;
                   9286:     my %groups = ();
                   9287:     foreach my $key (keys(%env)) {
1.811     albertel 9288:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9289:             my ($start,$end) = split(/\./,$env{$key});
                   9290:             if (($end!=0) && ($end<$now)) { next; }
                   9291:             if (($start!=0) && ($start>$now)) { next; }
                   9292:             if ($1 eq $cdom && $2 eq $cnum) {
                   9293:                 $groups{$3} = $env{$key} ;
                   9294:             }
                   9295:         }
                   9296:     }
                   9297:     return %groups;
                   9298: }
                   9299: 
1.683     raeburn  9300: sub get_group_membership {
                   9301:     my ($cdom,$cnum,$group) = @_;
                   9302:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9303: }
                   9304: 
                   9305: sub get_users_groups {
                   9306:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9307:     my @usersgroups;
1.683     raeburn  9308:     my $cachetime=1800;
                   9309: 
                   9310:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9311:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9312:     if (defined($cached)) {
1.734     albertel 9313:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9314:     } else {  
                   9315:         $grouplist = '';
1.816     raeburn  9316:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9317:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9318:         my $access_end = $env{'course.'.$courseid.
                   9319:                               '.default_enrollment_end_date'};
                   9320:         my $now = time;
                   9321:         foreach my $key (keys(%roleshash)) {
                   9322:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9323:                 my $group = $1;
                   9324:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9325:                     my $start = $2;
                   9326:                     my $end = $1;
                   9327:                     if ($start == -1) { next; } # deleted from group
                   9328:                     if (($start!=0) && ($start>$now)) { next; }
                   9329:                     if (($end!=0) && ($end<$now)) {
                   9330:                         if ($access_end && $access_end < $now) {
                   9331:                             if ($access_end - $end < 86400) {
                   9332:                                 push(@usersgroups,$group);
1.733     raeburn  9333:                             }
                   9334:                         }
1.817     raeburn  9335:                         next;
1.733     raeburn  9336:                     }
1.817     raeburn  9337:                     push(@usersgroups,$group);
1.683     raeburn  9338:                 }
                   9339:             }
                   9340:         }
1.817     raeburn  9341:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9342:         $grouplist = join(':',@usersgroups);
                   9343:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9344:     }
1.733     raeburn  9345:     return @usersgroups;
1.683     raeburn  9346: }
                   9347: 
                   9348: sub devalidate_getgroups_cache {
                   9349:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9350:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9351: 
1.683     raeburn  9352:     my $hashid="$udom:$uname:$courseid";
                   9353:     &devalidate_cache_new('getgroups',$hashid);
                   9354: }
                   9355: 
1.12      www      9356: # ------------------------------------------------------------------ Plain Text
                   9357: 
                   9358: sub plaintext {
1.988     raeburn  9359:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9360:     if ($short =~ m{^cr/}) {
1.758     albertel 9361: 	return (split('/',$short))[-1];
                   9362:     }
1.742     raeburn  9363:     if (!defined($cid)) {
                   9364:         $cid = $env{'request.course.id'};
                   9365:     }
                   9366:     my %rolenames = (
1.1008    raeburn  9367:                       Course    => 'std',
                   9368:                       Community => 'alt1',
1.1305    raeburn  9369:                       Placement => 'std',
1.742     raeburn  9370:                     );
1.1037    raeburn  9371:     if ($cid ne '') {
                   9372:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9373:             unless ($forcedefault) {
                   9374:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9375:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9376:                 return &Apache::lonlocal::mt($roletext);
                   9377:             }
                   9378:         }
                   9379:     }
                   9380:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9381:         (defined($rolenames{$type})) && 
                   9382:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9383:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9384:     } elsif ($cid ne '') {
                   9385:         my $crstype = $env{'course.'.$cid.'.type'};
                   9386:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9387:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9388:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9389:         }
1.742     raeburn  9390:     }
1.1037    raeburn  9391:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9392: }
                   9393: 
                   9394: # ----------------------------------------------------------------- Assign Role
                   9395: 
                   9396: sub assignrole {
1.957     raeburn  9397:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9398:         $context)=@_;
1.21      www      9399:     my $mrole;
                   9400:     if ($role =~ /^cr\//) {
1.393     www      9401:         my $cwosec=$url;
1.811     albertel 9402:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9403: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9404:            my $refused = 1;
                   9405:            if ($context eq 'requestcourses') {
                   9406:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9407:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9408:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9409:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9410:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9411:                            if ($crsenv{'internal.courseowner'} eq
                   9412:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9413:                                $refused = '';
                   9414:                            }
                   9415:                        }
                   9416:                    }
                   9417:                }
                   9418:            }
                   9419:            if ($refused) {
                   9420:                &logthis('Refused custom assignrole: '.
                   9421:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9422:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9423:                return 'refused';
                   9424:            }
1.104     www      9425:         }
1.21      www      9426:         $mrole='cr';
1.678     raeburn  9427:     } elsif ($role =~ /^gr\//) {
                   9428:         my $cwogrp=$url;
1.811     albertel 9429:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9430:         unless (&allowed('mdg',$cwogrp)) {
                   9431:             &logthis('Refused group assignrole: '.
                   9432:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9433:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9434:             return 'refused';
                   9435:         }
                   9436:         $mrole='gr';
1.21      www      9437:     } else {
1.82      www      9438:         my $cwosec=$url;
1.811     albertel 9439:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9440:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9441:             my $refused;
                   9442:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9443:                 if (!(&allowed('c'.$role,$url))) {
                   9444:                     $refused = 1;
                   9445:                 }
                   9446:             } else {
                   9447:                 $refused = 1;
                   9448:             }
1.947     raeburn  9449:             if ($refused) {
1.1045    raeburn  9450:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9451:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9452:                     my %crsenv;
                   9453:                     if ($role eq 'cc' || $role eq 'co') {
                   9454:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9455:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9456:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9457:                                 if ($crsenv{'internal.courseowner'} eq 
                   9458:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9459:                                     $refused = '';
                   9460:                                 }
                   9461:                             }
                   9462:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9463:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9464:                                 if ($crsenv{'internal.courseowner'} eq 
                   9465:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9466:                                     $refused = '';
                   9467:                                 }
                   9468:                             }
                   9469:                         }
                   9470:                     }
1.1368    raeburn  9471:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9472:                     if ($role eq 'st') {
                   9473:                         $refused = '';
1.1377    raeburn  9474:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9475:                         $refused = '';
                   9476:                     }
1.1017    raeburn  9477:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9478:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9479:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9480:                         my $wrongcc;
                   9481:                         if ($cnum =~ /^$match_community$/) {
                   9482:                             $wrongcc = 1 if ($role eq 'cc');
                   9483:                         } else {
                   9484:                             $wrongcc = 1 if ($role eq 'co');
                   9485:                         }
                   9486:                         unless ($wrongcc) {
                   9487:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9488:                             if ($crsenv{'internal.courseowner'} eq 
                   9489:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9490:                                 $refused = '';
                   9491:                             }
1.1017    raeburn  9492:                         }
                   9493:                     }
1.1183    raeburn  9494:                 } elsif ($context eq 'requestauthor') {
                   9495:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9496:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9497:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9498:                             $refused = '';
                   9499:                         } else {
                   9500:                             my %domdefaults = &get_domain_defaults($udom);
                   9501:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9502:                                 my $checkbystatus;
                   9503:                                 if ($env{'user.adv'}) { 
                   9504:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9505:                                     if ($disposition eq 'automatic') {
                   9506:                                         $refused = '';
                   9507:                                     } elsif ($disposition eq '') {
                   9508:                                         $checkbystatus = 1;
                   9509:                                     } 
                   9510:                                 } else {
                   9511:                                     $checkbystatus = 1;
                   9512:                                 }
                   9513:                                 if ($checkbystatus) {
                   9514:                                     if ($env{'environment.inststatus'}) {
                   9515:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9516:                                         foreach my $type (@inststatuses) {
                   9517:                                             if (($type ne '') &&
                   9518:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9519:                                                 $refused = '';
                   9520:                                             }
                   9521:                                         }
                   9522:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9523:                                         $refused = '';
                   9524:                                     }
                   9525:                                 }
                   9526:                             }
                   9527:                         }
                   9528:                     }
1.1017    raeburn  9529:                 }
                   9530:                 if ($refused) {
1.947     raeburn  9531:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9532:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9533: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9534:                     return 'refused';
                   9535:                 }
1.932     raeburn  9536:             }
1.1131    raeburn  9537:         } elsif ($role eq 'au') {
                   9538:             if ($url ne '/'.$udom.'/') {
                   9539:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9540:                          ' to assign author role for '.$uname.':'.$udom.
                   9541:                          ' in domain: '.$url.' refused (wrong domain).');
                   9542:                 return 'refused';
                   9543:             }
1.104     www      9544:         }
1.21      www      9545:         $mrole=$role;
                   9546:     }
1.620     albertel 9547:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9548:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9549:     if ($end) { $command.='_'.$end; }
1.21      www      9550:     if ($start) {
                   9551: 	if ($end) { 
1.81      www      9552:            $command.='_'.$start; 
1.21      www      9553:         } else {
1.81      www      9554:            $command.='_0_'.$start;
1.21      www      9555:         }
                   9556:     }
1.739     raeburn  9557:     my $origstart = $start;
                   9558:     my $origend = $end;
1.957     raeburn  9559:     my $delflag;
1.357     www      9560: # actually delete
                   9561:     if ($deleteflag) {
1.373     www      9562: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9563: # modify command to delete the role
1.620     albertel 9564:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9565:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9566: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9567: # set start and finish to negative values for userrolelog
                   9568:            $start=-1;
                   9569:            $end=-1;
1.957     raeburn  9570:            $delflag = 1;
1.357     www      9571:         }
                   9572:     }
                   9573: # send command
1.349     www      9574:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9575: # log new user role if status is ok
1.349     www      9576:     if ($answer eq 'ok') {
1.663     raeburn  9577: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9578:         if (($role eq 'cc') || ($role eq 'in') ||
                   9579:             ($role eq 'ep') || ($role eq 'ad') ||
                   9580:             ($role eq 'ta') || ($role eq 'st') ||
                   9581:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9582:             ($role eq 'co')) {
1.1200    raeburn  9583: # for course roles, perform group memberships changes triggered by role change.
                   9584:             unless ($role =~ /^gr/) {
                   9585:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9586:                                                  $origstart,$selfenroll,$context);
                   9587:             }
1.1184    raeburn  9588:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9589:                            $selfenroll,$context);
                   9590:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9591:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9592:                  ($role eq 'da')) {
1.1184    raeburn  9593:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9594:                            $context);
                   9595:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9596:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9597:                              $context); 
                   9598:         }
1.1053    raeburn  9599:         if ($role eq 'cc') {
                   9600:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9601:         }
1.349     www      9602:     }
                   9603:     return $answer;
1.169     harris41 9604: }
                   9605: 
1.1053    raeburn  9606: sub autoupdate_coowners {
                   9607:     my ($url,$end,$start,$uname,$udom) = @_;
                   9608:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9609:     if (($cdom ne '') && ($cnum ne '')) {
                   9610:         my $now = time;
                   9611:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9612:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9613:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9614:             my $instcode = $coursehash{'internal.coursecode'};
                   9615:             if ($instcode ne '') {
1.1056    raeburn  9616:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9617:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9618:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9619:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9620:                         if ($result eq 'valid') {
                   9621:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9622:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9623:                                     push(@newcoowners,$coowner);
                   9624:                                 }
                   9625:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9626:                                     push(@newcoowners,$uname.':'.$udom);
                   9627:                                 }
                   9628:                                 @newcoowners = sort(@newcoowners);
                   9629:                             } else {
                   9630:                                 push(@newcoowners,$uname.':'.$udom);
                   9631:                             }
                   9632:                         } else {
                   9633:                             if ($coursehash{'internal.co-owners'}) {
                   9634:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9635:                                     unless ($coowner eq $uname.':'.$udom) {
                   9636:                                         push(@newcoowners,$coowner);
                   9637:                                     }
                   9638:                                 }
                   9639:                                 unless (@newcoowners > 0) {
                   9640:                                     $delcoowners = 1;
                   9641:                                     $coowners = '';
                   9642:                                 }
                   9643:                             }
                   9644:                         }
                   9645:                         if (@newcoowners || $delcoowners) {
                   9646:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9647:                                             $delcoowners,@newcoowners);
                   9648:                         }
                   9649:                     }
                   9650:                 }
                   9651:             }
                   9652:         }
                   9653:     }
                   9654: }
                   9655: 
                   9656: sub store_coowners {
                   9657:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9658:     my $cid = $cdom.'_'.$cnum;
                   9659:     my ($coowners,$delresult,$putresult);
                   9660:     if (@newcoowners) {
                   9661:         $coowners = join(',',@newcoowners);
                   9662:         my %coownershash = (
                   9663:                             'internal.co-owners' => $coowners,
                   9664:                            );
                   9665:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9666:         if ($putresult eq 'ok') {
                   9667:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9668:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9669:             }
                   9670:         }
                   9671:     }
                   9672:     if ($delcoowners) {
                   9673:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9674:         if ($delresult eq 'ok') {
                   9675:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9676:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9677:             }
                   9678:         }
                   9679:     }
                   9680:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9681:         my %crsinfo =
                   9682:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9683:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9684:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9685:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9686:         }
                   9687:     }
                   9688: }
                   9689: 
1.169     harris41 9690: # -------------------------------------------------- Modify user authentication
1.197     www      9691: # Overrides without validation
                   9692: 
1.169     harris41 9693: sub modifyuserauth {
                   9694:     my ($udom,$uname,$umode,$upass)=@_;
                   9695:     my $uhome=&homeserver($uname,$udom);
1.197     www      9696:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9697:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9698:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9699:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9700:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9701: 		     &escape($upass),$uhome);
1.620     albertel 9702:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9703:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9704:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9705:     &log($udom,,$uname,$uhome,
1.620     albertel 9706:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9707:                                      $env{'user.name'}.', '.$umode.
1.197     www      9708:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9709:     unless ($reply eq 'ok') {
1.197     www      9710:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9711: 	return 'error: '.$reply;
                   9712:     }   
1.170     harris41 9713:     return 'ok';
1.80      www      9714: }
                   9715: 
1.81      www      9716: # --------------------------------------------------------------- Modify a user
1.80      www      9717: 
1.81      www      9718: sub modifyuser {
1.206     matthew  9719:     my ($udom,    $uname, $uid,
                   9720:         $umode,   $upass, $first,
                   9721:         $middle,  $last,  $gene,
1.1058    raeburn  9722:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9723:     $udom= &LONCAPA::clean_domain($udom);
                   9724:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9725:     my $showcandelete = 'none';
                   9726:     if (ref($candelete) eq 'ARRAY') {
                   9727:         if (@{$candelete} > 0) {
                   9728:             $showcandelete = join(', ',@{$candelete});
                   9729:         }
                   9730:     }
1.81      www      9731:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9732:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9733: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9734:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9735:                                      ' desiredhome not specified'). 
1.620     albertel 9736:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9737:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9738:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9739:     my $newuser;
                   9740:     if ($uhome eq 'no_host') {
                   9741:         $newuser = 1;
1.1368    raeburn  9742:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9743:                 ($umode eq 'lti')) {
                   9744:             return 'error: more information needed to create new user';
                   9745:         }
1.1075    raeburn  9746:     }
1.80      www      9747: # ----------------------------------------------------------------- Create User
1.406     albertel 9748:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9749: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9750:         my $unhome='';
1.844     albertel 9751:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9752:             $unhome = $desiredhome;
1.620     albertel 9753: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9754: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9755:         } else { # load balancing routine for determining $unhome
1.81      www      9756:             my $loadm=10000000;
1.841     albertel 9757: 	    my %servers = &get_servers($udom,'library');
                   9758: 	    foreach my $tryserver (keys(%servers)) {
                   9759: 		my $answer=reply('load',$tryserver);
                   9760: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9761: 		    $loadm=$answer;
                   9762: 		    $unhome=$tryserver;
                   9763: 		}
1.80      www      9764: 	    }
                   9765:         }
                   9766:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9767: 	    return 'error: unable to find a home server for '.$uname.
                   9768:                    ' in domain '.$udom;
1.80      www      9769:         }
                   9770:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9771:                          &escape($upass),$unhome);
                   9772: 	unless ($reply eq 'ok') {
                   9773:             return 'error: '.$reply;
                   9774:         }   
1.230     stredwic 9775:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9776:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9777: 	    return 'error: unable verify users home machine.';
1.80      www      9778:         }
1.209     matthew  9779:     }   # End of creation of new user
1.80      www      9780: # ---------------------------------------------------------------------- Add ID
                   9781:     if ($uid) {
                   9782:        $uid=~tr/A-Z/a-z/;
                   9783:        my %uidhash=&idrget($udom,$uname);
1.196     www      9784:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9785:          && (!$forceid)) {
1.80      www      9786: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9787: 	      return 'error: user id "'.$uid.'" does not match '.
                   9788:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9789:           }
                   9790:        } else {
1.1300    raeburn  9791: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9792:        }
                   9793:     }
                   9794: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9795:     my @tmp=&get('environment',
1.899     raeburn  9796: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9797:                     'permanentemail','inststatus'],
1.134     albertel 9798: 		   $udom,$uname);
1.1075    raeburn  9799:     my (%names,%oldnames);
1.313     matthew  9800:     if ($tmp[0] =~ m/^error:.*/) { 
                   9801:         %names=(); 
                   9802:     } else {
                   9803:         %names = @tmp;
1.1075    raeburn  9804:         %oldnames = %names;
1.313     matthew  9805:     }
1.388     www      9806: #
1.1058    raeburn  9807: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9808: # of users did not contain them), do not overwrite existing values
                   9809: # unless field is in $candelete array ref.  
                   9810: #
                   9811: 
                   9812:     my @fields = ('firstname','middlename','lastname','generation',
                   9813:                   'permanentemail','id');
                   9814:     my %newvalues;
                   9815:     if (ref($candelete) eq 'ARRAY') {
                   9816:         foreach my $field (@fields) {
                   9817:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9818:                 if ($field eq 'firstname') {
                   9819:                     $names{$field} = $first;
                   9820:                 } elsif ($field eq 'middlename') {
                   9821:                     $names{$field} = $middle;
                   9822:                 } elsif ($field eq 'lastname') {
                   9823:                     $names{$field} = $last;
                   9824:                 } elsif ($field eq 'generation') { 
                   9825:                     $names{$field} = $gene;
                   9826:                 } elsif ($field eq 'permanentemail') {
                   9827:                     $names{$field} = $email;
                   9828:                 } elsif ($field eq 'id') {
                   9829:                     $names{$field}  = $uid;
                   9830:                 }
                   9831:             }
                   9832:         }
                   9833:     }
1.388     www      9834:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9835:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9836:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9837:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9838:     if ($email) {
                   9839:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9840:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9841:     }
1.899     raeburn  9842:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9843:     if (defined($inststatus)) {
                   9844:         $names{'inststatus'} = '';
                   9845:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9846:         if (ref($usertypes) eq 'HASH') {
                   9847:             my @okstatuses; 
                   9848:             foreach my $item (split(/:/,$inststatus)) {
                   9849:                 if (defined($usertypes->{$item})) {
                   9850:                     push(@okstatuses,$item);  
                   9851:                 }
                   9852:             }
                   9853:             if (@okstatuses) {
                   9854:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9855:             }
                   9856:         }
                   9857:     }
1.1075    raeburn  9858:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9859:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9860:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9861:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9862:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9863:     } else {
                   9864:         $logmsg .= ' during self creation';
                   9865:     }
1.1075    raeburn  9866:     my $changed;
                   9867:     if ($newuser) {
                   9868:         $changed = 1;
                   9869:     } else {
                   9870:         foreach my $field (@fields) {
                   9871:             if ($names{$field} ne $oldnames{$field}) {
                   9872:                 $changed = 1;
                   9873:                 last;
                   9874:             }
                   9875:         }
                   9876:     }
                   9877:     unless ($changed) {
                   9878:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9879:         &logthis($logmsg);
                   9880:         return 'ok';
                   9881:     }
                   9882:     my $reply = &put('environment', \%names, $udom,$uname);
                   9883:     if ($reply ne 'ok') { 
                   9884:         return 'error: '.$reply;
                   9885:     }
1.1087    raeburn  9886:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9887:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9888:     }
1.1075    raeburn  9889:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9890:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9891:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9892:     &logthis($logmsg);
1.134     albertel 9893:     return 'ok';
1.80      www      9894: }
                   9895: 
1.81      www      9896: # -------------------------------------------------------------- Modify student
1.80      www      9897: 
1.81      www      9898: sub modifystudent {
                   9899:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9900:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9901:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9902:     if (!$cid) {
1.620     albertel 9903: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9904: 	    return 'not_in_class';
                   9905: 	}
1.80      www      9906:     }
                   9907: # --------------------------------------------------------------- Make the user
1.81      www      9908:     my $reply=&modifyuser
1.209     matthew  9909: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9910:          $desiredhome,$email,$inststatus);
1.80      www      9911:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9912:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9913:     # student's environment
1.297     matthew  9914:     $uid = undef if (!$forceid);
1.455     albertel 9915:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9916:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9917:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9918:     return $reply;
                   9919: }
                   9920: 
                   9921: sub modify_student_enrollment {
1.1216    raeburn  9922:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9923:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9924:     my ($cdom,$cnum,$chome);
                   9925:     if (!$cid) {
1.620     albertel 9926: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9927: 	    return 'not_in_class';
                   9928: 	}
1.620     albertel 9929: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9930: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9931:     } else {
                   9932: 	($cdom,$cnum)=split(/_/,$cid);
                   9933:     }
1.620     albertel 9934:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9935:     if (!$chome) {
1.457     raeburn  9936: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9937:     }
1.455     albertel 9938:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9939:     # Make sure the user exists
1.81      www      9940:     my $uhome=&homeserver($uname,$udom);
                   9941:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9942: 	return 'error: no such user';
                   9943:     }
1.297     matthew  9944:     # Get student data if we were not given enough information
                   9945:     if (!defined($first)  || $first  eq '' || 
                   9946:         !defined($last)   || $last   eq '' || 
                   9947:         !defined($uid)    || $uid    eq '' || 
                   9948:         !defined($middle) || $middle eq '' || 
                   9949:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9950:         # They did not supply us with enough data to enroll the student, so
                   9951:         # we need to pick up more information.
1.297     matthew  9952:         my %tmp = &get('environment',
1.294     matthew  9953:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9954:                        ,$udom,$uname);
                   9955: 
1.800     albertel 9956:         #foreach my $key (keys(%tmp)) {
                   9957:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9958:         #}
1.294     matthew  9959:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9960:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9961:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9962:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9963:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9964:     }
1.556     albertel 9965:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9966:     my $user = "$uname:$udom";
                   9967:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9968:     my $reply=cput('classlist',
1.1148    raeburn  9969: 		   {$user => 
1.1314    raeburn  9970: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9971: 		   $cdom,$cnum);
1.1148    raeburn  9972:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9973:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9974:     } else { 
1.81      www      9975: 	return 'error: '.$reply;
                   9976:     }
1.297     matthew  9977:     # Add student role to user
1.83      www      9978:     my $uurl='/'.$cid;
1.81      www      9979:     $uurl=~s/\_/\//g;
                   9980:     if ($usec) {
                   9981: 	$uurl.='/'.$usec;
                   9982:     }
1.1148    raeburn  9983:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9984:                              $selfenroll,$context);
                   9985:     if ($result ne 'ok') {
                   9986:         if ($old_entry{$user} ne '') {
                   9987:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9988:         } else {
                   9989:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9990:         }
                   9991:     }
                   9992:     return $result; 
1.21      www      9993: }
                   9994: 
1.556     albertel 9995: sub format_name {
                   9996:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9997:     my $name;
                   9998:     if ($first ne 'lastname') {
                   9999: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10000:     } else {
                   10001: 	if ($lastname=~/\S/) {
                   10002: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10003: 	    $name=~s/\s+,/,/;
                   10004: 	} else {
                   10005: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10006: 	}
                   10007:     }
                   10008:     $name=~s/^\s+//;
                   10009:     $name=~s/\s+$//;
                   10010:     $name=~s/\s+/ /g;
                   10011:     return $name;
                   10012: }
                   10013: 
1.84      www      10014: # ------------------------------------------------- Write to course preferences
                   10015: 
                   10016: sub writecoursepref {
                   10017:     my ($courseid,%prefs)=@_;
                   10018:     $courseid=~s/^\///;
                   10019:     $courseid=~s/\_/\//g;
                   10020:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10021:     my $chome=homeserver($cnum,$cdomain);
                   10022:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10023: 	return 'error: no such course';
                   10024:     }
                   10025:     my $cstring='';
1.800     albertel 10026:     foreach my $pref (keys(%prefs)) {
                   10027: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10028:     }
1.84      www      10029:     $cstring=~s/\&$//;
                   10030:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10031: }
                   10032: 
                   10033: # ---------------------------------------------------------- Make/modify course
                   10034: 
                   10035: sub createcourse {
1.741     raeburn  10036:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10037:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10038:     $url=&declutter($url);
                   10039:     my $cid='';
1.1028    raeburn  10040:     if ($context eq 'requestcourses') {
                   10041:         my $can_create = 0;
                   10042:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10043:         if ($udom eq $ownerdom) {
                   10044:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10045:                                   $context)) {
                   10046:                 $can_create = 1;
                   10047:             }
                   10048:         } else {
                   10049:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10050:                                            $category);
                   10051:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10052:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10053:                 if (@curr > 0) {
                   10054:                     my @options = qw(approval validate autolimit);
                   10055:                     my $optregex = join('|',@options);
                   10056:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10057:                         $can_create = 1;
                   10058:                     }
                   10059:                 }
                   10060:             }
                   10061:         }
                   10062:         if ($can_create) {
                   10063:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10064:                 unless (&allowed('ccc',$udom)) {
                   10065:                     return 'refused'; 
                   10066:                 }
1.1017    raeburn  10067:             }
                   10068:         } else {
                   10069:             return 'refused';
                   10070:         }
1.1028    raeburn  10071:     } elsif (!&allowed('ccc',$udom)) {
                   10072:         return 'refused';
1.84      www      10073:     }
1.1011    raeburn  10074: # --------------------------------------------------------------- Get Unique ID
                   10075:     my $uname;
                   10076:     if ($cnum =~ /^$match_courseid$/) {
                   10077:         my $chome=&homeserver($cnum,$udom,'true');
                   10078:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10079:             $uname = $cnum;
                   10080:         } else {
1.1038    raeburn  10081:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10082:         }
                   10083:     } else {
1.1038    raeburn  10084:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10085:     }
                   10086:     return $uname if ($uname =~ /^error/);
                   10087: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10088:     if (!defined($course_server)) {
                   10089:         if (defined(&domain($udom,'primary'))) {
                   10090:             $course_server = &domain($udom,'primary');
                   10091:         } else {
                   10092:             $course_server = $env{'user.home'}; 
                   10093:         }
                   10094:     }
                   10095:     my %host_servers =
                   10096:         &Apache::lonnet::get_servers($udom,'library');
                   10097:     unless ($host_servers{$course_server}) {
                   10098:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10099:     }
1.84      www      10100: # ------------------------------------------------------------- Make the course
                   10101:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10102:                       $course_server);
1.84      www      10103:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10104:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10105:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10106: 	return 'error: no such course';
                   10107:     }
1.271     www      10108: # ----------------------------------------------------------------- Course made
1.516     raeburn  10109: # log existence
1.1029    raeburn  10110:     my $now = time;
1.918     raeburn  10111:     my $newcourse = {
                   10112:                     $udom.'_'.$uname => {
1.921     raeburn  10113:                                      description => $description,
                   10114:                                      inst_code   => $inst_code,
                   10115:                                      owner       => $course_owner,
                   10116:                                      type        => $crstype,
1.1029    raeburn  10117:                                      creator     => $env{'user.name'}.':'.
                   10118:                                                     $env{'user.domain'},
                   10119:                                      created     => $now,
                   10120:                                      context     => $context,
1.918     raeburn  10121:                                                 },
                   10122:                     };
1.921     raeburn  10123:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10124: # set toplevel url
1.271     www      10125:     my $topurl=$url;
                   10126:     unless ($nonstandard) {
                   10127: # ------------------------------------------ For standard courses, make top url
                   10128:         my $mapurl=&clutter($url);
1.278     www      10129:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10130:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10131: <map>
                   10132: <resource id="1" type="start"></resource>
                   10133: <resource id="2" src="$mapurl"></resource>
                   10134: <resource id="3" type="finish"></resource>
                   10135: <link index="1" from="1" to="2"></link>
                   10136: <link index="2" from="2" to="3"></link>
                   10137: </map>
                   10138: ENDINITMAP
                   10139:         $topurl=&declutter(
1.638     albertel 10140:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10141:                           );
                   10142:     }
                   10143: # ----------------------------------------------------------- Write preferences
1.84      www      10144:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10145:                      ('description'              => $description,
                   10146:                       'url'                      => $topurl,
                   10147:                       'internal.creator'         => $env{'user.name'}.':'.
                   10148:                                                     $env{'user.domain'},
                   10149:                       'internal.created'         => $now,
                   10150:                       'internal.creationcontext' => $context)
                   10151:                     );
1.84      www      10152:     return '/'.$udom.'/'.$uname;
                   10153: }
                   10154: 
1.1011    raeburn  10155: # ------------------------------------------------------------------- Create ID
                   10156: sub generate_coursenum {
1.1038    raeburn  10157:     my ($udom,$crstype) = @_;
1.1011    raeburn  10158:     my $domdesc = &domain($udom);
                   10159:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10160:     my $first;
                   10161:     if ($crstype eq 'Community') {
                   10162:         $first = '0';
                   10163:     } else {
                   10164:         $first = int(1+rand(9)); 
                   10165:     } 
                   10166:     my $uname=$first.
1.1011    raeburn  10167:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10168:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10169:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10170: # ----------------------------------------------- Make sure that does not exist
                   10171:     my $uhome=&homeserver($uname,$udom,'true');
                   10172:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10173:         if ($crstype eq 'Community') {
                   10174:             $first = '0';
                   10175:         } else {
                   10176:             $first = int(1+rand(9));
                   10177:         }
                   10178:         $uname=$first.
1.1011    raeburn  10179:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10180:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10181:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10182:         $uhome=&homeserver($uname,$udom,'true');
                   10183:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10184:             return 'error: unable to generate unique course-ID';
                   10185:         }
                   10186:     }
                   10187:     return $uname;
                   10188: }
                   10189: 
1.813     albertel 10190: sub is_course {
1.1167    droeschl 10191:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10192:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10193: 
1.1381    raeburn  10194:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10195:     my $uhome=&homeserver($cnum,$cdom);
                   10196:     my $iscourse;
                   10197:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10198:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10199:     } else {
                   10200:         my $hashid = $cdom.':'.$cnum;
                   10201:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10202:         unless (defined($cached)) {
                   10203:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10204:                                         $cnum,undef,undef,'.');
                   10205:             $iscourse = 0;
                   10206:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10207:                 $iscourse = 1;
                   10208:             }
                   10209:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10210:         }
                   10211:     }
                   10212:     return unless ($iscourse);
1.1167    droeschl 10213:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10214: }
                   10215: 
1.1015    raeburn  10216: sub store_userdata {
                   10217:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10218:     my $result;
1.1016    raeburn  10219:     if ($datakey ne '') {
1.1013    raeburn  10220:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10221:             if ($udom eq '' || $uname eq '') {
                   10222:                 $udom = $env{'user.domain'};
                   10223:                 $uname = $env{'user.name'};
                   10224:             }
                   10225:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10226:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10227:                 $result = 'error: no_host';
                   10228:             } else {
                   10229:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10230:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10231: 
                   10232:                 my $namevalue='';
                   10233:                 foreach my $key (keys(%{$storehash})) {
                   10234:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10235:                 }
                   10236:                 $namevalue=~s/\&$//;
1.1224    raeburn  10237:                 unless ($namespace eq 'courserequests') {
                   10238:                     $datakey = &escape($datakey);
                   10239:                 }
1.1105    raeburn  10240:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10241:                                   $namevalue,$uhome);
1.1013    raeburn  10242:             }
                   10243:         } else {
                   10244:             $result = 'error: data to store was not a hash reference'; 
                   10245:         }
                   10246:     } else {
                   10247:         $result= 'error: invalid requestkey'; 
                   10248:     }
                   10249:     return $result;
                   10250: }
                   10251: 
1.21      www      10252: # ---------------------------------------------------------- Assign Custom Role
                   10253: 
                   10254: sub assigncustomrole {
1.957     raeburn  10255:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10256:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10257:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10258: }
                   10259: 
                   10260: # ----------------------------------------------------------------- Revoke Role
                   10261: 
                   10262: sub revokerole {
1.957     raeburn  10263:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10264:     my $now=time;
1.965     raeburn  10265:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10266: }
                   10267: 
                   10268: # ---------------------------------------------------------- Revoke Custom Role
                   10269: 
                   10270: sub revokecustomrole {
1.957     raeburn  10271:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10272:     my $now=time;
1.357     www      10273:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10274:            $deleteflag,$selfenroll,$context);
1.17      www      10275: }
                   10276: 
1.533     banghart 10277: # ------------------------------------------------------------ Disk usage
1.535     albertel 10278: sub diskusage {
1.955     raeburn  10279:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10280:     $directorypath =~ s/\/$//;
                   10281:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10282:                        .&escape($getpropath).':'.&escape($uname).':'
                   10283:                        .&escape($udom),homeserver($uname,$udom));
                   10284:     if ($listing eq 'unknown_cmd') {
                   10285:         if ($getpropath) {
                   10286:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10287:         }
                   10288:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10289:     }
1.514     albertel 10290:     return $listing;
1.512     banghart 10291: }
                   10292: 
1.566     banghart 10293: sub is_locked {
1.1096    raeburn  10294:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10295:     my @check;
                   10296:     my $is_locked;
1.1093    raeburn  10297:     push (@check,$file_name);
1.613     albertel 10298:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10299: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10300:     my ($tmp)=keys(%locked);
                   10301:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10302:     
1.566     banghart 10303:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10304:         $is_locked = 'false';
                   10305:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10306:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10307:                $is_locked = 'true';
1.1096    raeburn  10308:                if (ref($which) eq 'ARRAY') {
                   10309:                    push(@{$which},$entry);
                   10310:                } else {
                   10311:                    last;
                   10312:                }
1.745     raeburn  10313:            }
                   10314:        }
1.566     banghart 10315:     } else {
                   10316:         $is_locked = 'false';
                   10317:     }
1.1093    raeburn  10318:     return $is_locked;
1.566     banghart 10319: }
                   10320: 
1.759     albertel 10321: sub declutter_portfile {
                   10322:     my ($file) = @_;
1.833     albertel 10323:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10324:     return $file;
                   10325: }
                   10326: 
1.559     banghart 10327: # ------------------------------------------------------------- Mark as Read Only
                   10328: 
                   10329: sub mark_as_readonly {
                   10330:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10331:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10332:     my ($tmp)=keys(%current_permissions);
                   10333:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10334:     foreach my $file (@{$files}) {
1.759     albertel 10335: 	$file = &declutter_portfile($file);
1.561     banghart 10336:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10337:     }
1.613     albertel 10338:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10339:     return;
                   10340: }
                   10341: 
1.572     banghart 10342: # ------------------------------------------------------------Save Selected Files
                   10343: 
                   10344: sub save_selected_files {
                   10345:     my ($user, $path, @files) = @_;
                   10346:     my $filename = $user."savedfiles";
1.573     banghart 10347:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10348:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10349:     foreach my $file (@files) {
1.620     albertel 10350:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10351:     }
                   10352:     foreach my $file (@other_files) {
1.574     banghart 10353:         print (OUT $file."\n");
1.572     banghart 10354:     }
1.574     banghart 10355:     close (OUT);
1.572     banghart 10356:     return 'ok';
                   10357: }
                   10358: 
1.574     banghart 10359: sub clear_selected_files {
                   10360:     my ($user) = @_;
                   10361:     my $filename = $user."savedfiles";
1.1359    raeburn  10362:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10363:     print (OUT undef);
                   10364:     close (OUT);
                   10365:     return ("ok");    
                   10366: }
                   10367: 
1.572     banghart 10368: sub files_in_path {
                   10369:     my ($user, $path) = @_;
                   10370:     my $filename = $user."savedfiles";
                   10371:     my %return_files;
1.1359    raeburn  10372:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10373:     while (my $line_in = <IN>) {
1.574     banghart 10374:         chomp ($line_in);
                   10375:         my @paths_and_file = split (m!/!, $line_in);
                   10376:         my $file_part = pop (@paths_and_file);
                   10377:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10378:         $path_part.='/';
                   10379:         my $path_and_file = $path_part.$file_part;
                   10380:         if ($path_part eq $path) {
                   10381:             $return_files{$file_part}= 'selected';
                   10382:         }
                   10383:     }
1.574     banghart 10384:     close (IN);
                   10385:     return (\%return_files);
1.572     banghart 10386: }
                   10387: 
                   10388: # called in portfolio select mode, to show files selected NOT in current directory
                   10389: sub files_not_in_path {
                   10390:     my ($user, $path) = @_;
                   10391:     my $filename = $user."savedfiles";
                   10392:     my @return_files;
                   10393:     my $path_part;
1.1359    raeburn  10394:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10395:     while (my $line = <IN>) {
1.572     banghart 10396:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10397:         my @paths_and_file = split(m|/|, $line);
                   10398:         my $file_part = pop(@paths_and_file);
                   10399:         chomp($file_part);
                   10400:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10401:         $path_part .= '/';
                   10402:         my $path_and_file = $path_part.$file_part;
                   10403:         if ($path_part ne $path) {
1.800     albertel 10404:             push(@return_files, ($path_and_file));
1.572     banghart 10405:         }
                   10406:     }
1.800     albertel 10407:     close(OUT);
1.574     banghart 10408:     return (@return_files);
1.572     banghart 10409: }
                   10410: 
1.1273    raeburn  10411: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10412:  
                   10413: sub portfiles_versioning {
                   10414:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10415:     my $portfolio_root = '/userfiles/portfolio';
                   10416:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10417:     foreach my $file (@{$portfiles}) {
                   10418:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10419:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10420:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10421:         my $getpropath = 1;
                   10422:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10423:                                              $stu_name,$getpropath);
                   10424:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10425:         my $new_answer = 
                   10426:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10427:         if ($new_answer ne 'problem getting file') {
                   10428:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10429:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10430:                               [$symb,$env{'request.course.id'},'graded']);
                   10431:         }
                   10432:     }
                   10433: }
                   10434: 
                   10435: sub get_next_version {
                   10436:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10437:     my $version;
                   10438:     if (ref($dir_list) eq 'ARRAY') {
                   10439:         foreach my $row (@{$dir_list}) {
                   10440:             my ($file) = split(/\&/,$row,2);
                   10441:             my ($file_name,$file_version,$file_ext) =
                   10442:                 &file_name_version_ext($file);
                   10443:             if (($file_name eq $answer_name) &&
                   10444:                 ($file_ext eq $answer_ext)) {
                   10445:                      # gets here if filename and extension match,
                   10446:                      # regardless of version
                   10447:                 if ($file_version ne '') {
                   10448:                     # a versioned file is found  so save it for later
                   10449:                     if ($file_version > $version) {
                   10450:                         $version = $file_version;
                   10451:                     }
                   10452:                 }
                   10453:             }
                   10454:         }
                   10455:     }
                   10456:     $version ++;
                   10457:     return($version);
                   10458: }
                   10459: 
                   10460: sub version_selected_portfile {
                   10461:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10462:     my ($answer_name,$answer_ver,$answer_ext) =
                   10463:         &file_name_version_ext($file_name);
                   10464:     my $new_answer;
                   10465:     $env{'form.copy'} =
                   10466:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10467:     if($env{'form.copy'} eq '-1') {
                   10468:         $new_answer = 'problem getting file';
                   10469:     } else {
                   10470:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10471:         my $copy_result = 
                   10472:             &finishuserfileupload($stu_name,$domain,'copy',
                   10473:                                   '/portfolio'.$directory.$new_answer);
                   10474:     }
                   10475:     undef($env{'form.copy'});
                   10476:     return ($new_answer);
                   10477: }
                   10478: 
                   10479: sub file_name_version_ext {
                   10480:     my ($file)=@_;
                   10481:     my @file_parts = split(/\./, $file);
                   10482:     my ($name,$version,$ext);
                   10483:     if (@file_parts > 1) {
                   10484:         $ext=pop(@file_parts);
                   10485:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10486:             $version=pop(@file_parts);
                   10487:         }
                   10488:         $name=join('.',@file_parts);
                   10489:     } else {
                   10490:         $name=join('.',@file_parts);
                   10491:     }
                   10492:     return($name,$version,$ext);
                   10493: }
                   10494: 
1.745     raeburn  10495: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10496: 
1.745     raeburn  10497: sub get_portfile_permissions {
                   10498:     my ($domain,$user) = @_;
1.613     albertel 10499:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10500:     my ($tmp)=keys(%current_permissions);
                   10501:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10502:     return \%current_permissions;
                   10503: }
                   10504: 
                   10505: #---------------------------------------------Get portfolio file access controls
                   10506: 
1.749     raeburn  10507: sub get_access_controls {
1.745     raeburn  10508:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10509:     my %access;
                   10510:     my $real_file = $file;
                   10511:     $file =~ s/\.meta$//;
1.745     raeburn  10512:     if (defined($file)) {
1.749     raeburn  10513:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10514:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10515:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10516:             }
                   10517:         }
1.745     raeburn  10518:     } else {
1.749     raeburn  10519:         foreach my $key (keys(%{$current_permissions})) {
                   10520:             if ($key =~ /\0accesscontrol$/) {
                   10521:                 if (defined($group)) {
                   10522:                     if ($key !~ m-^\Q$group\E/-) {
                   10523:                         next;
                   10524:                     }
                   10525:                 }
                   10526:                 my ($fullpath) = split(/\0/,$key);
                   10527:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10528:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10529:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10530:                     }
                   10531:                 }
                   10532:             }
                   10533:         }
                   10534:     }
                   10535:     return %access;
                   10536: }
                   10537: 
                   10538: sub modify_access_controls {
                   10539:     my ($file_name,$changes,$domain,$user)=@_;
                   10540:     my ($outcome,$deloutcome);
                   10541:     my %store_permissions;
                   10542:     my %new_values;
                   10543:     my %new_control;
                   10544:     my %translation;
                   10545:     my @deletions = ();
                   10546:     my $now = time;
                   10547:     if (exists($$changes{'activate'})) {
                   10548:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10549:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10550:             my $numnew = scalar(@newitems);
                   10551:             for (my $i=0; $i<$numnew; $i++) {
                   10552:                 my $newkey = $newitems[$i];
                   10553:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10554:                 if ($newkey =~ /^\d+:/) { 
                   10555:                     $newkey =~ s/^(\d+)/$newid/;
                   10556:                     $translation{$1} = $newid;
                   10557:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10558:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10559:                     $translation{$1} = $newid;
                   10560:                 }
1.749     raeburn  10561:                 $new_values{$file_name."\0".$newkey} = 
                   10562:                                           $$changes{'activate'}{$newitems[$i]};
                   10563:                 $new_control{$newkey} = $now;
                   10564:             }
                   10565:         }
                   10566:     }
                   10567:     my %todelete;
                   10568:     my %changed_items;
                   10569:     foreach my $action ('delete','update') {
                   10570:         if (exists($$changes{$action})) {
                   10571:             if (ref($$changes{$action}) eq 'HASH') {
                   10572:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10573:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10574:                     if ($action eq 'delete') { 
                   10575:                         $todelete{$itemnum} = 1;
                   10576:                     } else {
                   10577:                         $changed_items{$itemnum} = $key;
                   10578:                     }
                   10579:                 }
1.745     raeburn  10580:             }
                   10581:         }
1.749     raeburn  10582:     }
                   10583:     # get lock on access controls for file.
                   10584:     my $lockhash = {
                   10585:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10586:                                                        ':'.$env{'user.domain'},
                   10587:                    }; 
                   10588:     my $tries = 0;
                   10589:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10590:    
1.1288    damieng  10591:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10592:         $tries ++;
1.1289    damieng  10593:         sleep(0.1);
1.749     raeburn  10594:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10595:     }
                   10596:     if ($gotlock eq 'ok') {
                   10597:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10598:         my ($tmp)=keys(%curr_permissions);
                   10599:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10600:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10601:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10602:             if (ref($curr_controls) eq 'HASH') {
                   10603:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10604:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10605:                     if (defined($todelete{$itemnum})) {
                   10606:                         push(@deletions,$file_name."\0".$control_item);
                   10607:                     } else {
                   10608:                         if (defined($changed_items{$itemnum})) {
                   10609:                             $new_control{$changed_items{$itemnum}} = $now;
                   10610:                             push(@deletions,$file_name."\0".$control_item);
                   10611:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10612:                         } else {
                   10613:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10614:                         }
                   10615:                     }
1.745     raeburn  10616:                 }
                   10617:             }
                   10618:         }
1.970     raeburn  10619:         my ($group);
                   10620:         if (&is_course($domain,$user)) {
                   10621:             ($group,my $file) = split(/\//,$file_name,2);
                   10622:         }
1.749     raeburn  10623:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10624:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10625:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10626:         #  remove lock
                   10627:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10628:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10629:         my $sqlresult =
1.970     raeburn  10630:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10631:                                     $group);
1.749     raeburn  10632:     } else {
                   10633:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10634:     }
1.749     raeburn  10635:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10636: }
                   10637: 
1.827     raeburn  10638: sub make_public_indefinitely {
1.1271    raeburn  10639:     my (@requrl) = @_;
                   10640:     return &automated_portfile_access('public',\@requrl);
                   10641: }
                   10642: 
                   10643: sub automated_portfile_access {
                   10644:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10645:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10646:         return 'invalid';
                   10647:     }
1.1271    raeburn  10648:     my %urls;
                   10649:     if (ref($addsref) eq 'ARRAY') {
                   10650:         foreach my $requrl (@{$addsref}) {
                   10651:             if (&is_portfolio_url($requrl)) {
                   10652:                 unless (exists($urls{$requrl})) {
                   10653:                     $urls{$requrl} = 'add';
                   10654:                 }
                   10655:             }
                   10656:         }
                   10657:     }
                   10658:     if (ref($delsref) eq 'ARRAY') {
                   10659:         foreach my $requrl (@{$delsref}) { 
                   10660:             if (&is_portfolio_url($requrl)) {
                   10661:                 unless (exists($urls{$requrl})) {
                   10662:                     $urls{$requrl} = 'delete'; 
                   10663:                 }
                   10664:             }
                   10665:         }
                   10666:     }
                   10667:     unless (keys(%urls)) {
                   10668:         return 'invalid';
                   10669:     }
                   10670:     my $ip;
                   10671:     if ($accesstype eq 'ip') {
                   10672:         if (ref($info) eq 'HASH') {
                   10673:             if ($info->{'ip'} ne '') {
                   10674:                 $ip = $info->{'ip'};
                   10675:             }
                   10676:         }
                   10677:         if ($ip eq '') {
                   10678:             return 'invalid';
                   10679:         }
                   10680:     }
                   10681:     my $errors;
1.827     raeburn  10682:     my $now = time;
1.1271    raeburn  10683:     my %current_perms;
                   10684:     foreach my $requrl (sort(keys(%urls))) {
                   10685:         my $action;
                   10686:         if ($urls{$requrl} eq 'add') {
                   10687:             $action = 'activate';
                   10688:         } else {
                   10689:             $action = 'none';
                   10690:         }
                   10691:         my $aclnum = 0;
1.827     raeburn  10692:         my (undef,$udom,$unum,$file_name,$group) =
                   10693:             &parse_portfolio_url($requrl);
1.1271    raeburn  10694:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10695:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10696:         }
                   10697:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10698:                                                    $group,$file_name);
                   10699:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10700:             my ($num,$scope,$end,$start) = 
                   10701:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10702:             if ($scope eq $accesstype) {
                   10703:                 if (($start <= $now) && ($end == 0)) {
                   10704:                     if ($accesstype eq 'ip') {
                   10705:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10706:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10707:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10708:                                     if ($urls{$requrl} eq 'add') {
                   10709:                                         $action = 'none';
                   10710:                                         last;
                   10711:                                     } else {
                   10712:                                         $action = 'delete';
                   10713:                                         $aclnum = $num;
                   10714:                                         last;
                   10715:                                     }
                   10716:                                 }
                   10717:                             }
                   10718:                         }
                   10719:                     } elsif ($accesstype eq 'public') {
                   10720:                         if ($urls{$requrl} eq 'add') {
                   10721:                             $action = 'none';
                   10722:                             last;
                   10723:                         } else {
                   10724:                             $action = 'delete';
                   10725:                             $aclnum = $num;
                   10726:                             last;
                   10727:                         }
                   10728:                     }
                   10729:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10730:                     $action = 'update';
                   10731:                     $aclnum = $num;
1.1271    raeburn  10732:                     last;
1.827     raeburn  10733:                 }
                   10734:             }
                   10735:         }
                   10736:         if ($action eq 'none') {
1.1271    raeburn  10737:             next;
1.827     raeburn  10738:         } else {
                   10739:             my %changes;
                   10740:             my $newend = 0;
                   10741:             my $newstart = $now;
1.1271    raeburn  10742:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10743:             $changes{$action}{$newkey} = {
1.1271    raeburn  10744:                 type => $accesstype,
1.827     raeburn  10745:                 time => {
                   10746:                     start => $newstart,
                   10747:                     end   => $newend,
                   10748:                 },
                   10749:             };
1.1271    raeburn  10750:             if ($accesstype eq 'ip') {
                   10751:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10752:             }
1.827     raeburn  10753:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10754:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10755:             unless ($outcome eq 'ok') {
                   10756:                 $errors .= $outcome.' ';
                   10757:             }
1.827     raeburn  10758:         }
1.1271    raeburn  10759:     }
                   10760:     if ($errors) {
                   10761:         $errors =~ s/\s$//;
                   10762:         return $errors;
1.827     raeburn  10763:     } else {
1.1271    raeburn  10764:         return 'ok';
1.827     raeburn  10765:     }
                   10766: }
                   10767: 
1.745     raeburn  10768: #------------------------------------------------------Get Marked as Read Only
                   10769: 
                   10770: sub get_marked_as_readonly {
                   10771:     my ($domain,$user,$what,$group) = @_;
                   10772:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10773:     my @readonly_files;
1.629     banghart 10774:     my $cmp1=$what;
                   10775:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10776:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10777:         if (defined($group)) {
                   10778:             if ($file_name !~ m-^\Q$group\E/-) {
                   10779:                 next;
                   10780:             }
                   10781:         }
1.561     banghart 10782:         if (ref($value) eq "ARRAY"){
                   10783:             foreach my $stored_what (@{$value}) {
1.629     banghart 10784:                 my $cmp2=$stored_what;
1.759     albertel 10785:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10786:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10787:                 }
1.629     banghart 10788:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10789:                     push(@readonly_files, $file_name);
1.745     raeburn  10790:                     last;
1.563     banghart 10791:                 } elsif (!defined($what)) {
                   10792:                     push(@readonly_files, $file_name);
1.745     raeburn  10793:                     last;
1.561     banghart 10794:                 }
                   10795:             }
1.745     raeburn  10796:         }
1.561     banghart 10797:     }
                   10798:     return @readonly_files;
                   10799: }
1.577     banghart 10800: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10801: 
1.577     banghart 10802: sub get_marked_as_readonly_hash {
1.745     raeburn  10803:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10804:     my %readonly_files;
1.745     raeburn  10805:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10806:         if (defined($group)) {
                   10807:             if ($file_name !~ m-^\Q$group\E/-) {
                   10808:                 next;
                   10809:             }
                   10810:         }
1.577     banghart 10811:         if (ref($value) eq "ARRAY"){
                   10812:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10813:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10814:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10815:                         if ($lock_descriptor eq 'graded') {
                   10816:                             $readonly_files{$file_name} = 'graded';
                   10817:                         } elsif ($lock_descriptor eq 'handback') {
                   10818:                             $readonly_files{$file_name} = 'handback';
                   10819:                         } else {
                   10820:                             if (!exists($readonly_files{$file_name})) {
                   10821:                                 $readonly_files{$file_name} = 'locked';
                   10822:                             }
                   10823:                         }
1.745     raeburn  10824:                     }
1.750     banghart 10825:                 } 
1.577     banghart 10826:             }
                   10827:         } 
                   10828:     }
                   10829:     return %readonly_files;
                   10830: }
1.559     banghart 10831: # ------------------------------------------------------------ Unmark as Read Only
                   10832: 
                   10833: sub unmark_as_readonly {
1.629     banghart 10834:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10835:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10836:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10837:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10838:     my $symb_crs = $what;
                   10839:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10840:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10841:     my ($tmp)=keys(%current_permissions);
                   10842:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10843:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10844:     foreach my $file (@readonly_files) {
1.759     albertel 10845: 	my $clean_file = &declutter_portfile($file);
                   10846: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10847: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10848:         my @new_locks;
                   10849:         my @del_keys;
                   10850:         if (ref($current_locks) eq "ARRAY"){
                   10851:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10852:                 my $compare=$locker;
1.749     raeburn  10853:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10854:                     $compare=join('',@{$locker});
1.746     raeburn  10855:                     if ($compare ne $symb_crs) {
                   10856:                         push(@new_locks, $locker);
                   10857:                     }
1.563     banghart 10858:                 }
                   10859:             }
1.650     albertel 10860:             if (scalar(@new_locks) > 0) {
1.563     banghart 10861:                 $current_permissions{$file} = \@new_locks;
                   10862:             } else {
                   10863:                 push(@del_keys, $file);
1.613     albertel 10864:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10865:                 delete($current_permissions{$file});
1.563     banghart 10866:             }
                   10867:         }
1.561     banghart 10868:     }
1.613     albertel 10869:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10870:     return;
                   10871: }
1.512     banghart 10872: 
1.17      www      10873: # ------------------------------------------------------------ Directory lister
                   10874: 
                   10875: sub dirlist {
1.955     raeburn  10876:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10877:     $uri=~s/^\///;
                   10878:     $uri=~s/\/$//;
1.253     stredwic 10879:     my ($udom, $uname);
1.955     raeburn  10880:     if ($getuserdir) {
1.253     stredwic 10881:         $udom = $userdomain;
                   10882:         $uname = $username;
1.955     raeburn  10883:     } else {
                   10884:         (undef,$udom,$uname)=split(/\//,$uri);
                   10885:         if(defined($userdomain)) {
                   10886:             $udom = $userdomain;
                   10887:         }
                   10888:         if(defined($username)) {
                   10889:             $uname = $username;
                   10890:         }
1.253     stredwic 10891:     }
1.955     raeburn  10892:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10893: 
1.955     raeburn  10894:     $dirRoot = $perlvar{'lonDocRoot'};
                   10895:     if (defined($getpropath)) {
                   10896:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10897:         $dirRoot =~ s/\/$//;
1.955     raeburn  10898:     } elsif (defined($getuserdir)) {
                   10899:         my $subdir=$uname.'__';
                   10900:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10901:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10902:                    ."/$udom/$subdir/$uname";
                   10903:     } elsif (defined($alternateRoot)) {
                   10904:         $dirRoot = $alternateRoot;
1.751     banghart 10905:     }
1.253     stredwic 10906: 
                   10907:     if($udom) {
                   10908:         if($uname) {
1.1135    raeburn  10909:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10910:             if ($uhome eq 'no_host') {
                   10911:                 return ([],'no_host');
                   10912:             }
1.955     raeburn  10913:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10914:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10915:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10916:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10917:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10918:             } else {
                   10919:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10920:             }
1.605     matthew  10921:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10922:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10923:                 @listing_results = split(/:/,$listing);
                   10924:             } else {
                   10925:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10926:             }
1.1135    raeburn  10927:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10928:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10929:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10930:                 return ([],$listing);
                   10931:             } else {
                   10932:                 return (\@listing_results);
1.1135    raeburn  10933:             }
1.955     raeburn  10934:         } elsif(!$alternateRoot) {
1.1136    raeburn  10935:             my (%allusers,%listerror);
1.841     albertel 10936: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10937:  	    foreach my $tryserver (keys(%servers)) {
                   10938:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10939:                                   &escape($udom),$tryserver);
                   10940:                 if ($listing eq 'unknown_cmd') {
                   10941: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10942: 				      $udom, $tryserver);
                   10943:                 } else {
                   10944:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10945:                 }
1.841     albertel 10946: 		if ($listing eq 'unknown_cmd') {
                   10947: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10948: 				      $udom, $tryserver);
                   10949: 		    @listing_results = split(/:/,$listing);
                   10950: 		} else {
                   10951: 		    @listing_results =
                   10952: 			map { &unescape($_); } split(/:/,$listing);
                   10953: 		}
1.1136    raeburn  10954:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10955:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10956:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10957:                     $listerror{$tryserver} = $listing;
                   10958:                 } else {
1.841     albertel 10959: 		    foreach my $line (@listing_results) {
                   10960: 			my ($entry) = split(/&/,$line,2);
                   10961: 			$allusers{$entry} = 1;
                   10962: 		    }
                   10963: 		}
1.253     stredwic 10964:             }
1.1136    raeburn  10965:             my @alluserslist=();
1.800     albertel 10966:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10967:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10968:             }
1.1318    droeschl 10969: 
                   10970:             if (!%listerror) {
                   10971:                 # no errors
                   10972:                 return (\@alluserslist);
                   10973:             } elsif (scalar(keys(%servers)) == 1) {
                   10974:                 # one library server, one error 
                   10975:                 my ($key) = keys(%listerror);
                   10976:                 return (\@alluserslist, $listerror{$key});
                   10977:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10978:                 # con_lost indicates that we might miss data from at least one
                   10979:                 # library server
                   10980:                 return (\@alluserslist, 'con_lost');
                   10981:             } else {
                   10982:                 # multiple library servers and no con_lost -> data should be
                   10983:                 # complete. 
                   10984:                 return (\@alluserslist);
                   10985:             }
                   10986: 
1.253     stredwic 10987:         } else {
1.1136    raeburn  10988:             return ([],'missing username');
1.253     stredwic 10989:         }
1.955     raeburn  10990:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10991:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10992:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10993:         return (\@all_domains);
1.955     raeburn  10994:     } else {
1.1136    raeburn  10995:         return ([],'missing domain');
1.275     stredwic 10996:     }
                   10997: }
                   10998: 
                   10999: # --------------------------------------------- GetFileTimestamp
                   11000: # This function utilizes dirlist and returns the date stamp for
                   11001: # when it was last modified.  It will also return an error of -1
                   11002: # if an error occurs
                   11003: 
                   11004: sub GetFileTimestamp {
1.955     raeburn  11005:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11006:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11007:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11008:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11009:                                     undef,$getuserdir);
                   11010:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11011:         return -1;
                   11012:     }
                   11013:     if (ref($fileref) eq 'ARRAY') {
                   11014:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11015:         # @stats contains first the filename, then the stat output
                   11016:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11017:     } else {
                   11018:         return -1;
1.253     stredwic 11019:     }
1.26      www      11020: }
                   11021: 
1.712     albertel 11022: sub stat_file {
                   11023:     my ($uri) = @_;
1.787     albertel 11024:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11025: 
1.955     raeburn  11026:     my ($udom,$uname,$file);
1.712     albertel 11027:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11028: 	($udom,$uname,$file) =
1.811     albertel 11029: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11030: 	$file = 'userfiles/'.$file;
                   11031:     }
                   11032:     if ($uri =~ m-^/res/-) {
                   11033: 	($udom,$uname) = 
1.807     albertel 11034: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11035: 	$file = $uri;
                   11036:     }
                   11037: 
                   11038:     if (!$udom || !$uname || !$file) {
                   11039: 	# unable to handle the uri
                   11040: 	return ();
                   11041:     }
1.956     raeburn  11042:     my $getpropath;
                   11043:     if ($file =~ /^userfiles\//) {
                   11044:         $getpropath = 1;
                   11045:     }
1.1136    raeburn  11046:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11047:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11048:         return ();
                   11049:     } else {
                   11050:         if (ref($listref) eq 'ARRAY') {
                   11051:             my @stats = split('&',$listref->[0]);
                   11052: 	    shift(@stats); #filename is first
                   11053: 	    return @stats;
                   11054:         }
1.712     albertel 11055:     }
                   11056:     return ();
                   11057: }
                   11058: 
1.1313    raeburn  11059: # --------------------------------------------------------- recursedirs
                   11060: # Recursive function to traverse either a specific user's Authoring Space
                   11061: # or corresponding Published Resource Space, and populate the hash ref:
                   11062: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11063: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11064: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11065: # files in Authoring Space.
                   11066: #
                   11067: # Inputs:
                   11068: #
                   11069: # $is_home - true if current server is home server for user's space
                   11070: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11071: # $docroot - Document root (i.e., /home/httpd/html
                   11072: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11073: # $relpath - Current path (relative to top level).
                   11074: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11075: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11076: #
                   11077: # Returns: nothing
                   11078: #
                   11079: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11080: #
                   11081: # Currently used by interface/londocs.pm to create linked select boxes for
                   11082: # directory and filename to import a Course "Author" resource into a course, and
                   11083: # also to create linked select boxes for Authoring Space and Directory to choose
                   11084: # save location for creation of a new "standard" problem from the Course Editor.
                   11085: #
                   11086: 
                   11087: sub recursedirs {
                   11088:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11089:     return unless (ref($dirhashref) eq 'HASH');
                   11090:     my $currpath = $docroot.$toppath;
                   11091:     if ($relpath) {
                   11092:         $currpath .= "/$relpath";
                   11093:     }
                   11094:     my $savefile;
                   11095:     if (ref($filehashref)) {
                   11096:         $savefile = 1;
                   11097:     }
                   11098:     if ($is_home) {
                   11099:         if (opendir(my $dirh,$currpath)) {
                   11100:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11101:                 next if ($item eq '');
                   11102:                 if (-d "$currpath/$item") {
                   11103:                     my $newpath;
                   11104:                     if ($relpath) {
                   11105:                         $newpath = "$relpath/$item";
                   11106:                     } else {
                   11107:                         $newpath = $item;
                   11108:                     }
                   11109:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11110:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11111:                 } elsif ($savefile) {
                   11112:                     if ($context eq 'priv') {
                   11113:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11114:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11115:                         }
                   11116:                     } else {
                   11117:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11118:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11119:                         }
                   11120:                     }
                   11121:                 }
                   11122:             }
                   11123:             closedir($dirh);
                   11124:         }
                   11125:     } else {
                   11126:         my ($dirlistref,$listerror) =
                   11127:             &dirlist($toppath.$relpath);
                   11128:         my @dir_lines;
                   11129:         my $dirptr=16384;
                   11130:         if (ref($dirlistref) eq 'ARRAY') {
                   11131:             foreach my $dir_line (sort
                   11132:                               {
                   11133:                                   my ($afile)=split('&',$a,2);
                   11134:                                   my ($bfile)=split('&',$b,2);
                   11135:                                   return (lc($afile) cmp lc($bfile));
                   11136:                               } (@{$dirlistref})) {
                   11137:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11138:                     split(/\&/,$dir_line,16);
                   11139:                 $item =~ s/\s+$//;
                   11140:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11141:                 if ($dirptr&$testdir) {
                   11142:                     my $newpath;
                   11143:                     if ($relpath) {
                   11144:                         $newpath = "$relpath/$item";
                   11145:                     } else {
                   11146:                         $relpath = '/';
                   11147:                         $newpath = $item;
                   11148:                     }
                   11149:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11150:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11151:                 } elsif ($savefile) {
                   11152:                     if ($context eq 'priv') {
                   11153:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11154:                             $filehashref->{$relpath}{$item} = 1;
                   11155:                         }
                   11156:                     } else {
                   11157:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11158:                             $filehashref->{$relpath}{$item} = 1;
                   11159:                         }
                   11160:                     }
                   11161:                 }
                   11162:             }
                   11163:         }
                   11164:     }
                   11165:     return;
                   11166: }
                   11167: 
1.26      www      11168: # -------------------------------------------------------- Value of a Condition
                   11169: 
1.713     albertel 11170: # gets the value of a specific preevaluated condition
                   11171: #    stored in the string  $env{user.state.<cid>}
                   11172: # or looks up a condition reference in the bighash and if if hasn't
                   11173: # already been evaluated recurses into docondval to get the value of
                   11174: # the condition, then memoizing it to 
                   11175: #   $env{user.state.<cid>.<condition>}
1.40      www      11176: sub directcondval {
                   11177:     my $number=shift;
1.620     albertel 11178:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11179: 	&Apache::lonuserstate::evalstate();
                   11180:     }
1.713     albertel 11181:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11182: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11183:     } elsif ($number =~ /^_/) {
                   11184: 	my $sub_condition;
                   11185: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11186: 		&GDBM_READER(),0640)) {
                   11187: 	    $sub_condition=$bighash{'conditions'.$number};
                   11188: 	    untie(%bighash);
                   11189: 	}
                   11190: 	my $value = &docondval($sub_condition);
1.949     raeburn  11191: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11192: 	return $value;
                   11193:     }
1.620     albertel 11194:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11195:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11196:     } else {
                   11197:        return 2;
                   11198:     }
                   11199: }
                   11200: 
1.713     albertel 11201: # get the collection of conditions for this resource
1.26      www      11202: sub condval {
                   11203:     my $condidx=shift;
1.54      www      11204:     my $allpathcond='';
1.713     albertel 11205:     foreach my $cond (split(/\|/,$condidx)) {
                   11206: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11207: 	    $allpathcond.=
                   11208: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11209: 	}
1.191     harris41 11210:     }
1.54      www      11211:     $allpathcond=~s/\|$//;
1.713     albertel 11212:     return &docondval($allpathcond);
                   11213: }
                   11214: 
                   11215: #evaluates an expression of conditions
                   11216: sub docondval {
                   11217:     my ($allpathcond) = @_;
                   11218:     my $result=0;
                   11219:     if ($env{'request.course.id'}
                   11220: 	&& defined($allpathcond)) {
                   11221: 	my $operand='|';
                   11222: 	my @stack;
                   11223: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11224: 	    if ($chunk eq '(') {
                   11225: 		push @stack,($operand,$result);
                   11226: 	    } elsif ($chunk eq ')') {
                   11227: 		my $before=pop @stack;
                   11228: 		if (pop @stack eq '&') {
                   11229: 		    $result=$result>$before?$before:$result;
                   11230: 		} else {
                   11231: 		    $result=$result>$before?$result:$before;
                   11232: 		}
                   11233: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11234: 		$operand=$chunk;
                   11235: 	    } else {
                   11236: 		my $new=directcondval($chunk);
                   11237: 		if ($operand eq '&') {
                   11238: 		    $result=$result>$new?$new:$result;
                   11239: 		} else {
                   11240: 		    $result=$result>$new?$result:$new;
                   11241: 		}
                   11242: 	    }
                   11243: 	}
1.26      www      11244:     }
                   11245:     return $result;
1.421     albertel 11246: }
                   11247: 
                   11248: # ---------------------------------------------------- Devalidate courseresdata
                   11249: 
                   11250: sub devalidatecourseresdata {
                   11251:     my ($coursenum,$coursedomain)=@_;
                   11252:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11253:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11254: }
                   11255: 
1.763     www      11256: 
1.200     www      11257: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11258: #
                   11259: #  Parameters:
                   11260: #      $coursenum    - Number of the course.
                   11261: #      $coursedomain - Domain at which the course was created.
                   11262: #  Returns:
                   11263: #     A hash of the course parameters along (I think) with timestamps
                   11264: #     and version info.
1.877     foxr     11265: 
1.624     albertel 11266: sub get_courseresdata {
                   11267:     my ($coursenum,$coursedomain)=@_;
1.200     www      11268:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11269:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11270:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11271:     my %dumpreply;
1.417     albertel 11272:     unless (defined($cached)) {
1.624     albertel 11273: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11274: 	$result=\%dumpreply;
1.251     albertel 11275: 	my ($tmp) = keys(%dumpreply);
                   11276: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11277: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11278: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11279: 	    return $tmp;
1.416     albertel 11280: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11281: 	    $result=undef;
1.599     albertel 11282: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11283: 	}
                   11284:     }
1.624     albertel 11285:     return $result;
                   11286: }
                   11287: 
1.633     albertel 11288: sub devalidateuserresdata {
                   11289:     my ($uname,$udom)=@_;
                   11290:     my $hashid="$udom:$uname";
                   11291:     &devalidate_cache_new('userres',$hashid);
                   11292: }
                   11293: 
1.624     albertel 11294: sub get_userresdata {
                   11295:     my ($uname,$udom)=@_;
                   11296:     #most student don\'t have any data set, check if there is some data
                   11297:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11298: 
                   11299:     my $hashid="$udom:$uname";
                   11300:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11301:     if (!defined($cached)) {
                   11302: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11303: 	$result=\%resourcedata;
                   11304: 	&do_cache_new('userres',$hashid,$result,600);
                   11305:     }
                   11306:     my ($tmp)=keys(%$result);
                   11307:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11308: 	return $result;
                   11309:     }
                   11310:     #error 2 occurs when the .db doesn't exist
                   11311:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11312:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11313: 	    &logthis("<font color=\"blue\">WARNING:".
                   11314: 		     " Trying to get resource data for ".
                   11315: 		     $uname." at ".$udom.": ".
                   11316: 		     $tmp."</font>");
                   11317:         }
1.624     albertel 11318:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11319: 	#&EXT_cache_set($udom,$uname);
                   11320: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11321: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11322:     }
                   11323:     return $tmp;
                   11324: }
1.879     foxr     11325: #----------------------------------------------- resdata - return resource data
                   11326: #  Purpose:
                   11327: #    Return resource data for either users or for a course.
                   11328: #  Parameters:
                   11329: #     $name      - Course/user name.
                   11330: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11331: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11332: #     $mapp      - decluttered URL of enclosing map  
                   11333: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11334: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11335: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11336: #     $courseid  - CourseID (first part of param identifier).
                   11337: #     $modifier  - Middle part of param identifier.
                   11338: #     $what      - Last part of param identifier.
1.879     foxr     11339: #     @which     - Array of names of resources desired.
                   11340: #  Returns:
                   11341: #     The value of the first reasource in @which that is found in the
                   11342: #     resource hash.
                   11343: #  Exceptional Conditions:
                   11344: #     If the $type passed in is not valid (not the string 'course' or 
                   11345: #     'user', an undefined  reference is returned.
                   11346: #     If none of the resources are found, an undef is returned
1.624     albertel 11347: sub resdata {
1.1301    raeburn  11348:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11349:         $modifier,$what,@which)=@_;
1.624     albertel 11350:     my $result;
                   11351:     if ($type eq 'course') {
                   11352: 	$result=&get_courseresdata($name,$domain);
                   11353:     } elsif ($type eq 'user') {
                   11354: 	$result=&get_userresdata($name,$domain);
                   11355:     }
                   11356:     if (!ref($result)) { return $result; }    
1.251     albertel 11357:     foreach my $item (@which) {
1.1301    raeburn  11358:         if ($item->[1] eq 'course') {
                   11359:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11360:                 unless ($$recursed) {
1.1302    raeburn  11361:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11362:                     $$recursed = 1;
                   11363:                 }
                   11364:                 foreach my $item (@${recurseup}) {
                   11365:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11366:                     last if (defined($result->{$norecursechk}));
                   11367:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11368:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11369:                 }
                   11370:             }
                   11371:         }
                   11372:         if (defined($result->{$item->[0]})) {
1.927     albertel 11373: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11374: 	}
1.250     albertel 11375:     }
1.291     albertel 11376:     return undef;
1.200     www      11377: }
                   11378: 
1.1360    raeburn  11379: sub get_domain_lti {
                   11380:     my ($cdom,$context) = @_;
                   11381:     my ($name,%lti);
                   11382:     if ($context eq 'consumer') {
                   11383:         $name = 'ltitools';
                   11384:     } elsif ($context eq 'provider') {
                   11385:         $name = 'lti';
                   11386:     } else {
                   11387:         return %lti;
                   11388:     }
                   11389:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11390:     if (defined($cached)) {
                   11391:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11392:             %lti = %{$result};
1.1298    raeburn  11393:         }
                   11394:     } else {
1.1360    raeburn  11395:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11396:         if (ref($domconfig{$name}) eq 'HASH') {
                   11397:             %lti = %{$domconfig{$name}};
                   11398:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11399:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11400:                 foreach my $id (keys(%lti)) {
                   11401:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11402:                         foreach my $item ('key','secret') {
1.1360    raeburn  11403:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11404:                         }
                   11405:                     }
                   11406:                 }
                   11407:             }
1.1298    raeburn  11408:         }
                   11409:         my $cachetime = 24*60*60;
1.1360    raeburn  11410:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11411:     }
1.1360    raeburn  11412:     return %lti;
1.1298    raeburn  11413: }
                   11414: 
1.1236    raeburn  11415: sub get_numsuppfiles {
                   11416:     my ($cnum,$cdom,$ignorecache)=@_;
                   11417:     my $hashid=$cnum.':'.$cdom;
                   11418:     my ($suppcount,$cached);
                   11419:     unless ($ignorecache) {
                   11420:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11421:     }
                   11422:     unless (defined($cached)) {
                   11423:         my $chome=&homeserver($cnum,$cdom);
                   11424:         unless ($chome eq 'no_host') {
1.1366    raeburn  11425:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11426:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11427:             ($suppcount,$supptools,$errors) =
                   11428:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11429:                                                          $supptools,$errors);
1.1236    raeburn  11430:         }
                   11431:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11432:     }
                   11433:     return $suppcount;
                   11434: }
                   11435: 
1.379     matthew  11436: #
                   11437: # EXT resource caching routines
                   11438: #
                   11439: 
1.1302    raeburn  11440: {
                   11441: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11442: #
                   11443: # The course for which we cache
                   11444: my $cachedmapkey='';
                   11445: # The cached recursive maps for this course
                   11446: my %cachedmaps=();
                   11447: # When this was last done
                   11448: my $cachedmaptime='';
                   11449: 
1.379     matthew  11450: sub clear_EXT_cache_status {
1.383     albertel 11451:     &delenv('cache.EXT.');
1.379     matthew  11452: }
                   11453: 
                   11454: sub EXT_cache_status {
                   11455:     my ($target_domain,$target_user) = @_;
1.383     albertel 11456:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11457:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11458:         # We know already the user has no data
                   11459:         return 1;
                   11460:     } else {
                   11461:         return 0;
                   11462:     }
                   11463: }
                   11464: 
                   11465: sub EXT_cache_set {
                   11466:     my ($target_domain,$target_user) = @_;
1.383     albertel 11467:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11468:     #&appenv({$cachename => time});
1.379     matthew  11469: }
                   11470: 
1.28      www      11471: # --------------------------------------------------------- Value of a Variable
1.58      www      11472: sub EXT {
1.715     albertel 11473: 
1.1228    raeburn  11474:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11475:     unless ($varname) { return ''; }
1.218     albertel 11476:     #get real user name/domain, courseid and symb
                   11477:     my $courseid;
1.359     albertel 11478:     my $publicuser;
1.427     www      11479:     if ($symbparm) {
                   11480: 	$symbparm=&get_symb_from_alias($symbparm);
                   11481:     }
1.218     albertel 11482:     if (!($uname && $udom)) {
1.790     albertel 11483:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11484:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11485:     } else {
1.620     albertel 11486: 	$courseid=$env{'request.course.id'};
1.218     albertel 11487:     }
1.48      www      11488:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11489:     my $rest;
1.320     albertel 11490:     if (defined($therest[0])) {
1.48      www      11491:        $rest=join('.',@therest);
                   11492:     } else {
                   11493:        $rest='';
                   11494:     }
1.320     albertel 11495: 
1.57      www      11496:     my $qualifierrest=$qualifier;
                   11497:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11498:     my $spacequalifierrest=$space;
                   11499:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11500:     if ($realm eq 'user') {
1.48      www      11501: # --------------------------------------------------------------- user.resource
                   11502: 	if ($space eq 'resource') {
1.651     albertel 11503: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11504: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11505: 		 &&
1.744     albertel 11506: 		 ($symbparm eq &symbread()) ) {	
                   11507: 		# if we are in the middle of processing the resource the
                   11508: 		# get the value we are planning on committing
                   11509:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11510:                     return $Apache::lonhomework::results{$qualifierrest};
                   11511:                 } else {
                   11512:                     return $Apache::lonhomework::history{$qualifierrest};
                   11513:                 }
1.335     albertel 11514: 	    } else {
1.359     albertel 11515: 		my %restored;
1.620     albertel 11516: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11517: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11518: 		} else {
                   11519: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11520: 		}
1.335     albertel 11521: 		return $restored{$qualifierrest};
                   11522: 	    }
1.48      www      11523: # ----------------------------------------------------------------- user.access
                   11524:         } elsif ($space eq 'access') {
1.218     albertel 11525: 	    # FIXME - not supporting calls for a specific user
1.48      www      11526:             return &allowed($qualifier,$rest);
                   11527: # ------------------------------------------ user.preferences, user.environment
                   11528:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11529: 	    if (($uname eq $env{'user.name'}) &&
                   11530: 		($udom eq $env{'user.domain'})) {
                   11531: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11532: 	    } else {
1.359     albertel 11533: 		my %returnhash;
                   11534: 		if (!$publicuser) {
                   11535: 		    %returnhash=&userenvironment($udom,$uname,
                   11536: 						 $qualifierrest);
                   11537: 		}
1.218     albertel 11538: 		return $returnhash{$qualifierrest};
                   11539: 	    }
1.48      www      11540: # ----------------------------------------------------------------- user.course
                   11541:         } elsif ($space eq 'course') {
1.218     albertel 11542: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11543:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11544: # ------------------------------------------------------------------- user.role
                   11545:         } elsif ($space eq 'role') {
1.218     albertel 11546: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11547:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11548:             if ($qualifier eq 'value') {
                   11549: 		return $role;
                   11550:             } elsif ($qualifier eq 'extent') {
                   11551:                 return $where;
                   11552:             }
                   11553: # ----------------------------------------------------------------- user.domain
                   11554:         } elsif ($space eq 'domain') {
1.218     albertel 11555:             return $udom;
1.48      www      11556: # ------------------------------------------------------------------- user.name
                   11557:         } elsif ($space eq 'name') {
1.218     albertel 11558:             return $uname;
1.48      www      11559: # ---------------------------------------------------- Any other user namespace
1.29      www      11560:         } else {
1.359     albertel 11561: 	    my %reply;
                   11562: 	    if (!$publicuser) {
                   11563: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11564: 	    }
                   11565: 	    return $reply{$qualifierrest};
1.48      www      11566:         }
1.236     www      11567:     } elsif ($realm eq 'query') {
                   11568: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11569:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11570: 						[$spacequalifierrest]);
1.620     albertel 11571: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11572:    } elsif ($realm eq 'request') {
1.48      www      11573: # ------------------------------------------------------------- request.browser
                   11574:         if ($space eq 'browser') {
1.1145    bisitz   11575:             return $env{'browser.'.$qualifier};
1.57      www      11576: # ------------------------------------------------------------ request.filename
                   11577:         } else {
1.620     albertel 11578:             return $env{'request.'.$spacequalifierrest};
1.29      www      11579:         }
1.28      www      11580:     } elsif ($realm eq 'course') {
1.48      www      11581: # ---------------------------------------------------------- course.description
1.620     albertel 11582:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11583:     } elsif ($realm eq 'resource') {
1.165     www      11584: 
1.620     albertel 11585: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11586: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11587: 	}
1.693     albertel 11588: 
1.1232    raeburn  11589:         if ($qualifier eq '') {
                   11590: 	    if ($space eq 'title') {
                   11591: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11592: 	        return &gettitle($symbparm);
                   11593: 	    }
1.693     albertel 11594: 	
1.1232    raeburn  11595: 	    if ($space eq 'map') {
                   11596: 	        my ($map) = &decode_symb($symbparm);
                   11597: 	        return &symbread($map);
                   11598: 	    }
                   11599:             if ($space eq 'maptitle') {
                   11600:                 my ($map) = &decode_symb($symbparm);
                   11601:                 return &gettitle($map);
                   11602:             }
                   11603: 	    if ($space eq 'filename') {
                   11604: 	        if ($symbparm) {
                   11605: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11606: 	        }
                   11607: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11608: 	    }
1.1232    raeburn  11609: 
1.1233    raeburn  11610:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11611:                 if ($space eq 'visibleparts') {
                   11612:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11613:                     my $item;
                   11614:                     if (ref($navmap)) {
                   11615:                         my $res = $navmap->getBySymb($symbparm);
                   11616:                         my $parts = $res->parts();
                   11617:                         if (ref($parts) eq 'ARRAY') {
                   11618:                             $item = join(',',@{$parts});
                   11619:                         }
                   11620:                         undef($navmap);
1.1232    raeburn  11621:                     }
1.1233    raeburn  11622:                     return $item;
1.1232    raeburn  11623:                 }
                   11624:             }
                   11625:         }
1.693     albertel 11626: 
1.1301    raeburn  11627: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11628: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11629:         if (($courseid eq '') && ($cid)) {
                   11630:             $courseid = $cid;
                   11631:         }
                   11632: 	if (($symbparm && $courseid) && 
                   11633: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11634: 
1.218     albertel 11635: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11636: 
1.60      www      11637: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11638: 	    my $symbp=$symbparm;
1.1301    raeburn  11639: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11640: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11641:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11642: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11643: 	    if (($env{'user.name'} eq $uname) &&
                   11644: 		($env{'user.domain'} eq $udom)) {
                   11645: 		$section=$env{'request.course.sec'};
1.733     raeburn  11646:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11647:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11648: 	    } else {
1.539     albertel 11649: 		if (! defined($usection)) {
1.551     albertel 11650: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11651: 		} else {
                   11652: 		    $section = $usection;
                   11653: 		}
1.733     raeburn  11654:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11655: 	    }
                   11656: 
                   11657: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11658: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11659:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11660: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11661: 
1.593     albertel 11662: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11663: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11664:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11665: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11666: 
1.60      www      11667: # ----------------------------------------------------------- first, check user
1.624     albertel 11668: 
1.1301    raeburn  11669: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11670:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11671: 				       ([$courselevelr,'resource'],
                   11672: 					[$courselevelm,'map'     ],
1.1301    raeburn  11673:                                         [$courseleveli,'map'     ],
1.927     albertel 11674: 					[$courselevel, 'course'  ]));
1.931     albertel 11675: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11676: 
1.594     albertel 11677: # ------------------------------------------------ second, check some of course
1.684     raeburn  11678:             my $coursereply;
1.691     raeburn  11679:             if (@groups > 0) {
                   11680:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11681:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11682:                                        $mapp,\$recursed,\@recurseup);
                   11683:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11684:             }
1.96      www      11685: 
1.684     raeburn  11686: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11687: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11688: 				  'course',$mapp,\$recursed,\@recurseup,
                   11689:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11690: 				  ([$seclevelr,   'resource'],
                   11691: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11692:                                    [$secleveli,   'map'     ],
1.927     albertel 11693: 				   [$seclevel,    'course'  ],
                   11694: 				   [$courselevelr,'resource']));
                   11695: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11696: 
1.60      www      11697: # ------------------------------------------------------ third, check map parms
1.218     albertel 11698: 	    my %parmhash=();
                   11699: 	    my $thisparm='';
                   11700: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11701: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11702: 		    &GDBM_READER(),0640)) {
1.218     albertel 11703: 		$thisparm=$parmhash{$symbparm};
                   11704: 		untie(%parmhash);
                   11705: 	    }
1.927     albertel 11706: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11707: 	}
1.594     albertel 11708: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11709:  
                   11710:         my $what = $spacequalifierrest;
                   11711: 	$what=~s/\./\_/;
1.282     albertel 11712: 	my $filename;
                   11713: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11714: 	if ($symbparm) {
1.409     www      11715: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11716: 	} else {
1.620     albertel 11717: 	    $filename=$env{'request.filename'};
1.282     albertel 11718: 	}
1.1362    raeburn  11719:         my $toolsymb;
                   11720:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11721:             $toolsymb = $symbparm;
                   11722:         }
                   11723: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11724: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11725: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11726: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11727: 
1.1301    raeburn  11728: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11729: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11730: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11731: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11732: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11733: 				     'course',$mapp,\$recursed,\@recurseup,
                   11734:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11735: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11736:                                       [$courseleveli,'map'   ],
1.927     albertel 11737: 				      [$courselevel, 'course']));
                   11738: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11739: 	}
1.145     www      11740: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11741: 	unless ($space eq '0') {
1.336     albertel 11742: 	    my @parts=split(/_/,$space);
                   11743: 	    my $id=pop(@parts);
                   11744: 	    my $part=join('_',@parts);
                   11745: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11746: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11747: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11748: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11749: 	}
1.395     albertel 11750: 	if ($recurse) { return undef; }
1.1362    raeburn  11751: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11752: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11753: # ---------------------------------------------------- Any other user namespace
                   11754:     } elsif ($realm eq 'environment') {
                   11755: # ----------------------------------------------------------------- environment
1.620     albertel 11756: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11757: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11758: 	} else {
1.770     albertel 11759: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11760: 		return '';
                   11761: 	    }
1.219     albertel 11762: 	    my %returnhash=&userenvironment($udom,$uname,
                   11763: 					    $spacequalifierrest);
                   11764: 	    return $returnhash{$spacequalifierrest};
                   11765: 	}
1.28      www      11766:     } elsif ($realm eq 'system') {
1.48      www      11767: # ----------------------------------------------------------------- system.time
                   11768: 	if ($space eq 'time') {
                   11769: 	    return time;
                   11770:         }
1.696     albertel 11771:     } elsif ($realm eq 'server') {
                   11772: # ----------------------------------------------------------------- system.time
                   11773: 	if ($space eq 'name') {
                   11774: 	    return $ENV{'SERVER_NAME'};
                   11775:         }
1.28      www      11776:     }
1.48      www      11777:     return '';
1.61      www      11778: }
                   11779: 
1.927     albertel 11780: sub get_reply {
                   11781:     my ($reply_value) = @_;
1.940     raeburn  11782:     if (ref($reply_value) eq 'ARRAY') {
                   11783:         if (wantarray) {
                   11784: 	    return @$reply_value;
                   11785:         }
                   11786:         return $reply_value->[0];
                   11787:     } else {
                   11788:         return $reply_value;
1.927     albertel 11789:     }
                   11790: }
                   11791: 
1.691     raeburn  11792: sub check_group_parms {
1.1301    raeburn  11793:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11794:         $recursed,$recurseupref) = @_;
                   11795:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11796:                   [$what,'course']);
                   11797:     my $coursereply;
1.691     raeburn  11798:     foreach my $group (@{$groups}) {
1.1301    raeburn  11799:         my @groupitems = ();
1.691     raeburn  11800:         foreach my $level (@levels) {
1.927     albertel 11801:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11802:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11803:         }
1.1301    raeburn  11804:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11805:                                    $env{'course.'.$courseid.'.domain'},
                   11806:                                    'course',$mapp,$recursed,$recurseupref,
                   11807:                                    $courseid,'.['.$group.'].',$what,
                   11808:                                    @groupitems);
                   11809:         last if (defined($coursereply));
1.691     raeburn  11810:     }
                   11811:     return $coursereply;
                   11812: }
                   11813: 
1.1301    raeburn  11814: sub get_map_hierarchy {
1.1302    raeburn  11815:     my ($mapname,$courseid) = @_;
                   11816:     my @recurseup = ();
1.1301    raeburn  11817:     if ($mapname) {
1.1302    raeburn  11818:         if (($cachedmapkey eq $courseid) &&
                   11819:             (abs($cachedmaptime-time)<5)) {
                   11820:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11821:                 return @{$cachedmaps{$mapname}};
                   11822:             }
                   11823:         }
1.1301    raeburn  11824:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11825:         if (ref($navmap)) {
                   11826:             @recurseup = $navmap->recurseup_maps($mapname);
                   11827:             undef($navmap);
1.1302    raeburn  11828:             $cachedmaps{$mapname} = \@recurseup;
                   11829:             $cachedmaptime=time;
                   11830:             $cachedmapkey=$courseid;
1.1301    raeburn  11831:         }
                   11832:     }
                   11833:     return @recurseup;
                   11834: }
                   11835: 
1.1302    raeburn  11836: }
                   11837: 
1.691     raeburn  11838: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11839:     my ($courseid,@groups) = @_;
                   11840:     @groups = sort(@groups);
1.691     raeburn  11841:     return @groups;
                   11842: }
                   11843: 
1.395     albertel 11844: sub packages_tab_default {
1.1362    raeburn  11845:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11846:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11847: 
                   11848:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11849:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11850: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11851: 	if ($pack_type eq 'default') {
                   11852: 	    $do_default=1;
                   11853: 	} elsif ($pack_type eq 'extension') {
                   11854: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11855: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11856: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11857: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11858: 	}
                   11859:     }
                   11860:     # first look for a package that matches the requested part id
                   11861:     foreach my $package (@specifics) {
                   11862: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11863: 	next if ($pack_part ne $part);
                   11864: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11865: 	    return $packagetab{"$pack_type&$name&default"};
                   11866: 	}
                   11867:     }
                   11868:     # look for any possible matching non extension_ package
                   11869:     foreach my $package (@specifics) {
                   11870: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11871: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11872: 	    return $packagetab{"$pack_type&$name&default"};
                   11873: 	}
1.585     albertel 11874: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11875: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11876: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11877: 	}
                   11878:     }
1.738     albertel 11879:     # look for any posible extension_ match
                   11880:     foreach my $package (@extension) {
                   11881: 	my ($package,$pack_type)=@{$package};
                   11882: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11883: 	    return $packagetab{"$pack_type&$name&default"};
                   11884: 	}
                   11885: 	if (defined($packagetab{$package."&$name&default"})) {
                   11886: 	    return $packagetab{$package."&$name&default"};
                   11887: 	}
                   11888:     }
                   11889:     # look for a global default setting
                   11890:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11891: 	return $packagetab{"default&$name&default"};
                   11892:     }
1.395     albertel 11893:     return undef;
                   11894: }
                   11895: 
1.334     albertel 11896: sub add_prefix_and_part {
                   11897:     my ($prefix,$part)=@_;
                   11898:     my $keyroot;
                   11899:     if (defined($prefix) && $prefix !~ /^__/) {
                   11900: 	# prefix that has a part already
                   11901: 	$keyroot=$prefix;
                   11902:     } elsif (defined($prefix)) {
                   11903: 	# prefix that is missing a part
                   11904: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11905:     } else {
                   11906: 	# no prefix at all
                   11907: 	if (defined($part)) { $keyroot='_'.$part; }
                   11908:     }
                   11909:     return $keyroot;
                   11910: }
                   11911: 
1.71      www      11912: # ---------------------------------------------------------------- Get metadata
                   11913: 
1.599     albertel 11914: my %metaentry;
1.1070    www      11915: my %importedpartids;
1.1369    raeburn  11916: my %importedrespids;
1.71      www      11917: sub metadata {
1.1362    raeburn  11918:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11919:     $uri=&declutter($uri);
1.288     albertel 11920:     # if it is a non metadata possible uri return quickly
1.529     albertel 11921:     if (($uri eq '') || 
                   11922: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11923: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11924:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11925: 	return undef;
                   11926:     }
1.1261    raeburn  11927:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11928: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11929: 	return undef;
1.288     albertel 11930:     }
1.73      www      11931:     my $filename=$uri;
                   11932:     $uri=~s/\.meta$//;
1.172     www      11933: #
                   11934: # Is the metadata already cached?
1.177     www      11935: # Look at timestamp of caching
1.172     www      11936: # Everything is cached by the main uri, libraries are never directly cached
                   11937: #
1.428     albertel 11938:     if (!defined($liburi)) {
1.599     albertel 11939: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11940: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11941:     }
1.1362    raeburn  11942: 
                   11943: #
                   11944: # If the uri is for an external tool the file from
                   11945: # which metadata should be retrieved depends on whether
                   11946: # the tool had been configured to be gradable (set in the Course
                   11947: # Editor or Resource Editor).
                   11948: #
                   11949: # If a valid symb has been included as the third arg in the call
                   11950: # to &metadata() that can be used to retrieve the value of
                   11951: # parameter_0_gradable set for the resource, and included in the
                   11952: # uploaded map containing the tool. The value is retrieved via
                   11953: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11954: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11955: # is retrieved via &get().
                   11956: #
                   11957: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11958: # hiddenresource and encrypturl (during course initialization)
                   11959: # the map-level parameter for resource.0.gradable included in the 
                   11960: # uploaded map containing the tool will not yet have been stored
                   11961: # in the user_course_parms.db file for the user's session, so in 
                   11962: # this case fall back to retrieving gradable status from the
                   11963: # exttool_$marker.db file.
1.1362    raeburn  11964: #
                   11965: # In order to avoid an infinite loop, &metadata() will return
                   11966: # before a call to &EXT(), if the uri is for an external tool
                   11967: # and the $what for which metadata is being requested is
                   11968: # parameter_0_gradable or 0_gradable.
                   11969: #
                   11970: 
                   11971:     if ($uri =~ /ext\.tool$/) {
                   11972:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11973:             return;
                   11974:         } else {
                   11975:             my ($checked,$use_passback);
                   11976:             if ($toolsymb ne '') {
                   11977:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11978:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11979:                     $checked = 1;
                   11980:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11981:                         $use_passback = 1;
                   11982:                     }
                   11983:                 }
                   11984:             }
                   11985:             unless ($checked) {
                   11986:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11987:                 $marker=~s/\D//g;
1.1363    raeburn  11988:                 if ($marker) {
1.1362    raeburn  11989:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11990:                     $use_passback = $toolsettings{'gradable'};
                   11991:                 }
                   11992:             }
                   11993:             if ($use_passback) {
                   11994:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11995:             } else {
                   11996:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11997:             }
                   11998:         }
                   11999:     }
                   12000: 
1.428     albertel 12001:     {
1.1069    www      12002: # Imported parts would go here
1.1369    raeburn  12003:         my @origfiletagids=();
1.1069    www      12004:         my $importedparts=0;
1.1369    raeburn  12005: 
                   12006: # Imported responseids would go here
                   12007:         my $importedresponses=0;
1.172     www      12008: #
                   12009: # Is this a recursive call for a library?
                   12010: #
1.599     albertel 12011: #	if (! exists($metacache{$uri})) {
                   12012: #	    $metacache{$uri}={};
                   12013: #	}
1.924     albertel 12014: 	my $cachetime = 60*60;
1.171     www      12015:         if ($liburi) {
                   12016: 	    $liburi=&declutter($liburi);
                   12017:             $filename=$liburi;
1.401     bowersj2 12018:         } else {
1.599     albertel 12019: 	    &devalidate_cache_new('meta',$uri);
                   12020: 	    undef(%metaentry);
1.401     bowersj2 12021: 	}
1.140     www      12022:         my %metathesekeys=();
1.73      www      12023:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12024: 	my $metastring;
1.1140    www      12025: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12026: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12027: 	    $metastring = 
1.929     albertel 12028: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12029: 					  ('grade_target' => 'meta'));
                   12030: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12031: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12032:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12033: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12034: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12035: 	    $metastring=&getfile($file);
1.489     albertel 12036: 	}
1.208     albertel 12037:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12038:         my $token;
1.140     www      12039:         undef %metathesekeys;
1.71      www      12040:         while ($token=$parser->get_token) {
1.339     albertel 12041: 	    if ($token->[0] eq 'S') {
                   12042: 		if (defined($token->[2]->{'package'})) {
1.172     www      12043: #
                   12044: # This is a package - get package info
                   12045: #
1.339     albertel 12046: 		    my $package=$token->[2]->{'package'};
                   12047: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12048: 		    if (defined($token->[2]->{'id'})) { 
                   12049: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12050: 		    }
1.599     albertel 12051: 		    if ($metaentry{':packages'}) {
                   12052: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12053: 		    } else {
1.599     albertel 12054: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12055: 		    }
1.736     albertel 12056: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12057: 			my $part=$keyroot;
                   12058: 			$part=~s/^\_//;
1.736     albertel 12059: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12060: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12061: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12062: 			    # ignore package.tab specified default values
                   12063:                             # here &package_tab_default() will fetch those
                   12064: 			    if ($subp eq 'default') { next; }
1.736     albertel 12065: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12066: 			    my $unikey;
                   12067: 			    if ($pack =~ /_0$/) {
                   12068: 				$unikey='parameter_0_'.$name;
                   12069: 				$part=0;
                   12070: 			    } else {
                   12071: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12072: 			    }
1.339     albertel 12073: 			    if ($subp eq 'display') {
                   12074: 				$value.=' [Part: '.$part.']';
                   12075: 			    }
1.599     albertel 12076: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12077: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12078: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12079: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12080: 			    }
1.599     albertel 12081: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12082: 				$metaentry{':'.$unikey}=
                   12083: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12084: 			    }
1.339     albertel 12085: 			}
                   12086: 		    }
                   12087: 		} else {
1.172     www      12088: #
                   12089: # This is not a package - some other kind of start tag
1.339     albertel 12090: #
                   12091: 		    my $entry=$token->[1];
1.1068    www      12092: 		    my $unikey='';
1.175     www      12093: 
1.339     albertel 12094: 		    if ($entry eq 'import') {
1.175     www      12095: #
                   12096: # Importing a library here
1.339     albertel 12097: #
1.1067    www      12098:                         my $location=$parser->get_text('/import');
                   12099:                         my $dir=$filename;
                   12100:                         $dir=~s|[^/]*$||;
                   12101:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12102: 
                   12103:                         my $importid=$token->[2]->{'id'};
1.1068    www      12104:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12105: #
                   12106: # Check metadata for imported file to
                   12107: # see if it contained response items
                   12108: #
1.1372    raeburn  12109:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12110:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12111:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12112:                                                            $depthcount+1));
                   12113:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12114:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12115:                                                              undef,$depthcount+1);
                   12116:                             if ($libresponseorder ne '') {
                   12117:                                 if ($#origfiletagids<0) {
                   12118:                                     undef(%importedrespids);
                   12119:                                     undef(%importedpartids);
                   12120:                                 }
1.1373    raeburn  12121:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12122:                                 if (@respids) {
                   12123:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12124:                                 }
                   12125:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12126:                                     $importedresponses = 1;
1.1369    raeburn  12127: # We need to get the original file and the imported file to get the response order correct
                   12128: # Load and inspect original file
1.1372    raeburn  12129:                                     if ($#origfiletagids<0) {
                   12130:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12131:                                         $origfile=&getfile($origfilelocation);
                   12132:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12133:                                     }
1.1369    raeburn  12134:                                 }
                   12135:                             }
                   12136:                         }
1.1370    raeburn  12137: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12138: # hash populated for imported library file
                   12139:                         %metaentry = %currmetaentry;
                   12140:                         undef(%currmetaentry);
1.1374    raeburn  12141:                         if ($importmode eq 'part') {
1.1068    www      12142: # Import as part(s)
1.1069    www      12143:                            $importedparts=1;
                   12144: # We need to get the original file and the imported file to get the part order correct
                   12145: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12146: # Load and inspect original file if we didn't do that already
                   12147:                            if ($#origfiletagids<0) {
                   12148:                                undef(%importedrespids);
                   12149:                                undef(%importedpartids);
                   12150:                                if ($origfile eq '') {
                   12151:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12152:                                    $origfile=&getfile($origfilelocation);
                   12153:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12154:                                }
1.1070    www      12155:                            }
1.1372    raeburn  12156:                            my @impfilepartids;
                   12157: # If <partorder> tag is included in metadata for the imported file
                   12158: # get the parts in the imported file from that.
                   12159:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12160:                                %currmetaentry = %metaentry;
                   12161:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12162:                                                             $depthcount+1);
                   12163:                                %metaentry = %currmetaentry;
                   12164:                                undef(%currmetaentry);
                   12165:                                if ($libpartorder ne '') {
                   12166:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12167:                                }
                   12168:                            } else {
                   12169: # If no <partorder> tag available, load and inspect imported file
                   12170:                                my $impfile=&getfile($location);
                   12171:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12172:                            }
1.1069    www      12173:                            if ($#impfilepartids>=0) {
                   12174: # This problem had parts
1.1070    www      12175:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12176:                            } else {
                   12177: # Importing by turning a single problem into a problem part
                   12178: # It gets the import-tags ID as part-ID
                   12179:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12180:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12181:                            }
1.1068    www      12182:                         } else {
1.1374    raeburn  12183: # Import as problem or as normal import
                   12184:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12185:                             unless ($importmode eq 'problem') {
1.1068    www      12186: # Normal import
1.1374    raeburn  12187:                                 if (defined($token->[2]->{'id'})) {
                   12188:                                     $unikey.='_'.$token->[2]->{'id'};
                   12189:                                 }
                   12190:                             }
                   12191: # Check metadata for imported file to
                   12192: # see if it contained parts
                   12193:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12194:                                 %currmetaentry = %metaentry;
                   12195:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12196:                                                              $depthcount+1);
                   12197:                                 %metaentry = %currmetaentry;
                   12198:                                 undef(%currmetaentry);
                   12199:                                 if ($libpartorder ne '') {
                   12200:                                     $importedparts = 1;
                   12201:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12202:                                 }
                   12203:                             }
1.1067    www      12204:                         }
1.339     albertel 12205: 			if ($depthcount<20) {
1.736     albertel 12206: 			    my $metadata = 
1.1362    raeburn  12207: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12208: 					  $depthcount+1);
                   12209: 			    foreach my $meta (split(',',$metadata)) {
                   12210: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12211: 				$metathesekeys{$meta}=1;
1.339     albertel 12212: 			    }
1.1068    www      12213:                         }
1.1067    www      12214: 		    } else {
                   12215: #
                   12216: # Not importing, some other kind of non-package, non-library start tag
                   12217: # 
                   12218:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12219:                         if (defined($token->[2]->{'id'})) {
                   12220:                             $unikey.='_'.$token->[2]->{'id'};
                   12221:                         }
1.339     albertel 12222: 			if (defined($token->[2]->{'name'})) { 
                   12223: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12224: 			}
                   12225: 			$metathesekeys{$unikey}=1;
1.736     albertel 12226: 			foreach my $param (@{$token->[3]}) {
                   12227: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12228: 				$token->[2]->{$param};
1.339     albertel 12229: 			}
                   12230: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12231: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12232: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12233: 		 # only ws inside the tag, and not in default, so use default
                   12234: 		 # as value
1.599     albertel 12235: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12236: 			} elsif ( $internaltext =~ /\S/ ) {
                   12237: 		  # something interesting inside the tag
                   12238: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12239: 			} else {
1.908     albertel 12240: 		  # no interesting values, don't set a default
1.339     albertel 12241: 			}
1.172     www      12242: # end of not-a-package not-a-library import
1.339     albertel 12243: 		    }
1.172     www      12244: # end of not-a-package start tag
1.339     albertel 12245: 		}
1.172     www      12246: # the next is the end of "start tag"
1.339     albertel 12247: 	    }
                   12248: 	}
1.483     albertel 12249: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12250: 	$extension = lc($extension);
                   12251: 	if ($extension eq 'htm') { $extension='html'; }
                   12252: 
1.737     albertel 12253: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12254: 	    #no specific packages #how's our extension
                   12255: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12256: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12257: 					 \%metathesekeys);
                   12258: 	}
1.883     albertel 12259: 
                   12260: 	if (!exists($metaentry{':packages'})
                   12261: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12262: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12263: 		#no specific packages well let's get default then
                   12264: 		if ($key!~/^default&/) { next; }
1.488     albertel 12265: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12266: 					     \%metathesekeys);
                   12267: 	    }
                   12268: 	}
1.338     www      12269: # are there custom rights to evaluate
1.599     albertel 12270: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12271: 
1.338     www      12272:     #
                   12273:     # Importing a rights file here
1.339     albertel 12274:     #
                   12275: 	    unless ($depthcount) {
1.599     albertel 12276: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12277: 		my $dir=$filename;
                   12278: 		$dir=~s|[^/]*$||;
                   12279: 		$location=&filelocation($dir,$location);
1.736     albertel 12280: 		my $rights_metadata =
1.1362    raeburn  12281: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12282: 			      $depthcount+1);
                   12283: 		foreach my $rights (split(',',$rights_metadata)) {
                   12284: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12285: 		    $metathesekeys{$rights}=1;
1.339     albertel 12286: 		}
                   12287: 	    }
                   12288: 	}
1.737     albertel 12289: 	# uniqifiy package listing
                   12290: 	my %seen;
                   12291: 	my @uniq_packages =
                   12292: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12293: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12294: 
1.1369    raeburn  12295:         if (($importedresponses) || ($importedparts)) {
                   12296:             if ($importedparts) {
1.1070    www      12297: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12298:                 $metaentry{':partorder'}='';
                   12299:                 $metathesekeys{'partorder'}=1;
                   12300:             }
                   12301:             if ($importedresponses) {
                   12302: # We had imported responses and need to rebuil responseorder
                   12303:                 $metaentry{':responseorder'}='';
                   12304:                 $metathesekeys{'responseorder'}=1;
                   12305:             }
                   12306:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12307:                 my $origid = $origfiletagids[$index+1];
                   12308:                 if ($origfiletagids[$index] eq 'part') {
                   12309: # Original part, part of the problem
                   12310:                     if ($importedparts) {
                   12311:                         $metaentry{':partorder'}.=','.$origid;
                   12312:                     }
                   12313:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12314:                     if ($importedparts) {
                   12315: # We have imported parts at this position
1.1373    raeburn  12316:                         if ($importedpartids{$origid} ne '') {
                   12317:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12318:                         }
1.1369    raeburn  12319:                     }
                   12320:                     if ($importedresponses) {
                   12321: # We have imported responses at this position
1.1373    raeburn  12322:                         if ($importedrespids{$origid} ne '') {
                   12323:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12324:                         }
                   12325:                     }
                   12326:                 } else {
                   12327: # Original response item, part of the problem
                   12328:                     if ($importedresponses) {
                   12329:                         $metaentry{':responseorder'}.=','.$origid;
                   12330:                     }
                   12331:                 }
                   12332:             }
                   12333:             if ($importedparts) {
                   12334:                 $metaentry{':partorder'}=~s/^\,//;
                   12335:             }
                   12336:             if ($importedresponses) {
                   12337:                 $metaentry{':responseorder'}=~s/^\,//;
                   12338:             }
1.1070    www      12339:         }
1.737     albertel 12340: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12341: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12342: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12343:         unless ($liburi) {
                   12344: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12345:         }
1.177     www      12346: # this is the end of "was not already recently cached
1.71      www      12347:     }
1.599     albertel 12348:     return $metaentry{':'.$what};
1.261     albertel 12349: }
                   12350: 
1.488     albertel 12351: sub metadata_create_package_def {
1.483     albertel 12352:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12353:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12354:     if ($subp eq 'default') { next; }
                   12355:     
1.599     albertel 12356:     if (defined($metaentry{':packages'})) {
                   12357: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12358:     } else {
1.599     albertel 12359: 	$metaentry{':packages'}=$package;
1.483     albertel 12360:     }
                   12361:     my $value=$packagetab{$key};
                   12362:     my $unikey;
                   12363:     $unikey='parameter_0_'.$name;
1.599     albertel 12364:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12365:     $$metathesekeys{$unikey}=1;
1.599     albertel 12366:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12367: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12368:     }
1.599     albertel 12369:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12370: 	$metaentry{':'.$unikey}=
                   12371: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12372:     }
                   12373: }
                   12374: 
1.261     albertel 12375: sub metadata_generate_part0 {
                   12376:     my ($metadata,$metacache,$uri) = @_;
                   12377:     my %allnames;
1.737     albertel 12378:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12379: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12380: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12381: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12382: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12383: 	    $allnames{$name}=$part;
                   12384: 	  }
                   12385: 	}
                   12386:     }
                   12387:     foreach my $name (keys(%allnames)) {
                   12388:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12389:       my $key=":parameter_0_$name";
1.261     albertel 12390:       $$metacache{"$key.part"}='0';
                   12391:       $$metacache{"$key.name"}=$name;
1.428     albertel 12392:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12393: 					   $allnames{$name}.'_'.$name.
                   12394: 					   '.type'};
1.428     albertel 12395:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12396: 			     '.display'};
1.644     www      12397:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12398:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12399:       $$metacache{"$key.display"}=$olddis;
                   12400:     }
1.71      www      12401: }
                   12402: 
1.764     albertel 12403: # ------------------------------------------------------ Devalidate title cache
                   12404: 
                   12405: sub devalidate_title_cache {
                   12406:     my ($url)=@_;
                   12407:     if (!$env{'request.course.id'}) { return; }
                   12408:     my $symb=&symbread($url);
                   12409:     if (!$symb) { return; }
                   12410:     my $key=$env{'request.course.id'}."\0".$symb;
                   12411:     &devalidate_cache_new('title',$key);
                   12412: }
                   12413: 
1.1014    droeschl 12414: # ------------------------------------------------- Get the title of a course
                   12415: 
                   12416: sub current_course_title {
                   12417:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12418: }
1.301     www      12419: # ------------------------------------------------- Get the title of a resource
                   12420: 
                   12421: sub gettitle {
                   12422:     my $urlsymb=shift;
                   12423:     my $symb=&symbread($urlsymb);
1.534     albertel 12424:     if ($symb) {
1.620     albertel 12425: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12426: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12427: 	if (defined($cached)) { 
                   12428: 	    return $result;
                   12429: 	}
1.534     albertel 12430: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12431: 	my $title='';
1.907     albertel 12432: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12433: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12434: 	} else {
                   12435: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12436: 		    &GDBM_READER(),0640)) {
                   12437: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12438: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12439: 		untie(%bighash);
                   12440: 	    }
1.534     albertel 12441: 	}
                   12442: 	$title=~s/\&colon\;/\:/gs;
                   12443: 	if ($title) {
1.1159    www      12444: # Remember both $symb and $title for dynamic metadata
                   12445:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12446:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12447: # Cache this title and then return it
1.599     albertel 12448: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12449: 	}
                   12450: 	$urlsymb=$url;
                   12451:     }
                   12452:     my $title=&metadata($urlsymb,'title');
                   12453:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12454:     return $title;
1.301     www      12455: }
1.613     albertel 12456: 
1.614     albertel 12457: sub get_slot {
                   12458:     my ($which,$cnum,$cdom)=@_;
                   12459:     if (!$cnum || !$cdom) {
1.790     albertel 12460: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12461: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12462: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12463:     }
1.703     albertel 12464:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12465:     my %slotinfo;
                   12466:     if (exists($remembered{$key})) {
                   12467: 	$slotinfo{$which} = $remembered{$key};
                   12468:     } else {
                   12469: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12470: 	&Apache::lonhomework::showhash(%slotinfo);
                   12471: 	my ($tmp)=keys(%slotinfo);
                   12472: 	if ($tmp=~/^error:/) { return (); }
                   12473: 	$remembered{$key} = $slotinfo{$which};
                   12474:     }
1.616     albertel 12475:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12476: 	return %{$slotinfo{$which}};
                   12477:     }
                   12478:     return $slotinfo{$which};
1.614     albertel 12479: }
1.1150    raeburn  12480: 
                   12481: sub get_reservable_slots {
                   12482:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12483:     my $now = time;
                   12484:     my $reservable_info;
                   12485:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12486:     if (exists($remembered{$key})) {
                   12487:         $reservable_info = $remembered{$key};
                   12488:     } else {
                   12489:         my %resv;
                   12490:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12491:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12492:         $reservable_info = \%resv;
                   12493:         $remembered{$key} = $reservable_info;
                   12494:     }
                   12495:     return $reservable_info;
                   12496: }
                   12497: 
                   12498: sub get_course_slots {
                   12499:     my ($cnum,$cdom) = @_;
                   12500:     my $hashid=$cnum.':'.$cdom;
                   12501:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12502:     if (defined($cached)) {
                   12503:         if (ref($result) eq 'HASH') {
                   12504:             return %{$result};
                   12505:         }
                   12506:     } else {
                   12507:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12508:         my ($tmp) = keys(%slots);
                   12509:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12510:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12511:             return %slots;
                   12512:         }
                   12513:     }
                   12514:     return;
                   12515: }
                   12516: 
                   12517: sub devalidate_slots_cache {
                   12518:     my ($cnum,$cdom)=@_;
                   12519:     my $hashid=$cnum.':'.$cdom;
                   12520:     &devalidate_cache_new('allslots',$hashid);
                   12521: }
                   12522: 
1.1181    raeburn  12523: sub get_coursechange {
                   12524:     my ($cdom,$cnum) = @_;
                   12525:     if ($cdom eq '' || $cnum eq '') {
                   12526:         return unless ($env{'request.course.id'});
                   12527:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12528:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12529:     }
                   12530:     my $hashid=$cdom.'_'.$cnum;
                   12531:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12532:     if ((defined($cached)) && ($change ne '')) {
                   12533:         return $change;
                   12534:     } else {
                   12535:         my %crshash;
                   12536:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12537:         if ($crshash{'internal.contentchange'} eq '') {
                   12538:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12539:             if ($change eq '') {
                   12540:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12541:                 $change = $crshash{'internal.created'};
                   12542:             }
                   12543:         } else {
                   12544:             $change = $crshash{'internal.contentchange'};
                   12545:         }
                   12546:         my $cachetime = 600;
                   12547:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12548:     }
                   12549:     return $change;
                   12550: }
                   12551: 
                   12552: sub devalidate_coursechange_cache {
                   12553:     my ($cnum,$cdom)=@_;
                   12554:     my $hashid=$cnum.':'.$cdom;
                   12555:     &devalidate_cache_new('crschange',$hashid);
                   12556: }
                   12557: 
1.31      www      12558: # ------------------------------------------------- Update symbolic store links
                   12559: 
                   12560: sub symblist {
                   12561:     my ($mapname,%newhash)=@_;
1.438     www      12562:     $mapname=&deversion(&declutter($mapname));
1.31      www      12563:     my %hash;
1.620     albertel 12564:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12565:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12566:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12567: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12568: 		next if ($url eq 'last_known'
                   12569: 			 && $env{'form.no_update_last_known'});
                   12570: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12571: 						    $newhash{$url}->[1],
                   12572: 						    $newhash{$url}->[0]);
1.191     harris41 12573:             }
1.31      www      12574:             if (untie(%hash)) {
                   12575: 		return 'ok';
                   12576:             }
                   12577:         }
                   12578:     }
                   12579:     return 'error';
1.212     www      12580: }
                   12581: 
                   12582: # --------------------------------------------------------------- Verify a symb
                   12583: 
                   12584: sub symbverify {
1.1190    raeburn  12585:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12586:     my $thisfn=$thisurl;
1.439     www      12587:     $thisfn=&declutter($thisfn);
1.215     www      12588: # direct jump to resource in page or to a sequence - will construct own symbs
                   12589:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12590: # check URL part
1.409     www      12591:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12592: 
1.431     www      12593:     unless ($url eq $thisfn) { return 0; }
1.213     www      12594: 
1.216     www      12595:     $symb=&symbclean($symb);
1.510     www      12596:     $thisurl=&deversion($thisurl);
1.439     www      12597:     $thisfn=&deversion($thisfn);
1.213     www      12598: 
                   12599:     my %bighash;
                   12600:     my $okay=0;
1.431     www      12601: 
1.620     albertel 12602:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12603:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12604:         my $noclutter;
1.1032    raeburn  12605:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12606:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12607:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12608:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12609:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12610:                 $noclutter = 1;
                   12611:             }
                   12612:         }
                   12613:         my $ids;
                   12614:         if ($noclutter) {
                   12615:             $ids=$bighash{'ids_'.$thisurl};
                   12616:         } else {
                   12617:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12618:         }
1.1102    raeburn  12619:         unless ($ids) {
                   12620:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12621:             $ids=$bighash{$idkey};
1.216     www      12622:         }
                   12623:         if ($ids) {
                   12624: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12625:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12626:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12627:             }
1.800     albertel 12628: 	    foreach my $id (split(/\,/,$ids)) {
                   12629: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12630:                if (
                   12631:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12632:    eq $symb) {
                   12633:                    if (ref($encstate)) {
                   12634:                        $$encstate = $bighash{'encrypted_'.$id};
                   12635:                    }
1.620     albertel 12636: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12637: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12638:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12639: 		       $okay=1;
1.1202    raeburn  12640:                        last;
1.582     albertel 12641: 		   }
                   12642: 	       }
1.216     www      12643: 	   }
                   12644:         }
1.213     www      12645: 	untie(%bighash);
                   12646:     }
                   12647:     return $okay;
1.31      www      12648: }
                   12649: 
1.210     www      12650: # --------------------------------------------------------------- Clean-up symb
                   12651: 
                   12652: sub symbclean {
                   12653:     my $symb=shift;
1.568     albertel 12654:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12655: # remove version from map
                   12656:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12657: 
1.210     www      12658: # remove version from URL
                   12659:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12660: 
1.507     www      12661: # remove wrapper
                   12662: 
1.510     www      12663:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12664:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12665:     return $symb;
1.409     www      12666: }
                   12667: 
                   12668: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12669: 
                   12670: sub encode_symb {
                   12671:     my ($map,$resid,$url)=@_;
                   12672:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12673: }
1.409     www      12674: 
                   12675: sub decode_symb {
1.568     albertel 12676:     my $symb=shift;
                   12677:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12678:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12679:     return (&fixversion($map),$resid,&fixversion($url));
                   12680: }
                   12681: 
                   12682: sub fixversion {
                   12683:     my $fn=shift;
1.609     banghart 12684:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12685:     my %bighash;
                   12686:     my $uri=&clutter($fn);
1.620     albertel 12687:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12688: # is this cached?
1.599     albertel 12689:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12690:     if (defined($cached)) { return $result; }
                   12691: # unfortunately not cached, or expired
1.620     albertel 12692:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12693: 	    &GDBM_READER(),0640)) {
                   12694:  	if ($bighash{'version_'.$uri}) {
                   12695:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12696:  	    unless (($version eq 'mostrecent') || 
                   12697: 		    ($version==&getversion($uri))) {
1.440     www      12698:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12699:  	    }
                   12700:  	}
                   12701:  	untie %bighash;
1.413     www      12702:     }
1.599     albertel 12703:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12704: }
                   12705: 
                   12706: sub deversion {
                   12707:     my $url=shift;
                   12708:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12709:     return $url;
1.210     www      12710: }
                   12711: 
1.31      www      12712: # ------------------------------------------------------ Return symb list entry
                   12713: 
                   12714: sub symbread {
1.1282    raeburn  12715:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12716:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12717:     if (defined($env{$cache_str})) {
                   12718:         if ($ignorecachednull) {
                   12719:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12720:         } else {
                   12721:             return $env{$cache_str};
                   12722:         }
                   12723:     }
1.242     www      12724: # no filename provided? try from environment
1.1265    raeburn  12725:     unless ($thisfn) {
1.620     albertel 12726:         if ($env{'request.symb'}) {
                   12727: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12728: 	}
1.620     albertel 12729: 	$thisfn=$env{'request.filename'};
1.44      www      12730:     }
1.569     albertel 12731:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12732: # is that filename actually a symb? Verify, clean, and return
                   12733:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12734: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12735: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12736: 	}
1.242     www      12737:     }
1.44      www      12738:     $thisfn=declutter($thisfn);
1.31      www      12739:     my %hash;
1.37      www      12740:     my %bighash;
                   12741:     my $syval='';
1.620     albertel 12742:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12743:         my $targetfn = $thisfn;
1.609     banghart 12744:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12745:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12746:         }
1.687     albertel 12747: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12748: 	    $targetfn=$1;
                   12749: 	}
1.620     albertel 12750:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12751:                       &GDBM_READER(),0640)) {
1.481     raeburn  12752: 	    $syval=$hash{$targetfn};
1.37      www      12753:             untie(%hash);
                   12754:         }
                   12755: # ---------------------------------------------------------- There was an entry
                   12756:         if ($syval) {
1.601     albertel 12757: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12758: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12759: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12760: 		    #return $env{$cache_str}='';
1.601     albertel 12761: 		#}    
                   12762: 		#$syval.=$1;
                   12763: 	    #}
1.37      www      12764:         } else {
                   12765: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12766:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12767:                             &GDBM_READER(),0640)) {
1.37      www      12768: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12769:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12770:               unless ($ids) { 
                   12771:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12772:               }
                   12773:               unless ($ids) {
                   12774: # alias?
                   12775: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12776:               }
1.37      www      12777:               if ($ids) {
                   12778: # ------------------------------------------------------------------- Has ID(s)
                   12779:                  my @possibilities=split(/\,/,$ids);
1.39      www      12780:                  if ($#possibilities==0) {
                   12781: # ----------------------------------------------- There is only one possibility
1.37      www      12782: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12783: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12784: 						    $resid,$thisfn);
1.1282    raeburn  12785:                      if (ref($possibles) eq 'HASH') {
                   12786:                          $possibles->{$syval} = 1;    
                   12787:                      }
                   12788:                      if ($checkforblock) {
                   12789:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12790:                          if (@blockers) {
                   12791:                              $syval = '';
                   12792:                              return;
                   12793:                          }
                   12794:                      }
                   12795:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12796: # ------------------------------------------ There is more than one possibility
                   12797:                      my $realpossible=0;
1.800     albertel 12798:                      foreach my $id (@possibilities) {
                   12799: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12800:                          my $canaccess;
                   12801:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12802:                              $canaccess = 1;
                   12803:                          } else { 
                   12804:                              $canaccess = &allowed('bre',$file);
                   12805:                          }
                   12806:                          if ($canaccess) {
                   12807:          		     my ($mapid,$resid)=split(/\./,$id);
                   12808:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12809:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12810: 						             $resid,$thisfn);
                   12811:                                  if (ref($possibles) eq 'HASH') {
                   12812:                                      $possibles->{$syval} = 1;
                   12813:                                  }
                   12814:                                  if ($checkforblock) {
                   12815:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12816:                                      unless (@blockers > 0) {
                   12817:                                          $syval = $poss_syval;
                   12818:                                          $realpossible++;
                   12819:                                      }
                   12820:                                  } else {
                   12821:                                      $syval = $poss_syval;
                   12822:                                      $realpossible++;
                   12823:                                  }
                   12824:                              }
1.39      www      12825: 			 }
1.191     harris41 12826:                      }
1.39      www      12827: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12828:                  } else {
                   12829:                      $syval='';
1.37      www      12830:                  }
                   12831: 	      }
1.1282    raeburn  12832:               untie(%bighash);
1.481     raeburn  12833:            }
1.31      www      12834:         }
1.62      www      12835:         if ($syval) {
1.620     albertel 12836: 	    return $env{$cache_str}=$syval;
1.62      www      12837:         }
1.31      www      12838:     }
1.949     raeburn  12839:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12840:     return $env{$cache_str}='';
1.31      www      12841: }
                   12842: 
                   12843: # ---------------------------------------------------------- Return random seed
                   12844: 
1.32      www      12845: sub numval {
                   12846:     my $txt=shift;
                   12847:     $txt=~tr/A-J/0-9/;
                   12848:     $txt=~tr/a-j/0-9/;
                   12849:     $txt=~tr/K-T/0-9/;
                   12850:     $txt=~tr/k-t/0-9/;
                   12851:     $txt=~tr/U-Z/0-5/;
                   12852:     $txt=~tr/u-z/0-5/;
                   12853:     $txt=~s/\D//g;
1.564     albertel 12854:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12855:     return int($txt);
1.368     albertel 12856: }
                   12857: 
1.484     albertel 12858: sub numval2 {
                   12859:     my $txt=shift;
                   12860:     $txt=~tr/A-J/0-9/;
                   12861:     $txt=~tr/a-j/0-9/;
                   12862:     $txt=~tr/K-T/0-9/;
                   12863:     $txt=~tr/k-t/0-9/;
                   12864:     $txt=~tr/U-Z/0-5/;
                   12865:     $txt=~tr/u-z/0-5/;
                   12866:     $txt=~s/\D//g;
                   12867:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12868:     my $total;
                   12869:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12870:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12871:     return int($total);
                   12872: }
                   12873: 
1.575     albertel 12874: sub numval3 {
                   12875:     use integer;
                   12876:     my $txt=shift;
                   12877:     $txt=~tr/A-J/0-9/;
                   12878:     $txt=~tr/a-j/0-9/;
                   12879:     $txt=~tr/K-T/0-9/;
                   12880:     $txt=~tr/k-t/0-9/;
                   12881:     $txt=~tr/U-Z/0-5/;
                   12882:     $txt=~tr/u-z/0-5/;
                   12883:     $txt=~s/\D//g;
                   12884:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12885:     my $total;
                   12886:     foreach my $val (@txts) { $total+=$val; }
                   12887:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12888:     return $total;
                   12889: }
                   12890: 
1.675     albertel 12891: sub digest {
                   12892:     my ($data)=@_;
                   12893:     my $digest=&Digest::MD5::md5($data);
                   12894:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12895:     my ($e,$f);
                   12896:     {
                   12897:         use integer;
                   12898:         $e=($a+$b);
                   12899:         $f=($c+$d);
                   12900:         if ($_64bit) {
                   12901:             $e=(($e<<32)>>32);
                   12902:             $f=(($f<<32)>>32);
                   12903:         }
                   12904:     }
                   12905:     if (wantarray) {
                   12906: 	return ($e,$f);
                   12907:     } else {
                   12908: 	my $g;
                   12909: 	{
                   12910: 	    use integer;
                   12911: 	    $g=($e+$f);
                   12912: 	    if ($_64bit) {
                   12913: 		$g=(($g<<32)>>32);
                   12914: 	    }
                   12915: 	}
                   12916: 	return $g;
                   12917:     }
                   12918: }
                   12919: 
1.368     albertel 12920: sub latest_rnd_algorithm_id {
1.675     albertel 12921:     return '64bit5';
1.366     albertel 12922: }
1.32      www      12923: 
1.503     albertel 12924: sub get_rand_alg {
                   12925:     my ($courseid)=@_;
1.790     albertel 12926:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12927:     if ($courseid) {
1.620     albertel 12928: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12929:     }
                   12930:     return &latest_rnd_algorithm_id();
                   12931: }
                   12932: 
1.562     albertel 12933: sub validCODE {
                   12934:     my ($CODE)=@_;
                   12935:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12936:     return 0;
                   12937: }
                   12938: 
1.491     albertel 12939: sub getCODE {
1.620     albertel 12940:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12941:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12942: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12943: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12944: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12945:     }
                   12946:     return undef;
                   12947: }
1.1133    foxr     12948: #
                   12949: #  Determines the random seed for a specific context:
                   12950: #
                   12951: # parameters:
                   12952: #   symb      - in course context the symb for the seed.
                   12953: #   course_id - The course id of the form domain_coursenum.
                   12954: #   domain    - Domain for the user.
                   12955: #   course    - Course for the user.
                   12956: #   cenv      - environment of the course.
                   12957: #
                   12958: # NOTE:
                   12959: #   All parameters are picked out of the environment if missing
                   12960: #   or not defined.
                   12961: #   If a symb cannot be determined the current time is used instead.
                   12962: #
                   12963: #  For a given well defined symb, courside, domain, username,
                   12964: #  and course environment, the seed is reproducible.
                   12965: #
1.31      www      12966: sub rndseed {
1.1133    foxr     12967:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12968:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12969:     if (!defined($symb)) {
1.366     albertel 12970: 	unless ($symb=$wsymb) { return time; }
                   12971:     }
1.1146    foxr     12972:     if (!defined $courseid) { 
                   12973: 	$courseid=$wcourseid; 
                   12974:     }
                   12975:     if (!defined $domain) { $domain=$wdomain; }
                   12976:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12977: 
                   12978:     my $which;
                   12979:     if (defined($cenv->{'rndseed'})) {
                   12980: 	$which = $cenv->{'rndseed'};
                   12981:     } else {
                   12982: 	$which =&get_rand_alg($courseid);
                   12983:     }
1.491     albertel 12984:     if (defined(&getCODE())) {
1.1133    foxr     12985: 
1.675     albertel 12986: 	if ($which eq '64bit5') {
                   12987: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12988: 	} elsif ($which eq '64bit4') {
1.575     albertel 12989: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12990: 	} else {
                   12991: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12992: 	}
1.675     albertel 12993:     } elsif ($which eq '64bit5') {
                   12994: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12995:     } elsif ($which eq '64bit4') {
                   12996: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12997:     } elsif ($which eq '64bit3') {
                   12998: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12999:     } elsif ($which eq '64bit2') {
                   13000: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13001:     } elsif ($which eq '64bit') {
                   13002: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13003:     }
                   13004:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13005: }
                   13006: 
                   13007: sub rndseed_32bit {
                   13008:     my ($symb,$courseid,$domain,$username)=@_;
                   13009:     {
                   13010: 	use integer;
                   13011: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13012: 	my $symbseed=numval($symb) << 22;
                   13013: 	my $namechck=unpack("%32C*",$username) << 17;
                   13014: 	my $nameseed=numval($username) << 12;
                   13015: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13016: 	my $courseseed=unpack("%32C*",$courseid);
                   13017: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13018: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13019: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13020: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13021: 	return $num;
                   13022:     }
                   13023: }
                   13024: 
                   13025: sub rndseed_64bit {
                   13026:     my ($symb,$courseid,$domain,$username)=@_;
                   13027:     {
                   13028: 	use integer;
                   13029: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13030: 	my $symbseed=numval($symb) << 10;
                   13031: 	my $namechck=unpack("%32S*",$username);
                   13032: 	
                   13033: 	my $nameseed=numval($username) << 21;
                   13034: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13035: 	my $courseseed=unpack("%32S*",$courseid);
                   13036: 	
                   13037: 	my $num1=$symbchck+$symbseed+$namechck;
                   13038: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13039: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13040: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13041: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13042: 	return "$num1,$num2";
1.155     albertel 13043:     }
1.366     albertel 13044: }
                   13045: 
1.443     albertel 13046: sub rndseed_64bit2 {
                   13047:     my ($symb,$courseid,$domain,$username)=@_;
                   13048:     {
                   13049: 	use integer;
                   13050: 	# strings need to be an even # of cahracters long, it it is odd the
                   13051:         # last characters gets thrown away
                   13052: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13053: 	my $symbseed=numval($symb) << 10;
                   13054: 	my $namechck=unpack("%32S*",$username.' ');
                   13055: 	
                   13056: 	my $nameseed=numval($username) << 21;
1.501     albertel 13057: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13058: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13059: 	
                   13060: 	my $num1=$symbchck+$symbseed+$namechck;
                   13061: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13062: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13063: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13064: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13065: 	return "$num1,$num2";
                   13066:     }
                   13067: }
                   13068: 
                   13069: sub rndseed_64bit3 {
                   13070:     my ($symb,$courseid,$domain,$username)=@_;
                   13071:     {
                   13072: 	use integer;
                   13073: 	# strings need to be an even # of cahracters long, it it is odd the
                   13074:         # last characters gets thrown away
                   13075: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13076: 	my $symbseed=numval2($symb) << 10;
                   13077: 	my $namechck=unpack("%32S*",$username.' ');
                   13078: 	
                   13079: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13080: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13081: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13082: 	
                   13083: 	my $num1=$symbchck+$symbseed+$namechck;
                   13084: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13085: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13086: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13087: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13088: 	
1.503     albertel 13089: 	return "$num1:$num2";
1.443     albertel 13090:     }
                   13091: }
                   13092: 
1.575     albertel 13093: sub rndseed_64bit4 {
                   13094:     my ($symb,$courseid,$domain,$username)=@_;
                   13095:     {
                   13096: 	use integer;
                   13097: 	# strings need to be an even # of cahracters long, it it is odd the
                   13098:         # last characters gets thrown away
                   13099: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13100: 	my $symbseed=numval3($symb) << 10;
                   13101: 	my $namechck=unpack("%32S*",$username.' ');
                   13102: 	
                   13103: 	my $nameseed=numval3($username) << 21;
                   13104: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13105: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13106: 	
                   13107: 	my $num1=$symbchck+$symbseed+$namechck;
                   13108: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13109: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13110: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13111: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13112: 	
1.575     albertel 13113: 	return "$num1:$num2";
                   13114:     }
                   13115: }
                   13116: 
1.675     albertel 13117: sub rndseed_64bit5 {
                   13118:     my ($symb,$courseid,$domain,$username)=@_;
                   13119:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13120:     return "$num1:$num2";
                   13121: }
                   13122: 
1.366     albertel 13123: sub rndseed_CODE_64bit {
                   13124:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13125:     {
1.366     albertel 13126: 	use integer;
1.443     albertel 13127: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13128: 	my $symbseed=numval2($symb);
1.491     albertel 13129: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13130: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13131: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13132: 	my $num1=$symbseed+$CODEchck;
                   13133: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13134: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13135: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13136: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13137: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13138: 	return "$num1:$num2";
1.366     albertel 13139:     }
                   13140: }
                   13141: 
1.575     albertel 13142: sub rndseed_CODE_64bit4 {
                   13143:     my ($symb,$courseid,$domain,$username)=@_;
                   13144:     {
                   13145: 	use integer;
                   13146: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13147: 	my $symbseed=numval3($symb);
                   13148: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13149: 	my $CODEseed=numval3(&getCODE());
                   13150: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13151: 	my $num1=$symbseed+$CODEchck;
                   13152: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13153: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13154: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13155: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13156: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13157: 	return "$num1:$num2";
                   13158:     }
                   13159: }
                   13160: 
1.675     albertel 13161: sub rndseed_CODE_64bit5 {
                   13162:     my ($symb,$courseid,$domain,$username)=@_;
                   13163:     my $code = &getCODE();
                   13164:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13165:     return "$num1:$num2";
                   13166: }
                   13167: 
1.366     albertel 13168: sub setup_random_from_rndseed {
                   13169:     my ($rndseed)=@_;
1.503     albertel 13170:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13171:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13172:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13173:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13174:         } else {
                   13175:             &Math::Random::random_set_seed($num1,$num2);
                   13176:         }
1.366     albertel 13177:     } else {
                   13178: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13179:     }
1.36      albertel 13180: }
                   13181: 
1.474     albertel 13182: sub latest_receipt_algorithm_id {
1.835     albertel 13183:     return 'receipt3';
1.474     albertel 13184: }
                   13185: 
1.480     www      13186: sub recunique {
                   13187:     my $fucourseid=shift;
                   13188:     my $unique;
1.835     albertel 13189:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13190: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13191: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13192:     } else {
                   13193: 	$unique=$perlvar{'lonReceipt'};
                   13194:     }
                   13195:     return unpack("%32C*",$unique);
                   13196: }
                   13197: 
                   13198: sub recprefix {
                   13199:     my $fucourseid=shift;
                   13200:     my $prefix;
1.835     albertel 13201:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13202: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13203: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13204:     } else {
                   13205: 	$prefix=$perlvar{'lonHostID'};
                   13206:     }
                   13207:     return unpack("%32C*",$prefix);
                   13208: }
                   13209: 
1.76      www      13210: sub ireceipt {
1.474     albertel 13211:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13212: 
                   13213:     my $return =&recprefix($fucourseid).'-';
                   13214: 
                   13215:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13216: 	$env{'request.state'} eq 'construct') {
                   13217: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13218: 	return $return;
                   13219:     }
                   13220: 
1.76      www      13221:     my $cuname=unpack("%32C*",$funame);
                   13222:     my $cudom=unpack("%32C*",$fudom);
                   13223:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13224:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13225:     my $cunique=&recunique($fucourseid);
1.474     albertel 13226:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13227:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13228: 
1.790     albertel 13229: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13230: 			       
                   13231: 	$return.= ($cunique%$cuname+
                   13232: 		   $cunique%$cudom+
                   13233: 		   $cusymb%$cuname+
                   13234: 		   $cusymb%$cudom+
                   13235: 		   $cucourseid%$cuname+
                   13236: 		   $cucourseid%$cudom+
                   13237: 		   $cpart%$cuname+
                   13238: 		   $cpart%$cudom);
                   13239:     } else {
                   13240: 	$return.= ($cunique%$cuname+
                   13241: 		   $cunique%$cudom+
                   13242: 		   $cusymb%$cuname+
                   13243: 		   $cusymb%$cudom+
                   13244: 		   $cucourseid%$cuname+
                   13245: 		   $cucourseid%$cudom);
                   13246:     }
                   13247:     return $return;
1.76      www      13248: }
                   13249: 
                   13250: sub receipt {
1.474     albertel 13251:     my ($part)=@_;
1.790     albertel 13252:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13253:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13254: }
1.260     ng       13255: 
1.790     albertel 13256: sub whichuser {
                   13257:     my ($passedsymb)=@_;
                   13258:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13259:     if (defined($env{'form.grade_symb'})) {
                   13260: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13261: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13262: 	if (!$allowed &&
                   13263: 	    exists($env{'request.course.sec'}) &&
                   13264: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13265: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13266: 			      '/'.$env{'request.course.sec'});
                   13267: 	}
                   13268: 	if ($allowed) {
                   13269: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13270: 	    $courseid=$tmp_courseid;
                   13271: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13272: 	    ($name)=&get_env_multiple('form.grade_username');
                   13273: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13274: 	}
                   13275:     }
                   13276:     if (!$passedsymb) {
                   13277: 	$symb=&symbread();
                   13278:     } else {
                   13279: 	$symb=$passedsymb;
                   13280:     }
                   13281:     $courseid=$env{'request.course.id'};
                   13282:     $domain=$env{'user.domain'};
                   13283:     $name=$env{'user.name'};
                   13284:     if ($name eq 'public' && $domain eq 'public') {
                   13285: 	if (!defined($env{'form.username'})) {
                   13286: 	    $env{'form.username'}.=time.rand(10000000);
                   13287: 	}
                   13288: 	$name.=$env{'form.username'};
                   13289:     }
                   13290:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13291: 
                   13292: }
                   13293: 
1.36      albertel 13294: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13295: # returns either the contents of the file or 
                   13296: # -1 if the file doesn't exist
1.481     raeburn  13297: #
                   13298: # if the target is a file that was uploaded via DOCS, 
                   13299: # a check will be made to see if a current copy exists on the local server,
                   13300: # if it does this will be served, otherwise a copy will be retrieved from
                   13301: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13302: # the local server.   
1.472     albertel 13303: 
1.36      albertel 13304: sub getfile {
1.538     albertel 13305:     my ($file) = @_;
1.609     banghart 13306:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13307:     &repcopy($file);
                   13308:     return &readfile($file);
                   13309: }
                   13310: 
                   13311: sub repcopy_userfile {
                   13312:     my ($file)=@_;
1.1142    raeburn  13313:     my $londocroot = $perlvar{'lonDocRoot'};
                   13314:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13315:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13316:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13317: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13318:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13319:     if (-e "$file") {
1.828     www      13320: # we already have a local copy, check it out
1.538     albertel 13321: 	my @fileinfo = stat($file);
1.828     www      13322: 	my $rtncode;
                   13323: 	my $info;
1.538     albertel 13324: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13325: 	if ($lwpresp ne 'ok') {
1.828     www      13326: # there is no such file anymore, even though we had a local copy
1.482     albertel 13327: 	    if ($rtncode eq '404') {
1.538     albertel 13328: 		unlink($file);
1.482     albertel 13329: 	    }
                   13330: 	    return -1;
                   13331: 	}
                   13332: 	if ($info < $fileinfo[9]) {
1.828     www      13333: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13334: 	    return 'ok';
1.828     www      13335: 	} else {
                   13336: # the file is outdated, get rid of it
                   13337: 	    unlink($file);
1.482     albertel 13338: 	}
1.828     www      13339:     }
                   13340: # one way or the other, at this point, we don't have the file
                   13341: # construct the correct path for the file
                   13342:     my @parts = ($cdom,$cnum); 
                   13343:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13344: 	push @parts, split(/\//,$1);
                   13345:     }
                   13346:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13347:     foreach my $part (@parts) {
                   13348: 	$path .= '/'.$part;
                   13349: 	if (!-e $path) {
                   13350: 	    mkdir($path,0770);
1.482     albertel 13351: 	}
                   13352:     }
1.828     www      13353: # now the path exists for sure
                   13354: # get a user agent
                   13355:     my $transferfile=$file.'.in.transfer';
                   13356: # FIXME: this should flock
                   13357:     if (-e $transferfile) { return 'ok'; }
                   13358:     my $request;
                   13359:     $uri=~s/^\///;
1.980     raeburn  13360:     my $homeserver = &homeserver($cnum,$cdom);
1.1397  ! raeburn  13361:     my $hostname = &hostname($homeserver); 
1.980     raeburn  13362:     my $protocol = $protocol{$homeserver};
                   13363:     $protocol = 'http' if ($protocol ne 'https');
1.1397  ! raeburn  13364:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  13365:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13366: # did it work?
                   13367:     if ($response->is_error()) {
                   13368: 	unlink($transferfile);
                   13369: 	&logthis("Userfile repcopy failed for $uri");
                   13370: 	return -1;
                   13371:     }
                   13372: # worked, rename the transfer file
                   13373:     rename($transferfile,$file);
1.607     raeburn  13374:     return 'ok';
1.481     raeburn  13375: }
                   13376: 
1.517     albertel 13377: sub tokenwrapper {
                   13378:     my $uri=shift;
1.980     raeburn  13379:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13380:     $uri=~s|^/||;
1.620     albertel 13381:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13382:     my $token=$1;
1.552     albertel 13383:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13384:     if ($udom && $uname && $file) {
                   13385: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13386:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13387:         my $homeserver = &homeserver($uname,$udom);
1.1397  ! raeburn  13388:         my $hostname = &hostname($homeserver);
1.980     raeburn  13389:         my $protocol = $protocol{$homeserver};
                   13390:         $protocol = 'http' if ($protocol ne 'https');
1.1397  ! raeburn  13391:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13392:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13393:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13394:     } else {
                   13395:         return '/adm/notfound.html';
                   13396:     }
                   13397: }
                   13398: 
1.828     www      13399: # call with reqtype HEAD: get last modification time
                   13400: # call with reqtype GET: get the file contents
                   13401: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13402: #
1.481     raeburn  13403: sub getuploaded {
                   13404:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13405:     $uri=~s/^\///;
1.980     raeburn  13406:     my $homeserver = &homeserver($cnum,$cdom);
1.1397  ! raeburn  13407:     my $hostname = &hostname($homeserver);
1.980     raeburn  13408:     my $protocol = $protocol{$homeserver};
                   13409:     $protocol = 'http' if ($protocol ne 'https');
1.1397  ! raeburn  13410:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13411:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13412:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13413:     $$rtncode = $response->code;
1.482     albertel 13414:     if (! $response->is_success()) {
                   13415: 	return 'failed';
                   13416:     }      
                   13417:     if ($reqtype eq 'HEAD') {
1.486     www      13418: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13419:     } elsif ($reqtype eq 'GET') {
                   13420: 	$$info = $response->content;
1.472     albertel 13421:     }
1.482     albertel 13422:     return 'ok';
1.36      albertel 13423: }
                   13424: 
1.481     raeburn  13425: sub readfile {
                   13426:     my $file = shift;
                   13427:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13428:     my $fh;
1.1359    raeburn  13429:     open($fh,"<",$file);
1.481     raeburn  13430:     my $a='';
1.800     albertel 13431:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13432:     return $a;
                   13433: }
                   13434: 
1.36      albertel 13435: sub filelocation {
1.590     banghart 13436:     my ($dir,$file) = @_;
                   13437:     my $location;
                   13438:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13439: 
                   13440:     if ($file =~ m-^/adm/-) {
                   13441: 	$file=~s-^/adm/wrapper/-/-;
                   13442: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13443:     }
1.882     albertel 13444: 
1.1139    www      13445:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13446:         $location = $file;
1.609     banghart 13447:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13448:         my ($udom,$uname,$filename)=
1.811     albertel 13449:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13450:         my $home=&homeserver($uname,$udom);
                   13451:         my $is_me=0;
                   13452:         my @ids=&current_machine_ids();
                   13453:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13454:         if ($is_me) {
1.1117    foxr     13455:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13456:         } else {
                   13457:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13458:   	      $udom.'/'.$uname.'/'.$filename;
                   13459:         }
1.882     albertel 13460:     } elsif ($file =~ m-^/adm/-) {
                   13461: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13462:     } else {
                   13463:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13464:         $file=~s:^/(res|priv)/:/:;
                   13465:         my $space=$1;
1.590     banghart 13466:         if ( !( $file =~ m:^/:) ) {
                   13467:             $location = $dir. '/'.$file;
                   13468:         } else {
1.1142    raeburn  13469:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13470:         }
1.59      albertel 13471:     }
1.590     banghart 13472:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13473:     while ($location=~m{/\.\./}) {
                   13474: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13475: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13476: 	} else {
                   13477: 	    $location=~ s{/\.\./}{/}g;
                   13478: 	}
                   13479:     } #remove dir/..
1.590     banghart 13480:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13481:     return $location;
1.46      www      13482: }
1.36      albertel 13483: 
1.46      www      13484: sub hreflocation {
                   13485:     my ($dir,$file)=@_;
1.980     raeburn  13486:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13487: 	$file=filelocation($dir,$file);
1.700     albertel 13488:     } elsif ($file=~m-^/adm/-) {
                   13489: 	$file=~s-^/adm/wrapper/-/-;
                   13490: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13491:     }
                   13492:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13493: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13494:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13495: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13496: 	        {/uploaded/$1/$2/}x;
1.46      www      13497:     }
1.913     albertel 13498:     if ($file=~ m{^/userfiles/}) {
                   13499: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13500:     }
1.462     albertel 13501:     return $file;
1.465     albertel 13502: }
                   13503: 
1.1139    www      13504: 
                   13505: 
                   13506: 
                   13507: 
1.465     albertel 13508: sub current_machine_domains {
1.853     albertel 13509:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13510: }
                   13511: 
                   13512: sub machine_domains {
                   13513:     my ($hostname) = @_;
1.465     albertel 13514:     my @domains;
1.838     albertel 13515:     my %hostname = &all_hostnames();
1.465     albertel 13516:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13517: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13518: 	if ($hostname eq $name) {
1.844     albertel 13519: 	    push(@domains,&host_domain($id));
1.465     albertel 13520: 	}
                   13521:     }
                   13522:     return @domains;
                   13523: }
                   13524: 
                   13525: sub current_machine_ids {
1.853     albertel 13526:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13527: }
                   13528: 
                   13529: sub machine_ids {
                   13530:     my ($hostname) = @_;
                   13531:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13532:     my @ids;
1.888     albertel 13533:     my %name_to_host = &all_names();
1.889     albertel 13534:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13535: 	return @{ $name_to_host{$hostname} };
                   13536:     }
                   13537:     return;
1.31      www      13538: }
                   13539: 
1.824     raeburn  13540: sub additional_machine_domains {
                   13541:     my @domains;
1.1359    raeburn  13542:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13543:     while( my $line = <$fh>) {
                   13544:         $line =~ s/\s//g;
                   13545:         push(@domains,$line);
                   13546:     }
                   13547:     return @domains;
                   13548: }
                   13549: 
                   13550: sub default_login_domain {
                   13551:     my $domain = $perlvar{'lonDefDomain'};
                   13552:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13553:     foreach my $posdom (&current_machine_domains(),
                   13554:                         &additional_machine_domains()) {
                   13555:         if (lc($posdom) eq lc($testdomain)) {
                   13556:             $domain=$posdom;
                   13557:             last;
                   13558:         }
                   13559:     }
                   13560:     return $domain;
                   13561: }
                   13562: 
1.31      www      13563: # ------------------------------------------------------------- Declutters URLs
                   13564: 
                   13565: sub declutter {
                   13566:     my $thisfn=shift;
1.569     albertel 13567:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13568:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13569:         $thisfn=~s{^/home/httpd/html}{};
                   13570:     }
1.31      www      13571:     $thisfn=~s/^\///;
1.697     albertel 13572:     $thisfn=~s|^adm/wrapper/||;
                   13573:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13574:     $thisfn=~s/^res\///;
1.1172    bisitz   13575:     $thisfn=~s/^priv\///;
1.1032    raeburn  13576:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13577:         $thisfn=~s/\?.+$//;
                   13578:     }
1.268     www      13579:     return $thisfn;
                   13580: }
                   13581: 
                   13582: # ------------------------------------------------------------- Clutter up URLs
                   13583: 
                   13584: sub clutter {
                   13585:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13586:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13587: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13588:        $thisfn='/res'.$thisfn; 
                   13589:     }
1.1031    raeburn  13590:     if ($thisfn !~m|^/adm|) {
                   13591: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13592: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13593: 	} else {
                   13594: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13595: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13596: 	    if ($embstyle eq 'ssi'
                   13597: 		|| ($embstyle eq 'hdn')
                   13598: 		|| ($embstyle eq 'rat')
                   13599: 		|| ($embstyle eq 'prv')
                   13600: 		|| ($embstyle eq 'ign')) {
                   13601: 		#do nothing with these
                   13602: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13603: 		|| ($embstyle eq 'emb')
                   13604: 		|| ($embstyle eq 'wrp')) {
                   13605: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13606: 	    } elsif ($embstyle eq 'unk'
                   13607: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13608: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13609: 	    } else {
1.718     www      13610: #		&logthis("Got a blank emb style");
1.695     albertel 13611: 	    }
1.694     albertel 13612: 	}
1.1343    raeburn  13613:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13614:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13615:     }
1.31      www      13616:     return $thisfn;
1.12      www      13617: }
                   13618: 
1.787     albertel 13619: sub clutter_with_no_wrapper {
                   13620:     my $uri = &clutter(shift);
                   13621:     if ($uri =~ m-^/adm/-) {
                   13622: 	$uri =~ s-^/adm/wrapper/-/-;
                   13623: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13624:     }
                   13625:     return $uri;
                   13626: }
                   13627: 
1.557     albertel 13628: sub freeze_escape {
                   13629:     my ($value)=@_;
                   13630:     if (ref($value)) {
                   13631: 	$value=&nfreeze($value);
                   13632: 	return '__FROZEN__'.&escape($value);
                   13633:     }
                   13634:     return &escape($value);
                   13635: }
                   13636: 
1.11      www      13637: 
1.557     albertel 13638: sub thaw_unescape {
                   13639:     my ($value)=@_;
                   13640:     if ($value =~ /^__FROZEN__/) {
                   13641: 	substr($value,0,10,undef);
                   13642: 	$value=&unescape($value);
                   13643: 	return &thaw($value);
                   13644:     }
                   13645:     return &unescape($value);
                   13646: }
                   13647: 
1.436     albertel 13648: sub correct_line_ends {
                   13649:     my ($result)=@_;
                   13650:     $$result =~s/\r\n/\n/mg;
                   13651:     $$result =~s/\r/\n/mg;
1.415     albertel 13652: }
1.1       albertel 13653: # ================================================================ Main Program
                   13654: 
1.184     www      13655: sub goodbye {
1.204     albertel 13656:    &logthis("Starting Shut down");
1.443     albertel 13657: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13658:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13659: #converted
1.599     albertel 13660: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13661:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13662: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13663: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13664: #1.1 only
1.870     albertel 13665: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13666: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13667: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13668: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13669:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13670:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13671:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13672:    &flushcourselogs();
                   13673:    &logthis("Shutting down");
                   13674: }
                   13675: 
1.852     albertel 13676: sub get_dns {
1.1210    raeburn  13677:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13678:     if (!$ignore_cache) {
                   13679: 	my ($content,$cached)=
                   13680: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13681: 	if ($cached) {
1.1210    raeburn  13682: 	    &$func($content,$hashref);
1.869     albertel 13683: 	    return;
                   13684: 	}
                   13685:     }
                   13686: 
                   13687:     my %alldns;
1.1379    raeburn  13688:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13689:         foreach my $dns (<$config>) {
                   13690: 	    next if ($dns !~ /^\^(\S*)/x);
                   13691:             my $line = $1;
                   13692:             my ($host,$protocol) = split(/:/,$line);
                   13693:             if ($protocol ne 'https') {
                   13694:                 $protocol = 'http';
                   13695:             }
                   13696: 	    $alldns{$host} = $protocol;
1.979     raeburn  13697:         }
1.1379    raeburn  13698:         close($config);
1.869     albertel 13699:     }
                   13700:     while (%alldns) {
1.1263    raeburn  13701: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13702: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13703:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13704:         delete($alldns{$dns});
1.852     albertel 13705: 	next if ($response->is_error());
1.1379    raeburn  13706:         if ($url eq '/adm/dns/loncapaCRL') {
                   13707:             return &$func($response);
                   13708:         } else {
                   13709: 	    my @content = split("\n",$response->content);
                   13710: 	    unless ($nocache) {
                   13711: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   13712: 	    }
                   13713: 	    &$func(\@content,$hashref);
                   13714:             return;
                   13715:         }
                   13716:     }
                   13717:     my $which = (split('/',$url,4))[3];
                   13718:     if ($which eq 'loncapaCRL') {
                   13719:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   13720:         if (-e $diskfile) {
                   13721:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   13722:         } else {
                   13723:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   13724:         }
                   13725:     } else {
                   13726:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13727:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13728:             my @content = <$config>;
                   13729:             close($config);
                   13730:             &$func(\@content,$hashref);
                   13731:         }
1.852     albertel 13732:     }
1.1210    raeburn  13733:     return;
                   13734: }
                   13735: 
                   13736: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13737: sub parse_dns_checksums_tab {
1.1210    raeburn  13738:     my ($lines,$hashref) = @_;
1.1264    raeburn  13739:     my $lonhost = $perlvar{'lonHostID'};
                   13740:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13741:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13742:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13743:     my $webconfdir = '/etc/httpd/conf';
                   13744:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13745:         $webconfdir = '/etc/apache2';
                   13746:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13747:         if ($1 >= 10) {
                   13748:             $webconfdir = '/etc/apache2';
                   13749:         }
                   13750:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13751:         if ($1 >= 10.0) {
                   13752:             $webconfdir = '/etc/apache2';
                   13753:         }
                   13754:     }
1.1210    raeburn  13755:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13756:     my (%chksum,%revnum);
                   13757:     if (ref($lines) eq 'ARRAY') {
                   13758:         chomp(@{$lines});
1.1238    raeburn  13759:         my $version = shift(@{$lines});
                   13760:         if ($version eq $release) {  
1.1210    raeburn  13761:             foreach my $line (@{$lines}) {
1.1238    raeburn  13762:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13763:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13764:                     if ($webconfdir eq '/etc/apache2') {
                   13765:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13766:                     }
                   13767:                 }
1.1238    raeburn  13768:                 $chksum{$file} = $shasum;
                   13769:                 $revnum{$file} = $version;
1.1210    raeburn  13770:             }
                   13771:             if (ref($hashref) eq 'HASH') {
                   13772:                 %{$hashref} = (
                   13773:                                 sums     => \%chksum,
                   13774:                                 versions => \%revnum,
                   13775:                               );
                   13776:             }
                   13777:         }
                   13778:     }
1.869     albertel 13779:     return;
1.852     albertel 13780: }
1.1210    raeburn  13781: 
                   13782: sub fetch_dns_checksums {
1.1238    raeburn  13783:     my %checksums;
                   13784:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13785:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13786:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13787:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13788:              \%checksums);
1.1210    raeburn  13789:     return \%checksums;
                   13790: }
                   13791: 
1.1379    raeburn  13792: sub fetch_crl_pemfile {
                   13793:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   13794: }
                   13795: 
                   13796: sub save_crl_pem {
                   13797:     my ($response) = @_;
1.1380    raeburn  13798:     my ($msg,$hadchanges);
1.1379    raeburn  13799:     if (ref($response)) {
                   13800:         my $now = time;
                   13801:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   13802:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   13803:         if (open(my $fh,'>',"$tmpcrl")) {
                   13804:             print $fh $response->content;
                   13805:             close($fh);
                   13806:             if (-e $lonca) {
                   13807:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   13808:                     my $check = <PIPE>;
                   13809:                     close(PIPE);
                   13810:                     chomp($check);
                   13811:                     if ($check eq 'verify OK') {
                   13812:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  13813:                         my $backup;
1.1379    raeburn  13814:                         if (-e $dest) {
1.1380    raeburn  13815:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   13816:                                 $backup = 'ok';
                   13817:                             }
1.1379    raeburn  13818:                         }
                   13819:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   13820:                             $msg = 'ok';
1.1380    raeburn  13821:                             if ($backup) {
                   13822:                                 my (%oldnums,%newnums);
                   13823:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   13824:                                     while (<PIPE>) {
                   13825:                                         $oldnums{(split(/:/))[1]} = 1;
                   13826:                                     }
                   13827:                                     close(PIPE);
                   13828:                                 }
                   13829:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   13830:                                     while(<PIPE>) {
                   13831:                                         $newnums{(split(/:/))[1]} = 1;
                   13832:                                     }
                   13833:                                     close(PIPE);
                   13834:                                 }
                   13835:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   13836:                                     unless (exists($oldnums{$key})) {
                   13837:                                         $hadchanges = 1;
                   13838:                                         last;
                   13839:                                     }
                   13840:                                 }
                   13841:                                 unless ($hadchanges) {
                   13842:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   13843:                                         unless (exists($newnums{$key})) {
                   13844:                                             $hadchanges = 1;
                   13845:                                             last;
                   13846:                                         }
                   13847:                                     }
                   13848:                                 }
                   13849:                             }
1.1379    raeburn  13850:                         }
                   13851:                     } else {
                   13852:                         unlink($tmpcrl);
                   13853:                     }
                   13854:                 } else {
                   13855:                     unlink($tmpcrl);
                   13856:                 }
                   13857:             } else {
                   13858:                 unlink($tmpcrl);
                   13859:             }
                   13860:         }
                   13861:     }
1.1380    raeburn  13862:     return ($msg,$hadchanges);
1.1379    raeburn  13863: }
                   13864: 
1.327     albertel 13865: # ------------------------------------------------------------ Read domain file
                   13866: {
1.852     albertel 13867:     my $loaded;
1.846     albertel 13868:     my %domain;
                   13869: 
1.852     albertel 13870:     sub parse_domain_tab {
                   13871: 	my ($lines) = @_;
                   13872: 	foreach my $line (@$lines) {
                   13873: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13874: 
1.846     albertel 13875: 	    chomp($line);
1.852     albertel 13876: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13877: 	    my %this_domain;
                   13878: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13879: 			       'lang_def', 'city', 'longi', 'lati',
                   13880: 			       'primary') {
                   13881: 		$this_domain{$field} = shift(@elements);
                   13882: 	    }
                   13883: 	    $domain{$name} = \%this_domain;
1.852     albertel 13884: 	}
                   13885:     }
1.864     albertel 13886: 
                   13887:     sub reset_domain_info {
                   13888: 	undef($loaded);
                   13889: 	undef(%domain);
                   13890:     }
                   13891: 
1.852     albertel 13892:     sub load_domain_tab {
1.1293    raeburn  13893: 	my ($ignore_cache,$nocache) = @_;
                   13894: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13895: 	my $fh;
1.1359    raeburn  13896: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13897: 	    my @lines = <$fh>;
                   13898: 	    &parse_domain_tab(\@lines);
1.448     albertel 13899: 	}
1.852     albertel 13900: 	close($fh);
                   13901: 	$loaded = 1;
1.327     albertel 13902:     }
1.846     albertel 13903: 
                   13904:     sub domain {
1.852     albertel 13905: 	&load_domain_tab() if (!$loaded);
                   13906: 
1.846     albertel 13907: 	my ($name,$what) = @_;
                   13908: 	return if ( !exists($domain{$name}) );
                   13909: 
                   13910: 	if (!$what) {
                   13911: 	    return $domain{$name}{'description'};
                   13912: 	}
                   13913: 	return $domain{$name}{$what};
                   13914:     }
1.974     raeburn  13915: 
                   13916:     sub domain_info {
                   13917:         &load_domain_tab() if (!$loaded);
                   13918:         return %domain;
                   13919:     }
                   13920: 
1.327     albertel 13921: }
                   13922: 
                   13923: 
1.1       albertel 13924: # ------------------------------------------------------------- Read hosts file
                   13925: {
1.838     albertel 13926:     my %hostname;
1.844     albertel 13927:     my %hostdom;
1.845     albertel 13928:     my %libserv;
1.852     albertel 13929:     my $loaded;
1.888     albertel 13930:     my %name_to_host;
1.1074    raeburn  13931:     my %internetdom;
1.1107    raeburn  13932:     my %LC_dns_serv;
1.852     albertel 13933: 
                   13934:     sub parse_hosts_tab {
                   13935: 	my ($file) = @_;
                   13936: 	foreach my $configline (@$file) {
                   13937: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13938:             chomp($configline);
                   13939: 	    if ($configline =~ /^\^/) {
                   13940:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13941:                     $LC_dns_serv{$1} = 1;
                   13942:                 }
                   13943:                 next;
                   13944:             }
1.1074    raeburn  13945: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13946: 	    $name=~s/\s//g;
                   13947: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13948:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13949:                     my $curr = $hostname{$id};
                   13950:                     my $skip;
                   13951:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13952:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13953:                             $skip = 1;
                   13954:                         } else {
                   13955:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13956:                         }
                   13957:                     }
                   13958:                     unless ($skip) {
                   13959:                         push(@{$name_to_host{$name}},$id);
                   13960:                     }
                   13961:                 } else {
                   13962:                     push(@{$name_to_host{$name}},$id);
                   13963:                 }
1.852     albertel 13964: 		$hostname{$id}=$name;
                   13965: 		$hostdom{$id}=$domain;
                   13966: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13967:                 if (defined($protocol)) {
                   13968:                     if ($protocol eq 'https') {
                   13969:                         $protocol{$id} = $protocol;
                   13970:                     } else {
                   13971:                         $protocol{$id} = 'http'; 
                   13972:                     }
1.968     raeburn  13973:                 } else {
1.969     raeburn  13974:                     $protocol{$id} = 'http';
1.968     raeburn  13975:                 }
1.1074    raeburn  13976:                 if (defined($intdom)) {
                   13977:                     $internetdom{$id} = $intdom;
                   13978:                 }
1.852     albertel 13979: 	    }
                   13980: 	}
                   13981:     }
1.864     albertel 13982:     
                   13983:     sub reset_hosts_info {
1.897     albertel 13984: 	&purge_remembered();
1.864     albertel 13985: 	&reset_domain_info();
                   13986: 	&reset_hosts_ip_info();
1.1339    raeburn  13987:         undef(%internetdom);
1.892     albertel 13988: 	undef(%name_to_host);
1.864     albertel 13989: 	undef(%hostname);
                   13990: 	undef(%hostdom);
                   13991: 	undef(%libserv);
                   13992: 	undef($loaded);
                   13993:     }
1.1       albertel 13994: 
1.852     albertel 13995:     sub load_hosts_tab {
1.1293    raeburn  13996: 	my ($ignore_cache,$nocache) = @_;
                   13997: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13998: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13999: 	my @config = <$config>;
                   14000: 	&parse_hosts_tab(\@config);
                   14001: 	close($config);
                   14002: 	$loaded=1;
1.1       albertel 14003:     }
1.852     albertel 14004: 
1.838     albertel 14005:     sub hostname {
1.852     albertel 14006: 	&load_hosts_tab() if (!$loaded);
                   14007: 
1.838     albertel 14008: 	my ($lonid) = @_;
                   14009: 	return $hostname{$lonid};
                   14010:     }
1.845     albertel 14011: 
1.838     albertel 14012:     sub all_hostnames {
1.852     albertel 14013: 	&load_hosts_tab() if (!$loaded);
                   14014: 
1.838     albertel 14015: 	return %hostname;
                   14016:     }
1.845     albertel 14017: 
1.888     albertel 14018:     sub all_names {
1.1293    raeburn  14019:         my ($ignore_cache,$nocache) = @_;
                   14020: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14021: 
                   14022: 	return %name_to_host;
                   14023:     }
                   14024: 
1.974     raeburn  14025:     sub all_host_domain {
                   14026:         &load_hosts_tab() if (!$loaded);
                   14027:         return %hostdom;
                   14028:     }
                   14029: 
1.1339    raeburn  14030:     sub all_host_intdom {
                   14031:         &load_hosts_tab() if (!$loaded);
                   14032:         return %internetdom;
                   14033:     }
                   14034: 
1.845     albertel 14035:     sub is_library {
1.852     albertel 14036: 	&load_hosts_tab() if (!$loaded);
                   14037: 
1.845     albertel 14038: 	return exists($libserv{$_[0]});
                   14039:     }
                   14040: 
                   14041:     sub all_library {
1.852     albertel 14042: 	&load_hosts_tab() if (!$loaded);
                   14043: 
1.845     albertel 14044: 	return %libserv;
                   14045:     }
                   14046: 
1.1062    droeschl 14047:     sub unique_library {
                   14048: 	#2x reverse removes all hostnames that appear more than once
                   14049:         my %unique = reverse &all_library();
                   14050:         return reverse %unique;
                   14051:     }
                   14052: 
1.841     albertel 14053:     sub get_servers {
1.852     albertel 14054: 	&load_hosts_tab() if (!$loaded);
                   14055: 
1.841     albertel 14056: 	my ($domain,$type) = @_;
                   14057: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14058: 	                                          : %hostname;
                   14059: 	my %result;
1.842     albertel 14060: 	if (ref($domain) eq 'ARRAY') {
                   14061: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14062: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14063: 		    $result{$host} = $hostname;
                   14064: 		}
                   14065: 	    }
                   14066: 	} else {
                   14067: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14068: 		if ($hostdom{$host} eq $domain) {
                   14069: 		    $result{$host} = $hostname;
                   14070: 		}
1.841     albertel 14071: 	    }
                   14072: 	}
                   14073: 	return %result;
                   14074:     }
1.845     albertel 14075: 
1.1062    droeschl 14076:     sub get_unique_servers {
                   14077:         my %unique = reverse &get_servers(@_);
                   14078: 	return reverse %unique;
                   14079:     }
                   14080: 
1.844     albertel 14081:     sub host_domain {
1.852     albertel 14082: 	&load_hosts_tab() if (!$loaded);
                   14083: 
1.844     albertel 14084: 	my ($lonid) = @_;
                   14085: 	return $hostdom{$lonid};
                   14086:     }
                   14087: 
1.841     albertel 14088:     sub all_domains {
1.852     albertel 14089: 	&load_hosts_tab() if (!$loaded);
                   14090: 
1.841     albertel 14091: 	my %seen;
                   14092: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14093: 	return @uniq;
                   14094:     }
1.1074    raeburn  14095: 
                   14096:     sub internet_dom {
                   14097:         &load_hosts_tab() if (!$loaded);
                   14098: 
                   14099:         my ($lonid) = @_;
                   14100:         return $internetdom{$lonid};
                   14101:     }
1.1107    raeburn  14102: 
                   14103:     sub is_LC_dns {
                   14104:         &load_hosts_tab() if (!$loaded);
                   14105: 
                   14106:         my ($hostname) = @_;
                   14107:         return exists($LC_dns_serv{$hostname});
                   14108:     }
                   14109: 
1.1       albertel 14110: }
                   14111: 
1.847     albertel 14112: { 
                   14113:     my %iphost;
1.856     albertel 14114:     my %name_to_ip;
                   14115:     my %lonid_to_ip;
1.869     albertel 14116: 
1.847     albertel 14117:     sub get_hosts_from_ip {
                   14118: 	my ($ip) = @_;
                   14119: 	my %iphosts = &get_iphost();
                   14120: 	if (ref($iphosts{$ip})) {
                   14121: 	    return @{$iphosts{$ip}};
                   14122: 	}
                   14123: 	return;
1.839     albertel 14124:     }
1.864     albertel 14125:     
                   14126:     sub reset_hosts_ip_info {
                   14127: 	undef(%iphost);
                   14128: 	undef(%name_to_ip);
                   14129: 	undef(%lonid_to_ip);
                   14130:     }
1.856     albertel 14131: 
                   14132:     sub get_host_ip {
                   14133: 	my ($lonid) = @_;
                   14134: 	if (exists($lonid_to_ip{$lonid})) {
                   14135: 	    return $lonid_to_ip{$lonid};
                   14136: 	}
                   14137: 	my $name=&hostname($lonid);
                   14138:    	my $ip = gethostbyname($name);
                   14139: 	return if (!$ip || length($ip) ne 4);
                   14140: 	$ip=inet_ntoa($ip);
                   14141: 	$name_to_ip{$name}   = $ip;
                   14142: 	$lonid_to_ip{$lonid} = $ip;
                   14143: 	return $ip;
                   14144:     }
1.847     albertel 14145:     
                   14146:     sub get_iphost {
1.1293    raeburn  14147: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14148: 
1.869     albertel 14149: 	if (!$ignore_cache) {
                   14150: 	    if (%iphost) {
                   14151: 		return %iphost;
                   14152: 	    }
                   14153: 	    my ($ip_info,$cached)=
                   14154: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14155: 	    if ($cached) {
                   14156: 		%iphost      = %{$ip_info->[0]};
                   14157: 		%name_to_ip  = %{$ip_info->[1]};
                   14158: 		%lonid_to_ip = %{$ip_info->[2]};
                   14159: 		return %iphost;
                   14160: 	    }
                   14161: 	}
1.894     albertel 14162: 
                   14163: 	# get yesterday's info for fallback
                   14164: 	my %old_name_to_ip;
                   14165: 	my ($ip_info,$cached)=
                   14166: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14167: 	if ($cached) {
                   14168: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14169: 	}
                   14170: 
1.1293    raeburn  14171: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14172: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14173: 	    my $ip;
                   14174: 	    if (!exists($name_to_ip{$name})) {
                   14175: 		$ip = gethostbyname($name);
                   14176: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14177: 		    if (defined($old_name_to_ip{$name})) {
                   14178: 			$ip = $old_name_to_ip{$name};
                   14179: 			&logthis("Can't find $name defaulting to old $ip");
                   14180: 		    } else {
                   14181: 			&logthis("Name $name no IP found");
                   14182: 			next;
                   14183: 		    }
                   14184: 		} else {
                   14185: 		    $ip=inet_ntoa($ip);
1.847     albertel 14186: 		}
                   14187: 		$name_to_ip{$name} = $ip;
                   14188: 	    } else {
                   14189: 		$ip = $name_to_ip{$name};
1.653     albertel 14190: 	    }
1.888     albertel 14191: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14192: 		$lonid_to_ip{$id} = $ip;
                   14193: 	    }
                   14194: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14195: 	}
1.1293    raeburn  14196:         unless ($nocache) {
                   14197: 	    &do_cache_new('iphost','iphost',
                   14198: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14199: 		          48*60*60);
                   14200:         }
1.869     albertel 14201: 
1.847     albertel 14202: 	return %iphost;
1.598     albertel 14203:     }
                   14204: 
1.992     raeburn  14205:     #
                   14206:     #  Given a DNS returns the loncapa host name for that DNS 
                   14207:     # 
                   14208:     sub host_from_dns {
                   14209:         my ($dns) = @_;
                   14210:         my @hosts;
                   14211:         my $ip;
                   14212: 
1.993     raeburn  14213:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14214:             $ip = $name_to_ip{$dns};
                   14215:         }
                   14216:         if (!$ip) {
                   14217:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14218:             if (length($ip) == 4) { 
                   14219: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14220:             }
                   14221:         }
                   14222:         if ($ip) {
                   14223: 	    @hosts = get_hosts_from_ip($ip);
                   14224: 	    return $hosts[0];
                   14225:         }
                   14226:         return undef;
1.986     foxr     14227:     }
1.992     raeburn  14228: 
1.1074    raeburn  14229:     sub get_internet_names {
                   14230:         my ($lonid) = @_;
                   14231:         return if ($lonid eq '');
                   14232:         my ($idnref,$cached)=
                   14233:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14234:         if ($cached) {
                   14235:             return $idnref;
                   14236:         }
                   14237:         my $ip = &get_host_ip($lonid);
                   14238:         my @hosts = &get_hosts_from_ip($ip);
                   14239:         my %iphost = &get_iphost();
                   14240:         my (@idns,%seen);
                   14241:         foreach my $id (@hosts) {
                   14242:             my $dom = &host_domain($id);
                   14243:             my $prim_id = &domain($dom,'primary');
                   14244:             my $prim_ip = &get_host_ip($prim_id);
                   14245:             next if ($seen{$prim_ip});
                   14246:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14247:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14248:                     my $intdom = &internet_dom($id);
                   14249:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14250:                         push(@idns,$intdom);
                   14251:                     }
                   14252:                 }
                   14253:             }
                   14254:             $seen{$prim_ip} = 1;
                   14255:         }
1.1219    raeburn  14256:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14257:     }
                   14258: 
1.986     foxr     14259: }
                   14260: 
1.1079    raeburn  14261: sub all_loncaparevs {
1.1249    raeburn  14262:     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  14263: }
                   14264: 
1.1227    raeburn  14265: # ---------------------------------------------------------- Read loncaparev table
                   14266: {
                   14267:     sub load_loncaparevs { 
                   14268:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14269:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14270:                 while (my $configline=<$config>) {
                   14271:                     chomp($configline);
                   14272:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14273:                     $loncaparevs{$hostid}=$loncaparev;
                   14274:                 }
                   14275:                 close($config);
                   14276:             }
                   14277:         }
                   14278:     }
                   14279: }
                   14280: 
                   14281: # ---------------------------------------------------------- Read serverhostID table
                   14282: {
                   14283:     sub load_serverhomeIDs {
                   14284:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14285:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14286:                 while (my $configline=<$config>) {
                   14287:                     chomp($configline);
                   14288:                     my ($name,$id)=split(/:/,$configline);
                   14289:                     $serverhomeIDs{$name}=$id;
                   14290:                 }
                   14291:                 close($config);
                   14292:             }
                   14293:         }
                   14294:     }
                   14295: }
                   14296: 
                   14297: 
1.862     albertel 14298: BEGIN {
                   14299: 
                   14300: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14301:     unless ($readit) {
                   14302: {
                   14303:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14304:     %perlvar = (%perlvar,%{$configvars});
                   14305: }
                   14306: 
                   14307: 
1.1       albertel 14308: # ------------------------------------------------------ Read spare server file
                   14309: {
1.1359    raeburn  14310:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14311: 
                   14312:     while (my $configline=<$config>) {
                   14313:        chomp($configline);
1.284     matthew  14314:        if ($configline) {
1.784     albertel 14315: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14316: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14317: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14318:        }
                   14319:     }
1.448     albertel 14320:     close($config);
1.1       albertel 14321: }
1.11      www      14322: # ------------------------------------------------------------ Read permissions
                   14323: {
1.1359    raeburn  14324:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14325: 
                   14326:     while (my $configline=<$config>) {
1.448     albertel 14327: 	chomp($configline);
                   14328: 	if ($configline) {
                   14329: 	    my ($role,$perm)=split(/ /,$configline);
                   14330: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14331: 	}
1.11      www      14332:     }
1.448     albertel 14333:     close($config);
1.11      www      14334: }
                   14335: 
                   14336: # -------------------------------------------- Read plain texts for permissions
                   14337: {
1.1359    raeburn  14338:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14339: 
                   14340:     while (my $configline=<$config>) {
1.448     albertel 14341: 	chomp($configline);
                   14342: 	if ($configline) {
1.742     raeburn  14343: 	    my ($short,@plain)=split(/:/,$configline);
                   14344:             %{$prp{$short}} = ();
                   14345: 	    if (@plain > 0) {
                   14346:                 $prp{$short}{'std'} = $plain[0];
                   14347:                 for (my $i=1; $i<@plain; $i++) {
                   14348:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14349:                 }
                   14350:             }
1.448     albertel 14351: 	}
1.135     www      14352:     }
1.448     albertel 14353:     close($config);
1.135     www      14354: }
                   14355: 
                   14356: # ---------------------------------------------------------- Read package table
                   14357: {
1.1359    raeburn  14358:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14359: 
                   14360:     while (my $configline=<$config>) {
1.483     albertel 14361: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14362: 	chomp($configline);
                   14363: 	my ($short,$plain)=split(/:/,$configline);
                   14364: 	my ($pack,$name)=split(/\&/,$short);
                   14365: 	if ($plain ne '') {
                   14366: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14367: 	    $packagetab{$short}=$plain; 
                   14368: 	}
1.11      www      14369:     }
1.448     albertel 14370:     close($config);
1.329     matthew  14371: }
                   14372: 
1.1073    raeburn  14373: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14374: 
                   14375: &load_loncaparevs();
1.1073    raeburn  14376: 
1.1074    raeburn  14377: # ---------------------------------------------------------- Read serverhostID table
                   14378: 
1.1227    raeburn  14379: &load_serverhomeIDs();
                   14380: 
                   14381: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14382: {
                   14383:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14384:     if (-e $file) {
                   14385:         my $parser = HTML::LCParser->new($file);
                   14386:         while (my $token = $parser->get_token()) {
                   14387:             if ($token->[0] eq 'S') {
                   14388:                 my $item = $token->[1];
                   14389:                 my $name = $token->[2]{'name'};
                   14390:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14391:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14392:                 my $namematch = $token->[2]{'namematch'};
                   14393:                 if ($item eq 'parameter') {
                   14394:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14395:                         my $release = $parser->get_text();
                   14396:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14397:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14398:                     }
                   14399:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14400:                     my $release = $parser->get_text();
                   14401:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14402:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14403:                 }
                   14404:             }
                   14405:         }
                   14406:     }
1.1073    raeburn  14407: }
                   14408: 
1.1138    raeburn  14409: # ---------------------------------------------------------- Read managers table
                   14410: {
                   14411:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14412:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14413:             while (my $configline=<$config>) {
                   14414:                 chomp($configline);
                   14415:                 next if ($configline =~ /^\#/);
                   14416:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14417:                     $managerstab{$configline} = 1;
                   14418:                 }
                   14419:             }
                   14420:             close($config);
                   14421:         }
                   14422:     }
                   14423: }
                   14424: 
1.329     matthew  14425: # ------------- set up temporary directory
                   14426: {
1.1117    foxr     14427:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14428: 
1.11      www      14429: }
                   14430: 
1.794     albertel 14431: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14432: 				'compress_threshold'=> 20_000,
                   14433:  			        });
1.185     www      14434: 
1.281     www      14435: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14436: $dumpcount=0;
1.958     www      14437: $locknum=0;
1.22      www      14438: 
1.163     harris41 14439: &logtouch();
1.672     albertel 14440: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14441: $readit=1;
1.564     albertel 14442:     {
                   14443: 	use integer;
                   14444: 	my $test=(2**32)+1;
1.568     albertel 14445: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14446: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14447:     }
1.195     www      14448: }
1.1       albertel 14449: }
1.179     www      14450: 
1.1       albertel 14451: 1;
1.191     harris41 14452: __END__
                   14453: 
1.243     albertel 14454: =pod
                   14455: 
1.191     harris41 14456: =head1 NAME
                   14457: 
1.243     albertel 14458: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14459: 
                   14460: =head1 SYNOPSIS
                   14461: 
1.243     albertel 14462: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14463: 
                   14464:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14465: 
1.243     albertel 14466: Common parameters:
                   14467: 
                   14468: =over 4
                   14469: 
                   14470: =item *
                   14471: 
                   14472: $uname : an internal username (if $cname expecting a course Id specifically)
                   14473: 
                   14474: =item *
                   14475: 
                   14476: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14477: 
                   14478: =item *
                   14479: 
                   14480: $symb : a resource instance identifier
                   14481: 
                   14482: =item *
                   14483: 
                   14484: $namespace : the name of a .db file that contains the data needed or
                   14485: being set.
                   14486: 
                   14487: =back
                   14488: 
1.394     bowersj2 14489: =head1 OVERVIEW
1.191     harris41 14490: 
1.394     bowersj2 14491: lonnet provides subroutines which interact with the
                   14492: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14493: about classes, users, and resources.
1.243     albertel 14494: 
                   14495: For many of these objects you can also use this to store data about
                   14496: them or modify them in various ways.
1.191     harris41 14497: 
1.394     bowersj2 14498: =head2 Symbs
1.191     harris41 14499: 
1.394     bowersj2 14500: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14501: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14502: map, the resource number of the resource in the map, and the URL of
                   14503: the resource itself. The latter is somewhat redundant, but might help
                   14504: if maps change.
                   14505: 
                   14506: An example is
                   14507: 
                   14508:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14509: 
                   14510: The respective map entry is
                   14511: 
                   14512:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14513:   title="Problem 2">
                   14514:  </resource>
                   14515: 
                   14516: Symbs are used by the random number generator, as well as to store and
                   14517: restore data specific to a certain instance of for example a problem.
                   14518: 
                   14519: =head2 Storing And Retrieving Data
                   14520: 
                   14521: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14522: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14523: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14524: is is the non-critical message twin of cstore. These functions are for
                   14525: handlers to store a perl hash to a user's permanent data space in an
                   14526: easy manner, and to retrieve it again on another call. It is expected
                   14527: that a handler would use this once at the beginning to retrieve data,
                   14528: and then again once at the end to send only the new data back.
                   14529: 
                   14530: The data is stored in the user's data directory on the user's
                   14531: homeserver under the ID of the course.
                   14532: 
                   14533: The hash that is returned by restore will have all of the previous
                   14534: value for all of the elements of the hash.
                   14535: 
                   14536: Example:
                   14537: 
                   14538:  #creating a hash
                   14539:  my %hash;
                   14540:  $hash{'foo'}='bar';
                   14541: 
                   14542:  #storing it
                   14543:  &Apache::lonnet::cstore(\%hash);
                   14544: 
                   14545:  #changing a value
                   14546:  $hash{'foo'}='notbar';
                   14547: 
                   14548:  #adding a new value
                   14549:  $hash{'bar'}='foo';
                   14550:  &Apache::lonnet::cstore(\%hash);
                   14551: 
                   14552:  #retrieving the hash
                   14553:  my %history=&Apache::lonnet::restore();
                   14554: 
                   14555:  #print the hash
                   14556:  foreach my $key (sort(keys(%history))) {
                   14557:    print("\%history{$key} = $history{$key}");
                   14558:  }
                   14559: 
                   14560: Will print out:
1.191     harris41 14561: 
1.394     bowersj2 14562:  %history{1:foo} = bar
                   14563:  %history{1:keys} = foo:timestamp
                   14564:  %history{1:timestamp} = 990455579
                   14565:  %history{2:bar} = foo
                   14566:  %history{2:foo} = notbar
                   14567:  %history{2:keys} = foo:bar:timestamp
                   14568:  %history{2:timestamp} = 990455580
                   14569:  %history{bar} = foo
                   14570:  %history{foo} = notbar
                   14571:  %history{timestamp} = 990455580
                   14572:  %history{version} = 2
                   14573: 
                   14574: Note that the special hash entries C<keys>, C<version> and
                   14575: C<timestamp> were added to the hash. C<version> will be equal to the
                   14576: total number of versions of the data that have been stored. The
                   14577: C<timestamp> attribute will be the UNIX time the hash was
                   14578: stored. C<keys> is available in every historical section to list which
                   14579: keys were added or changed at a specific historical revision of a
                   14580: hash.
                   14581: 
                   14582: B<Warning>: do not store the hash that restore returns directly. This
                   14583: will cause a mess since it will restore the historical keys as if the
                   14584: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14585: 
1.394     bowersj2 14586: Calling convention:
1.191     harris41 14587: 
1.1225    raeburn  14588:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14589:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14590: 
1.394     bowersj2 14591: For more detailed information, see lonnet specific documentation.
1.191     harris41 14592: 
1.394     bowersj2 14593: =head1 RETURN MESSAGES
1.191     harris41 14594: 
1.394     bowersj2 14595: =over 4
1.191     harris41 14596: 
1.394     bowersj2 14597: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14598: 
1.394     bowersj2 14599: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14600: when the connection is brought back up
1.191     harris41 14601: 
1.394     bowersj2 14602: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14603: for later delivery
1.191     harris41 14604: 
1.967     bisitz   14605: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14606: 
1.394     bowersj2 14607: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14608: that was requested
1.191     harris41 14609: 
1.243     albertel 14610: =back
1.191     harris41 14611: 
1.243     albertel 14612: =head1 PUBLIC SUBROUTINES
1.191     harris41 14613: 
1.243     albertel 14614: =head2 Session Environment Functions
1.191     harris41 14615: 
1.243     albertel 14616: =over 4
1.191     harris41 14617: 
1.394     bowersj2 14618: =item * 
                   14619: X<appenv()>
1.949     raeburn  14620: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14621: the user envirnoment file, and will be restored for each access this
1.620     albertel 14622: user makes during this session, also modifies the %env for the current
1.949     raeburn  14623: process. Optional rolesarrayref - if defined contains a reference to an array
                   14624: of roles which are exempt from the restriction on modifying user.role entries 
                   14625: in the user's environment.db and in %env.    
1.191     harris41 14626: 
                   14627: =item *
1.394     bowersj2 14628: X<delenv()>
1.987     raeburn  14629: B<delenv($delthis,$regexp)>: removes all items from the session
                   14630: environment file that begin with $delthis. If the 
                   14631: optional second arg - $regexp - is true, $delthis is treated as a 
                   14632: regular expression, otherwise \Q$delthis\E is used. 
                   14633: The values are also deleted from the current processes %env.
1.191     harris41 14634: 
1.795     albertel 14635: =item * get_env_multiple($name) 
                   14636: 
                   14637: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14638: values may be defined and end up as an array ref.
                   14639: 
                   14640: returns an array of values
                   14641: 
1.243     albertel 14642: =back
                   14643: 
                   14644: =head2 User Information
1.191     harris41 14645: 
1.243     albertel 14646: =over 4
1.191     harris41 14647: 
                   14648: =item *
1.394     bowersj2 14649: X<queryauthenticate()>
                   14650: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14651: authentication scheme
                   14652: 
                   14653: =item *
1.394     bowersj2 14654: X<authenticate()>
1.1073    raeburn  14655: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14656: authenticate user from domain's lib servers (first use the current
                   14657: one). C<$upass> should be the users password.
1.1073    raeburn  14658: $checkdefauth is optional (value is 1 if a check should be made to
                   14659:    authenticate user using default authentication method, and allow
                   14660:    account creation if username does not have account in the domain).
                   14661: $clientcancheckhost is optional (value is 1 if checking whether the
                   14662:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14663: 
                   14664: =item *
1.394     bowersj2 14665: X<homeserver()>
                   14666: B<homeserver($uname,$udom)>: find the server which has
                   14667: the user's directory and files (there must be only one), this caches
                   14668: the answer, and also caches if there is a borken connection.
1.191     harris41 14669: 
                   14670: =item *
1.394     bowersj2 14671: X<idget()>
1.1300    raeburn  14672: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14673: a list of student/employee IDs or clicker IDs
                   14674: (student/employee IDs are a unique resource in a domain, there must be 
                   14675: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14676: clickerIDs are not necessarily unique, as students might share clickers.
                   14677: (returns hash: id=>name,id=>name)
1.191     harris41 14678: 
                   14679: =item *
1.394     bowersj2 14680: X<idrget()>
                   14681: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14682: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14683: 
                   14684: =item *
1.394     bowersj2 14685: X<idput()>
1.1300    raeburn  14686: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14687: names and associated student/employee IDs or clicker IDs.
                   14688: 
                   14689: =item *
                   14690: X<iddel()>
                   14691: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14692: student/employee ID or clicker ID username look-ups from domain.
                   14693: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14694: If no $uhome is provided, it will be determined usig &homeserver()
                   14695: for each user.  If no $namespace is provided, the default is ids.
                   14696: 
                   14697: =item *
                   14698: X<updateclickers()>
                   14699: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14700: clicker ID-to-username look-ups in clickers.db on library server.
                   14701: Permitted actions are add or del (i.e., add or delete). The 
                   14702: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14703: value is an escaped comma-separated list of usernames (for whom the
                   14704: library server is the homeserver), who registered that particular ID.
                   14705: If $critical is true, the update will be sent via &critical, otherwise
                   14706: &reply() will be used.
1.191     harris41 14707: 
                   14708: =item *
1.394     bowersj2 14709: X<rolesinit()>
1.1169    droeschl 14710: B<rolesinit($udom,$username)>: get user privileges.
                   14711: returns user role, first access and timer interval hashes
1.243     albertel 14712: 
                   14713: =item *
1.1171    droeschl 14714: X<privileged()>
                   14715: B<privileged($username,$domain)>: returns a true if user has a
                   14716: privileged and active role (i.e. su or dc), false otherwise.
                   14717: 
                   14718: =item *
1.551     albertel 14719: X<getsection()>
                   14720: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14721: course $cname, return section name/number or '' for "not in course"
                   14722: and '-1' for "no section"
                   14723: 
                   14724: =item *
1.394     bowersj2 14725: X<userenvironment()>
                   14726: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14727: passed in @what from the requested user's environment, returns a hash
                   14728: 
1.858     raeburn  14729: =item * 
                   14730: X<userlog_query()>
1.859     albertel 14731: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14732: activity.log file. %filters defines filters applied when parsing the
                   14733: log file. These can be start or end timestamps, or the type of action
                   14734: - log to look for Login or Logout events, check for Checkin or
                   14735: Checkout, role for role selection. The response is in the form
                   14736: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14737: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14738: 
1.243     albertel 14739: =back
                   14740: 
                   14741: =head2 User Roles
                   14742: 
                   14743: =over 4
                   14744: 
                   14745: =item *
                   14746: 
1.1284    raeburn  14747: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14748: returns codes for allowed actions.
                   14749: 
                   14750: The first argument is required, all others are optional.
                   14751: 
                   14752: $priv is the privilege being checked.
                   14753: $uri contains additional information about what is being checked for access (e.g.,
                   14754: URL, course ID etc.). 
                   14755: $symb is the unique resource instance identifier in a course; if needed,
                   14756: but not provided, it will be retrieved via a call to &symbread(). 
                   14757: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14758: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14759: files).
                   14760: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14761: prevents recursive calls to &allowed.
                   14762: 
1.243     albertel 14763:  F: full access
                   14764:  U,I,K: authentication modes (cxx only)
                   14765:  '': forbidden
                   14766:  1: user needs to choose course
                   14767:  2: browse allowed
1.766     albertel 14768:  A: passphrase authentication needed
1.1284    raeburn  14769:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14770: 
                   14771: =item *
                   14772: 
1.1192    raeburn  14773: constructaccess($url,$setpriv) : check for access to construction space URL
                   14774: 
                   14775: See if the owner domain and name in the URL match those in the
                   14776: expected environment.  If so, return three element list
                   14777: ($ownername,$ownerdomain,$ownerhome).
                   14778: 
                   14779: Otherwise return the null string.
                   14780: 
                   14781: If second argument 'setpriv' is true, it assigns the privileges,
                   14782: and returns the same three element list, unless the owner has
                   14783: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14784: in which case the null string is returned.
                   14785: 
                   14786: =item *
                   14787: 
1.1326    raeburn  14788: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14789: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14790: for system, domain, and course level. $uname and $udom are optional (current
                   14791: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14792: 
                   14793: =item *
                   14794: 
1.988     raeburn  14795: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14796: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14797: $type is Course (default) or Community.
1.988     raeburn  14798: If $forcedefault evaluates to true, text returned will be default 
                   14799: text for $type. Otherwise, if this is a course, the text returned 
                   14800: will be a custom name for the role (if defined in the course's 
                   14801: environment).  If no custom name is defined the default is returned.
                   14802:    
1.832     raeburn  14803: =item *
                   14804: 
1.1219    raeburn  14805: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14806: All arguments are optional. Returns a hash of a roles, either for
                   14807: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14808: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14809: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14810: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14811: For each key, value is set to colon-separated start and end times for
                   14812: the role.  If no username and domain are specified, will default to
1.934     raeburn  14813: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14814: of role statuses (active, future or previous), roles 
                   14815: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14816: to restrict the list of roles reported. If no array ref is 
                   14817: provided for types, will default to return only active roles.
1.834     albertel 14818: 
1.1195    raeburn  14819: =item *
                   14820: 
                   14821: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14822: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14823: 
                   14824: Additional optional arguments are: $type (if role checking is to be restricted 
                   14825: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14826: available roles) or future (roles available in the future), and
                   14827: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14828: have active Domain Coordinator role in course's domain or in additional
                   14829: domains (specified in 'Domains to check for privileged users' in course
                   14830: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14831: 
                   14832: =item *
                   14833: 
                   14834: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14835: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14836: $possdomains and $possroles are optional array refs -- to domains to check and
                   14837: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14838: users' roles.db to check for a dc or su role in any domain. This can be
                   14839: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14840: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14841: this then allows &privileged_by_domain() to be used, which caches the identity
                   14842: of privileged users, eliminating the need for repeated calls to &dump().
                   14843: 
                   14844: =item *
                   14845: 
                   14846: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14847: where the outer hash keys are domains specified in the $possdomains array ref,
                   14848: next inner hash keys are privileged roles specified in the $roles array ref,
                   14849: and the innermost hash contains key = value pairs for username:domain = end:start
                   14850: for active or future "privileged" users with that role in that domain. To avoid
                   14851: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14852: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14853: 
1.243     albertel 14854: =back
                   14855: 
                   14856: =head2 User Modification
                   14857: 
                   14858: =over 4
                   14859: 
                   14860: =item *
                   14861: 
1.957     raeburn  14862: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14863: user for the level given by URL.  Optional start and end dates (leave empty
                   14864: string or zero for "no date")
1.191     harris41 14865: 
                   14866: =item *
                   14867: 
1.243     albertel 14868: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14869: change a users, password, possible return values are: ok,
                   14870: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14871: refused
1.191     harris41 14872: 
                   14873: =item *
                   14874: 
1.243     albertel 14875: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14876: 
                   14877: =item *
                   14878: 
1.1058    raeburn  14879: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14880:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14881: 
                   14882: will update user information (firstname,middlename,lastname,generation,
                   14883: permanentemail), and if forceid is true, student/employee ID also.
                   14884: A user's institutional affiliation(s) can also be updated.
                   14885: User information fields will not be overwritten with empty entries 
                   14886: unless the field is included in the $candelete array reference.
                   14887: This array is included when a single user is modified via "Manage Users",
                   14888: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14889: 
                   14890: =item *
                   14891: 
1.286     matthew  14892: modifystudent
                   14893: 
1.957     raeburn  14894: modify a student's enrollment and identification information.
1.1235    raeburn  14895: The course id is resolved based on the current user's environment.  
                   14896: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14897: associated with a course.
                   14898: 
1.297     matthew  14899: This call is essentially a wrapper for lonnet::modifyuser and
                   14900: lonnet::modify_student_enrollment
1.286     matthew  14901: 
                   14902: Inputs: 
                   14903: 
                   14904: =over 4
                   14905: 
1.957     raeburn  14906: =item B<$udom> Student's loncapa domain
1.286     matthew  14907: 
1.957     raeburn  14908: =item B<$uname> Student's loncapa login name
1.286     matthew  14909: 
1.964     bisitz   14910: =item B<$uid> Student/Employee ID
1.286     matthew  14911: 
1.957     raeburn  14912: =item B<$umode> Student's authentication mode
1.286     matthew  14913: 
1.957     raeburn  14914: =item B<$upass> Student's password
1.286     matthew  14915: 
1.957     raeburn  14916: =item B<$first> Student's first name
1.286     matthew  14917: 
1.957     raeburn  14918: =item B<$middle> Student's middle name
1.286     matthew  14919: 
1.957     raeburn  14920: =item B<$last> Student's last name
1.286     matthew  14921: 
1.957     raeburn  14922: =item B<$gene> Student's generation
1.286     matthew  14923: 
1.957     raeburn  14924: =item B<$usec> Student's section in course
1.286     matthew  14925: 
                   14926: =item B<$end> Unix time of the roles expiration
                   14927: 
                   14928: =item B<$start> Unix time of the roles start date
                   14929: 
                   14930: =item B<$forceid> If defined, allow $uid to be changed
                   14931: 
                   14932: =item B<$desiredhome> server to use as home server for student
                   14933: 
1.957     raeburn  14934: =item B<$email> Student's permanent e-mail address
                   14935: 
                   14936: =item B<$type> Type of enrollment (auto or manual)
                   14937: 
1.963     raeburn  14938: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14939: 
                   14940: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14941: 
1.963     raeburn  14942: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14943: 
1.963     raeburn  14944: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14945: 
1.1216    raeburn  14946: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14947: 
                   14948: =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  14949: 
1.286     matthew  14950: =back
1.297     matthew  14951: 
                   14952: =item *
                   14953: 
                   14954: modify_student_enrollment
                   14955: 
1.1235    raeburn  14956: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14957: 'role.request.course' must be defined for this function to proceed.
                   14958: 
                   14959: Inputs:
                   14960: 
                   14961: =over 4
                   14962: 
1.1235    raeburn  14963: =item $udom, student's domain
1.297     matthew  14964: 
1.1235    raeburn  14965: =item $uname, student's name
1.297     matthew  14966: 
1.1235    raeburn  14967: =item $uid, student's user id
1.297     matthew  14968: 
1.1235    raeburn  14969: =item $first, student's first name
1.297     matthew  14970: 
                   14971: =item $middle
                   14972: 
                   14973: =item $last
                   14974: 
                   14975: =item $gene
                   14976: 
                   14977: =item $usec
                   14978: 
                   14979: =item $end
                   14980: 
                   14981: =item $start
                   14982: 
1.957     raeburn  14983: =item $type
                   14984: 
                   14985: =item $locktype
                   14986: 
                   14987: =item $cid
                   14988: 
                   14989: =item $selfenroll
                   14990: 
                   14991: =item $context
                   14992: 
1.1216    raeburn  14993: =item $credits, number of credits student will earn from this class
                   14994: 
1.1314    raeburn  14995: =item $instsec, institutional course section code for student
                   14996: 
1.297     matthew  14997: =back
                   14998: 
1.191     harris41 14999: 
                   15000: =item *
                   15001: 
1.243     albertel 15002: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15003: custom role; give a custom role to a user for the level given by URL.  Specify
                   15004: name and domain of role author, and role name
1.191     harris41 15005: 
                   15006: =item *
                   15007: 
1.243     albertel 15008: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15009: 
                   15010: =item *
                   15011: 
1.243     albertel 15012: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15013: 
                   15014: =back
                   15015: 
                   15016: =head2 Course Infomation
                   15017: 
                   15018: =over 4
1.191     harris41 15019: 
                   15020: =item *
                   15021: 
1.1118    foxr     15022: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15023: specified course id, including all environment settings for the
                   15024: course, the description of the course will be in the hash under the
                   15025: key 'description'
1.191     harris41 15026: 
1.1118    foxr     15027: $options is an optional parameter that if supplied is a hash reference that controls
                   15028: what how this function works.  It has the following key/values:
                   15029: 
                   15030: =over 4
                   15031: 
                   15032: =item freshen_cache
                   15033: 
                   15034: If defined, and the environment cache for the course is valid, it is 
                   15035: returned in the returned hash.
                   15036: 
                   15037: =item one_time
                   15038: 
                   15039: If defined, the last cache time is set to _now_
                   15040: 
                   15041: =item user
                   15042: 
                   15043: If defined, the supplied username is used instead of the current user.
                   15044: 
                   15045: 
                   15046: =back
                   15047: 
1.191     harris41 15048: =item *
                   15049: 
1.624     albertel 15050: resdata($name,$domain,$type,@which) : request for current parameter
                   15051: setting for a specific $type, where $type is either 'course' or 'user',
                   15052: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15053: answers for 10 minutes.
1.243     albertel 15054: 
1.877     foxr     15055: =item *
                   15056: 
                   15057: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15058: data base, returning a hash that is keyed by the resource name and has
                   15059: values that are the resource value.  I believe that the timestamps and
                   15060: versions are also returned.
                   15061: 
1.1236    raeburn  15062: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15063: supplemental content area. This routine caches the number of files for 
                   15064: 10 minutes.
                   15065: 
1.243     albertel 15066: =back
                   15067: 
                   15068: =head2 Course Modification
                   15069: 
                   15070: =over 4
1.191     harris41 15071: 
                   15072: =item *
                   15073: 
1.243     albertel 15074: writecoursepref($courseid,%prefs) : write preferences (environment
                   15075: database) for a course
1.191     harris41 15076: 
                   15077: =item *
                   15078: 
1.1011    raeburn  15079: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15080: 
                   15081: =item *
                   15082: 
1.1038    raeburn  15083: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15084: 
1.1167    droeschl 15085: =item *
                   15086: 
                   15087: is_course($courseid), is_course($cdom, $cnum)
                   15088: 
                   15089: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15090: two component version $cdom, $cnum. It checks if the specified course exists.
                   15091: 
                   15092: Returns:
                   15093:     undef if the course doesn't exist, otherwise
                   15094:     in scalar context the combined courseid.
                   15095:     in list context the two components of the course identifier, domain and 
                   15096:     courseid.    
                   15097: 
1.243     albertel 15098: =back
                   15099: 
                   15100: =head2 Resource Subroutines
                   15101: 
                   15102: =over 4
1.191     harris41 15103: 
                   15104: =item *
                   15105: 
1.243     albertel 15106: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15107: 
                   15108: =item *
                   15109: 
1.243     albertel 15110: repcopy($filename) : subscribes to the requested file, and attempts to
                   15111: replicate from the owning library server, Might return
1.607     raeburn  15112: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15113: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15114: resource. Expects the local filesystem pathname
                   15115: (/home/httpd/html/res/....)
                   15116: 
                   15117: =back
                   15118: 
                   15119: =head2 Resource Information
                   15120: 
                   15121: =over 4
1.191     harris41 15122: 
                   15123: =item *
                   15124: 
1.1228    raeburn  15125: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15126: and returns the value of a variety of different possible values,
                   15127: $varname should be a request string, and the other parameters can be
                   15128: used to specify who and what one is asking about. Ordinarily, $cid 
                   15129: does not need to be specified, as it is retrived from 
                   15130: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15131: within lonuserstate::loadmap() when initializing a course, before
                   15132: $env{'request.course.id'} has been set, so it needs to be provided
                   15133: in that one case.
1.243     albertel 15134: 
                   15135: Possible values for $varname are environment.lastname (or other item
                   15136: from the envirnment hash), user.name (or someother aspect about the
                   15137: user), resource.0.maxtries (or some other part and parameter of a
                   15138: resource)
1.204     albertel 15139: 
                   15140: =item *
                   15141: 
1.243     albertel 15142: directcondval($number) : get current value of a condition; reads from a state
                   15143: string
1.204     albertel 15144: 
                   15145: =item *
                   15146: 
1.243     albertel 15147: condval($condidx) : value of condition index based on state
1.204     albertel 15148: 
                   15149: =item *
                   15150: 
1.1362    raeburn  15151: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15152: resource's metadata, $what should be either a specific key, or either
                   15153: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15154: packages that this resource currently uses, the last 3 arguments are 
                   15155: only used internally for recursive metadata.
                   15156: 
                   15157: the toolsymb is only used where the uri is for an external tool (for which
                   15158: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15159: 
1.1371    raeburn  15160: this function automatically caches all requests except any made recursively
                   15161: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15162: defined).
1.191     harris41 15163: 
                   15164: =item *
                   15165: 
1.243     albertel 15166: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15167: network of library servers; returns file handle of where SQL and regex results
                   15168: will be stored for query
1.191     harris41 15169: 
                   15170: =item *
                   15171: 
1.1282    raeburn  15172: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15173: return symbolic list entry (all arguments optional). 
                   15174: 
                   15175: Args: filename is the filename (including path) for the file for which a symb 
                   15176: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15177: to check access status if more than one resource was found in the bighash 
                   15178: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15179: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15180: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15181: cause possible symbs to be checked to determine if they are subject to content
                   15182: blocking, if so they will not be included as possible symbs; possibles is a
                   15183: ref to a hash, which, as a side effect, will be populated with all possible 
                   15184: symbs (content blocking not tested).
                   15185:  
1.243     albertel 15186: returns the data handle
1.191     harris41 15187: 
                   15188: =item *
                   15189: 
1.1190    raeburn  15190: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15191: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15192: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15193: on failure, user must be in a course, as it assumes the existence of
                   15194: the course initial hash, and uses $env('request.course.id'}.  The third
                   15195: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15196: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15197: encrypted; otherwise it will be null.  
1.191     harris41 15198: 
                   15199: =item *
                   15200: 
1.243     albertel 15201: symbclean($symb) : removes versions numbers from a symb, returns the
                   15202: cleaned symb
1.191     harris41 15203: 
                   15204: =item *
                   15205: 
1.243     albertel 15206: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15207: course map, user must be in a course for it to work.
1.191     harris41 15208: 
                   15209: =item *
                   15210: 
1.243     albertel 15211: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15212: 
                   15213: =item *
                   15214: 
1.243     albertel 15215: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15216: a random seed, all arguments are optional, if they aren't sent it uses the
                   15217: environment to derive them. Note: if symb isn't sent and it can't get one
                   15218: from &symbread it will use the current time as its return value
1.191     harris41 15219: 
                   15220: =item *
                   15221: 
1.243     albertel 15222: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15223: unfakeable, receipt
1.191     harris41 15224: 
                   15225: =item *
                   15226: 
1.620     albertel 15227: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15228: 
                   15229: =item *
                   15230: 
1.243     albertel 15231: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15232: 
                   15233: =item *
                   15234: 
1.243     albertel 15235: 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 15236: 
                   15237: =item *
                   15238: 
1.243     albertel 15239: 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 15240: 
                   15241: =item *
                   15242: 
1.243     albertel 15243: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15244: 
                   15245: =item *
                   15246: 
1.243     albertel 15247: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15248: forcing spreadsheet to reevaluate the resource scores next time.
                   15249: 
1.1195    raeburn  15250: =item * 
                   15251: 
1.1196    raeburn  15252: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15253: when viewing in course context.
1.1195    raeburn  15254: 
1.1196    raeburn  15255:  input: six args -- filename (decluttered), course number, course domain,
                   15256:                     url, symb (if registered) and group (if this is a 
                   15257:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15258: 
1.1196    raeburn  15259:  output: array of five scalars --
1.1195    raeburn  15260:          $cfile -- url for file editing if editable on current server
                   15261:          $home -- homeserver of resource (i.e., for author if published,
                   15262:                                           or course if uploaded.).
                   15263:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15264:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15265:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15266: 
                   15267: =item *
                   15268: 
                   15269: is_course_upload($file,$cnum,$cdom)
                   15270: 
                   15271: Used in course context to determine if current file was uploaded to 
                   15272: the course (i.e., would be found in /userfiles/docs on the course's 
                   15273: homeserver.
                   15274: 
                   15275:   input: 3 args -- filename (decluttered), course number and course domain.
                   15276:   output: boolean -- 1 if file was uploaded.
                   15277: 
1.243     albertel 15278: =back
                   15279: 
                   15280: =head2 Storing/Retreiving Data
                   15281: 
                   15282: =over 4
1.191     harris41 15283: 
                   15284: =item *
                   15285: 
1.1269    raeburn  15286: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15287: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15288: the remaining args aren't required and if they aren't passed or are '' they will
                   15289: be derived from the env (with the exception of $laststore, which is an 
                   15290: optional arg used when a user's submission is stored in grading).
                   15291: $laststore is $version=$timestamp, where $version is the most recent version
                   15292: number retrieved for the corresponding $symb in the $namespace db file, and
                   15293: $timestamp is the timestamp for that transaction (UNIX time).
                   15294: $laststore is currently only passed when cstore() is called by 
                   15295: structuretags::finalize_storage().
1.191     harris41 15296: 
                   15297: =item *
                   15298: 
1.1269    raeburn  15299: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15300: but uses critical subroutine
1.191     harris41 15301: 
                   15302: =item *
                   15303: 
1.243     albertel 15304: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15305: all args are optional
1.191     harris41 15306: 
                   15307: =item *
                   15308: 
1.717     albertel 15309: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15310: dumps the complete (or key matching regexp) namespace into a hash
                   15311: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15312: normally &store()ed into
                   15313: 
                   15314: $range should be either an integer '100' (give me the first 100
                   15315:                                            matching records)
                   15316:               or be  two integers sperated by a - with no spaces
                   15317:                  '30-50' (give me the 30th through the 50th matching
                   15318:                           records)
                   15319: 
                   15320: 
                   15321: =item *
                   15322: 
1.1269    raeburn  15323: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15324: replaces a &store() version of data with a replacement set of data
                   15325: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15326: reference. If $tolog is true, the transaction is logged in the courselog
                   15327: with an action=PUTSTORE.
1.717     albertel 15328: 
                   15329: =item *
                   15330: 
1.243     albertel 15331: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15332: works very similar to store/cstore, but all data is stored in a
                   15333: temporary location and can be reset using tmpreset, $storehash should
                   15334: be a hash reference, returns nothing on success
1.191     harris41 15335: 
                   15336: =item *
                   15337: 
1.243     albertel 15338: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15339: similar to restore, but all data is stored in a temporary location and
                   15340: can be reset using tmpreset. Returns a hash of values on success,
                   15341: error string otherwise.
1.191     harris41 15342: 
                   15343: =item *
                   15344: 
1.243     albertel 15345: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15346: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15347: 
                   15348: =item *
                   15349: 
1.243     albertel 15350: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15351: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15352: 
                   15353: =item *
                   15354: 
1.243     albertel 15355: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15356: namesp ($udom and $uname are optional)
1.191     harris41 15357: 
                   15358: =item *
                   15359: 
1.702     albertel 15360: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15361: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15362: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15363: 
1.702     albertel 15364: $range should be either an integer '100' (give me the first 100
                   15365:                                            matching records)
                   15366:               or be  two integers sperated by a - with no spaces
                   15367:                  '30-50' (give me the 30th through the 50th matching
                   15368:                           records)
1.449     matthew  15369: =item *
                   15370: 
                   15371: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15372: $store can be a scalar, an array reference, or if the amount to be 
                   15373: incremented is > 1, a hash reference.
                   15374: 
                   15375: ($udom and $uname are optional)
1.191     harris41 15376: 
                   15377: =item *
                   15378: 
1.243     albertel 15379: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15380: ($udom and $uname are optional)
1.191     harris41 15381: 
                   15382: =item *
                   15383: 
1.243     albertel 15384: cput($namespace,$storehash,$udom,$uname) : critical put
                   15385: ($udom and $uname are optional)
1.191     harris41 15386: 
                   15387: =item *
                   15388: 
1.748     albertel 15389: newput($namespace,$storehash,$udom,$uname) :
                   15390: 
                   15391: Attempts to store the items in the $storehash, but only if they don't
                   15392: currently exist, if this succeeds you can be certain that you have 
                   15393: successfully created a new key value pair in the $namespace db.
                   15394: 
                   15395: 
                   15396: Args:
                   15397:  $namespace: name of database to store values to
                   15398:  $storehash: hashref to store to the db
                   15399:  $udom: (optional) domain of user containing the db
                   15400:  $uname: (optional) name of user caontaining the db
                   15401: 
                   15402: Returns:
                   15403:  'ok' -> succeeded in storing all keys of $storehash
                   15404:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15405:                         least <key> already existed in the db (other
                   15406:                         requested keys may also already exist)
1.967     bisitz   15407:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15408:  'con_lost' -> unable to contact request server
                   15409:  'refused' -> action was not allowed by remote machine
                   15410: 
                   15411: 
                   15412: =item *
                   15413: 
1.243     albertel 15414: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15415: reference filled in from namesp (encrypts the return communication)
                   15416: ($udom and $uname are optional)
1.191     harris41 15417: 
                   15418: =item *
                   15419: 
1.243     albertel 15420: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15421: critical subroutine
                   15422: 
1.806     raeburn  15423: =item *
                   15424: 
1.860     raeburn  15425: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15426: array reference filled in from namespace found in domain level on either
                   15427: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15428: 
                   15429: =item *
                   15430: 
1.860     raeburn  15431: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15432: domain level either on specified domain server ($uhome) or primary domain 
                   15433: server ($udom and $uhome are optional)
1.806     raeburn  15434: 
1.943     raeburn  15435: =item * 
                   15436: 
1.1240    raeburn  15437: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15438: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15439: the target domain.
                   15440: 
                   15441: May also include additional key => value pairs for the following groups:
                   15442: 
                   15443: =over
                   15444: 
                   15445: =item
                   15446: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15447: 
                   15448: =over
                   15449: 
                   15450: =item defaultquota, authorquota
                   15451: 
                   15452: =back
                   15453: 
                   15454: =item
                   15455: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15456: portfolio for users).
                   15457: 
                   15458: =over
                   15459: 
                   15460: =item
                   15461: aboutme, blog, webdav, portfolio
                   15462: 
                   15463: =back
                   15464: 
                   15465: =item
                   15466: requestcourses: ability to request courses, and how requests are processed.
                   15467: 
                   15468: =over
                   15469: 
                   15470: =item
1.1305    raeburn  15471: official, unofficial, community, textbook, placement
1.1240    raeburn  15472: 
                   15473: =back
                   15474: 
                   15475: =item
                   15476: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15477: 
                   15478: =over
                   15479: 
                   15480: =item
1.1256    raeburn  15481: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15482: 
                   15483: =back
                   15484: 
                   15485: =item
                   15486: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15487: for course's uploaded content.
                   15488: 
                   15489: =over
                   15490: 
                   15491: =item
1.1246    raeburn  15492: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15493: communityquota, textbookquota, placementquota
1.1240    raeburn  15494: 
                   15495: =back
                   15496: 
                   15497: =item
                   15498: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15499: on your servers.
                   15500: 
                   15501: =over
                   15502: 
                   15503: =item 
                   15504: remotesessions, hostedsessions
                   15505: 
                   15506: =back
                   15507: 
                   15508: =back
                   15509: 
                   15510: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15511: utility to create a configuration.db file on a domain's primary library server 
                   15512: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15513: -- corresponding values are authentication type (internal, krb4, krb5,
                   15514: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15515: will be available. Values are retrieved from cache (if current), unless the
                   15516: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15517: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15518: 
                   15519: Typical usage:
1.943     raeburn  15520: 
1.1240    raeburn  15521: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15522: 
1.243     albertel 15523: =back
                   15524: 
                   15525: =head2 Network Status Functions
                   15526: 
                   15527: =over 4
1.191     harris41 15528: 
                   15529: =item *
                   15530: 
1.1137    raeburn  15531: dirlist() : return directory list based on URI (first arg).
                   15532: 
                   15533: Inputs: 1 required, 5 optional.
                   15534: 
                   15535: =over
                   15536: 
                   15537: =item 
                   15538: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15539: 
                   15540: =item
                   15541: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15542: 
                   15543: =item
                   15544: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15545: 
                   15546: =item
                   15547: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15548: 
                   15549: =item
                   15550: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15551: 
                   15552: =item 
                   15553: $alternateRoot - path to prepend in place of path from $uri.
                   15554: 
                   15555: =back
                   15556: 
                   15557: Returns: Array of up to two items.
                   15558: 
                   15559: =over
                   15560: 
                   15561: a reference to an array of files/subdirectories
                   15562: 
                   15563: =over
                   15564: 
                   15565: Each element in the array of files/subdirectories is a & separated list of
                   15566: item name and the result of running stat on the item.  If dirlist was requested
                   15567: for a file instead of a directory, the item name will be ''. For a directory 
                   15568: listing, if the item is a metadata file, the element will end &N&M 
                   15569: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15570: default copyright set (1).  
                   15571: 
                   15572: =back
                   15573: 
                   15574: a scalar containing error condition (if encountered).
                   15575: 
                   15576: =over
                   15577: 
                   15578: =item 
                   15579: no_host (no homeserver identified for $username:$domain).
                   15580: 
                   15581: =item 
                   15582: no_such_host (server contacted for listing not identified as valid host).
                   15583: 
                   15584: =item 
                   15585: con_lost (connection to remote server failed).
                   15586: 
                   15587: =item 
                   15588: refused (invalid $username:$domain received on lond side).
                   15589: 
                   15590: =item 
                   15591: no_such_dir (directory at specified path on lond side does not exist). 
                   15592: 
                   15593: =item 
                   15594: empty (directory at specified path on lond side is empty).
                   15595: 
                   15596: =over
                   15597: 
                   15598: This is currently not encountered because the &ls3, &ls2, 
                   15599: &ls (_handler) routines on the lond side do not filter out
                   15600: . and .. from a directory listing. 
                   15601: 
                   15602: =back
                   15603: 
                   15604: =back
                   15605: 
                   15606: =back
1.191     harris41 15607: 
                   15608: =item *
                   15609: 
1.243     albertel 15610: spareserver() : find server with least workload from spare.tab
                   15611: 
1.986     foxr     15612: 
                   15613: =item *
                   15614: 
                   15615: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15616: if there is no corresponding loncapa host.
                   15617: 
1.243     albertel 15618: =back
                   15619: 
1.986     foxr     15620: 
1.243     albertel 15621: =head2 Apache Request
                   15622: 
                   15623: =over 4
1.191     harris41 15624: 
                   15625: =item *
                   15626: 
1.243     albertel 15627: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15628: localhost, posts hash
                   15629: 
                   15630: =back
                   15631: 
                   15632: =head2 Data to String to Data
                   15633: 
                   15634: =over 4
1.191     harris41 15635: 
                   15636: =item *
                   15637: 
1.243     albertel 15638: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15639: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15640: 
                   15641: =item *
                   15642: 
1.243     albertel 15643: hashref2str($hashref) : convert a hashref into a string complete with
                   15644: escaping and '=' and '&' separators, supports elements that are
                   15645: arrayrefs and hashrefs
1.191     harris41 15646: 
                   15647: =item *
                   15648: 
1.243     albertel 15649: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15650: with escaping and '&' separators, supports elements that are arrayrefs
                   15651: and hashrefs
1.191     harris41 15652: 
                   15653: =item *
                   15654: 
1.243     albertel 15655: str2hash($string) : convert string to hash using unescaping and
                   15656: splitting on '=' and '&', supports elements that are arrayrefs and
                   15657: hashrefs
1.191     harris41 15658: 
                   15659: =item *
                   15660: 
1.243     albertel 15661: str2array($string) : convert string to hash using unescaping and
                   15662: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15663: 
                   15664: =back
                   15665: 
                   15666: =head2 Logging Routines
                   15667: 
                   15668: 
                   15669: These routines allow one to make log messages in the lonnet.log and
                   15670: lonnet.perm logfiles.
1.191     harris41 15671: 
1.1119    foxr     15672: =over 4
                   15673: 
1.191     harris41 15674: =item *
                   15675: 
1.243     albertel 15676: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15677: 
                   15678: =item *
                   15679: 
1.243     albertel 15680: logthis() : append message to the normal lonnet.log file, it gets
                   15681: preiodically rolled over and deleted.
1.191     harris41 15682: 
                   15683: =item *
                   15684: 
1.243     albertel 15685: logperm() : append a permanent message to lonnet.perm.log, this log
                   15686: file never gets deleted by any automated portion of the system, only
                   15687: messages of critical importance should go in here.
                   15688: 
1.1119    foxr     15689: 
1.243     albertel 15690: =back
                   15691: 
                   15692: =head2 General File Helper Routines
                   15693: 
                   15694: =over 4
1.191     harris41 15695: 
                   15696: =item *
                   15697: 
1.481     raeburn  15698: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15699: (a) files in /uploaded
                   15700:   (i) If a local copy of the file exists - 
                   15701:       compares modification date of local copy with last-modified date for 
                   15702:       definitive version stored on home server for course. If local copy is 
                   15703:       stale, requests a new version from the home server and stores it. 
                   15704:       If the original has been removed from the home server, then local copy 
                   15705:       is unlinked.
                   15706:   (ii) If local copy does not exist -
                   15707:       requests the file from the home server and stores it. 
                   15708:   
                   15709:   If $caller is 'uploadrep':  
                   15710:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15711:     for request for files originally uploaded via DOCS. 
                   15712:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15713:   
                   15714:   Otherwise:
                   15715:      This indicates a call from the content generation phase of the request.
                   15716:      -  returns the entire contents of the file or -1.
                   15717:      
                   15718: (b) files in /res
                   15719:    - returns the entire contents of a file or -1; 
                   15720:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15721: 
1.712     albertel 15722: 
                   15723: =item *
                   15724: 
                   15725: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15726:                   reference
                   15727: 
                   15728: returns either a stat() list of data about the file or an empty list
                   15729: if the file doesn't exist or couldn't find out about it (connection
                   15730: problems or user unknown)
                   15731: 
1.191     harris41 15732: =item *
                   15733: 
1.243     albertel 15734: filelocation($dir,$file) : returns file system location of a file
                   15735: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15736: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15737: and a file of ../bob will become /a/bob)
1.191     harris41 15738: 
                   15739: =item *
                   15740: 
                   15741: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15742: filelocation except for hrefs
                   15743: 
                   15744: =item *
                   15745: 
1.1261    raeburn  15746: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15747: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15748: 
1.243     albertel 15749: =back
                   15750: 
1.608     albertel 15751: =head2 Usererfile file routines (/uploaded*)
                   15752: 
                   15753: =over 4
                   15754: 
                   15755: =item *
                   15756: 
                   15757: userfileupload(): main rotine for putting a file in a user or course's
                   15758:                   filespace, arguments are,
                   15759: 
1.620     albertel 15760:  formname - required - this is the name of the element in $env where the
1.608     albertel 15761:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15762:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15763:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15764:  context - if coursedoc, store the file in the course of the active role
                   15765:              of the current user; 
                   15766:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15767:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15768:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15769:          if undefined, it will be placed in "unknown"
                   15770: 
                   15771:  (This routine calls clean_filename() to remove any dangerous
                   15772:  characters from the filename, and then calls finuserfileupload() to
                   15773:  complete the transaction)
                   15774: 
                   15775:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15776:  and /adm/notfound.html if unsuccessful
                   15777: 
                   15778: =item *
                   15779: 
                   15780: clean_filename(): routine for cleaing a filename up for storage in
                   15781:                  userfile space, argument is:
                   15782: 
                   15783:  filename - proposed filename
                   15784: 
                   15785: returns: the new clean filename
                   15786: 
                   15787: =item *
                   15788: 
1.1090    raeburn  15789: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15790: userspace, probably shouldn't be called directly
                   15791: 
                   15792:   docuname: username or courseid of destination for the file
                   15793:   docudom: domain of user/course of destination for the file
                   15794:   formname: same as for userfileupload()
1.1090    raeburn  15795:   fname: filename (including subdirectories) for the file
                   15796:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15797:   allfiles: reference to hash used to store objects found by parser
                   15798:   codebase: reference to hash used for codebases of java objects found by parser
                   15799:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15800:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15801:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15802:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15803:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15804:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15805:   mimetype: reference to scalar to accommodate mime type determined
                   15806:             from File::MMagic if $parser = parse.
1.608     albertel 15807: 
                   15808:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15809:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15810:  was 'overwrite').
                   15811:  
1.608     albertel 15812: 
                   15813: =item *
                   15814: 
                   15815: renameuserfile(): renames an existing userfile to a new name
                   15816: 
                   15817:   Args:
                   15818:    docuname: username or courseid of destination for the file
                   15819:    docudom: domain of user/course of destination for the file
                   15820:    old: current file name (including any subdirs under userfiles)
                   15821:    new: desired file name (including any subdirs under userfiles)
                   15822: 
                   15823: =item *
                   15824: 
                   15825: mkdiruserfile(): creates a directory is a userfiles dir
                   15826: 
                   15827:   Args:
                   15828:    docuname: username or courseid of destination for the file
                   15829:    docudom: domain of user/course of destination for the file
                   15830:    dir: dir to create (including any subdirs under userfiles)
                   15831: 
                   15832: =item *
                   15833: 
                   15834: removeuserfile(): removes a file that exists in userfiles
                   15835: 
                   15836:   Args:
                   15837:    docuname: username or courseid of destination for the file
                   15838:    docudom: domain of user/course of destination for the file
                   15839:    fname: filname to delete (including any subdirs under userfiles)
                   15840: 
                   15841: =item *
                   15842: 
                   15843: removeuploadedurl(): convience function for removeuserfile()
                   15844: 
                   15845:   Args:
                   15846:    url:  a full /uploaded/... url to delete
                   15847: 
1.747     albertel 15848: =item * 
                   15849: 
                   15850: get_portfile_permissions():
                   15851:   Args:
                   15852:     domain: domain of user or course contain the portfolio files
                   15853:     user: name of user or num of course contain the portfolio files
                   15854:   Returns:
                   15855:     hashref of a dump of the proper file_permissions.db
                   15856:    
                   15857: 
                   15858: =item * 
                   15859: 
                   15860: get_access_controls():
                   15861: 
                   15862: Args:
                   15863:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15864:   group: (optional) the group you want the files associated with
                   15865:   file: (optional) the file you want access info on
                   15866: 
                   15867: Returns:
1.749     raeburn  15868:     a hash (keys are file names) of hashes containing
                   15869:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15870:         values are XML containing access control settings (see below) 
1.747     albertel 15871: 
                   15872: Internal notes:
                   15873: 
1.749     raeburn  15874:  access controls are stored in file_permissions.db as key=value pairs.
                   15875:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15876:         where scope -> public,guest,course,group,domains or users.
                   15877:               end -> UNIX time for end of access (0 -> no end date)
                   15878:               start -> UNIX time for start of access
                   15879: 
                   15880:     value -> XML description of access control
                   15881:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15882:             <start></start>
                   15883:             <end></end>
                   15884: 
                   15885:             <password></password>  for scope type = guest
                   15886: 
                   15887:             <domain></domain>     for scope type = course or group
                   15888:             <number></number>
                   15889:             <roles id="">
                   15890:              <role></role>
                   15891:              <access></access>
                   15892:              <section></section>
                   15893:              <group></group>
                   15894:             </roles>
                   15895: 
                   15896:             <dom></dom>         for scope type = domains
                   15897: 
                   15898:             <users>             for scope type = users
                   15899:              <user>
                   15900:               <uname></uname>
                   15901:               <udom></udom>
                   15902:              </user>
                   15903:             </users>
                   15904:            </scope> 
                   15905:               
                   15906:  Access data is also aggregated for each file in an additional key=value pair:
                   15907:  key -> path to file/file_name\0accesscontrol 
                   15908:  value -> reference to hash
                   15909:           hash contains key = value pairs
                   15910:           where key = uniqueID:scope_end_start
                   15911:                 value = UNIX time record was last updated
                   15912: 
                   15913:           Used to improve speed of look-ups of access controls for each file.  
                   15914:  
                   15915:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15916: 
1.1198    raeburn  15917: =item *
                   15918: 
1.749     raeburn  15919: modify_access_controls():
                   15920: 
                   15921: Modifies access controls for a portfolio file
                   15922: Args
                   15923: 1. file name
                   15924: 2. reference to hash of required changes,
                   15925: 3. domain
                   15926: 4. username
                   15927:   where domain,username are the domain of the portfolio owner 
                   15928:   (either a user or a course) 
                   15929: 
                   15930: Returns:
                   15931: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15932: 2. result of deletions ('ok' or 'error', with error message).
                   15933: 3. reference to hash of any new or updated access controls.
                   15934: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15935:    key = integer (inbound ID)
1.1198    raeburn  15936:    value = uniqueID
                   15937: 
                   15938: =item *
                   15939: 
                   15940: get_timebased_id():
                   15941: 
                   15942: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15943: course via the Course Editor (e.g., folders, composite pages, 
                   15944: group bulletin boards).
                   15945: 
                   15946: Args: (first three required; six others optional)
                   15947: 
                   15948: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15949:    docssequence, or name of group
                   15950: 
                   15951: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15952:    e.g., num, boardids
                   15953: 
                   15954: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15955:    file will be named nohist_namespace.db
                   15956: 
                   15957: 4. cdom: domain of course; default is current course domain from %env
                   15958: 
                   15959: 5. cnum: course number; default is current course number from %env
                   15960: 
                   15961: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15962:    unix timestamp to form the suffix, if the plain timestamp is already
                   15963:    in use.  Default is to not do this, but simply increment the unix 
                   15964:    timestamp by 1 until a unique key is obtained.
                   15965: 
                   15966: 7. who: holder of locking key; defaults to user:domain for user.
                   15967: 
                   15968: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15969:    retrying); default is 3.
                   15970: 
                   15971: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15972: 
                   15973: Returns:
                   15974: 
                   15975: 1. suffix obtained (numeric)
                   15976: 
                   15977: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15978: 
                   15979: 3. error: contains (localized) error message if an error occurred.
                   15980: 
1.747     albertel 15981: 
1.608     albertel 15982: =back
                   15983: 
1.243     albertel 15984: =head2 HTTP Helper Routines
                   15985: 
                   15986: =over 4
                   15987: 
1.191     harris41 15988: =item *
                   15989: 
                   15990: escape() : unpack non-word characters into CGI-compatible hex codes
                   15991: 
                   15992: =item *
                   15993: 
                   15994: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15995: 
1.243     albertel 15996: =back
                   15997: 
                   15998: =head1 PRIVATE SUBROUTINES
                   15999: 
                   16000: =head2 Underlying communication routines (Shouldn't call)
                   16001: 
                   16002: =over 4
                   16003: 
                   16004: =item *
                   16005: 
                   16006: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16007: 
                   16008: =item *
                   16009: 
                   16010: reply() : uses subreply to send a message to remote machine, logs all failures
                   16011: 
                   16012: =item *
                   16013: 
                   16014: critical() : passes a critical message to another server; if cannot
                   16015: get through then place message in connection buffer directory and
                   16016: returns con_delayed, if incapable of saving message, returns
                   16017: con_failed
                   16018: 
                   16019: =item *
                   16020: 
                   16021: reconlonc() : tries to reconnect lonc client processes.
                   16022: 
                   16023: =back
                   16024: 
                   16025: =head2 Resource Access Logging
                   16026: 
                   16027: =over 4
                   16028: 
                   16029: =item *
                   16030: 
                   16031: flushcourselogs() : flush (save) buffer logs and access logs
                   16032: 
                   16033: =item *
                   16034: 
                   16035: courselog($what) : save message for course in hash
                   16036: 
                   16037: =item *
                   16038: 
                   16039: courseacclog($what) : save message for course using &courselog().  Perform
                   16040: special processing for specific resource types (problems, exams, quizzes, etc).
                   16041: 
1.191     harris41 16042: =item *
                   16043: 
                   16044: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16045: as a PerlChildExitHandler
1.243     albertel 16046: 
                   16047: =back
                   16048: 
                   16049: =head2 Other
                   16050: 
                   16051: =over 4
                   16052: 
                   16053: =item *
                   16054: 
                   16055: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16056: 
                   16057: =back
                   16058: 
                   16059: =cut
1.877     foxr     16060: 

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