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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1433  ! raeburn     4: # $Id: lonnet.pm,v 1.1432 2020/11/24 14:59:05 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.1405    raeburn    80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1416    raeburn    82:             %managerstab $passwdmin);
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.1406    raeburn   104: use LONCAPA::transliterate;
1.1117    foxr      105: 
1.1090    raeburn   106: use File::Copy;
1.676     albertel  107: 
1.195     www       108: my $readit;
1.1288    damieng   109: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  110: 
1.619     albertel  111: require Exporter;
                    112: 
                    113: our @ISA = qw (Exporter);
                    114: our @EXPORT = qw(%env);
                    115: 
1.449     matthew   116: 
1.1187    raeburn   117: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       118: {
                    119:     my $logid;
1.1187    raeburn   120:     sub write_log {
1.1188    raeburn   121: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   122:         if ($context eq 'course') {
                    123:             if (($cnum eq '') || ($cdom eq '')) {
                    124:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    125:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    126:             }
1.957     raeburn   127:         }
1.1184    raeburn   128: 	$logid ++;
1.957     raeburn   129:         my $now = time();
                    130: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   131:         my $logentry = { 
                    132:                           $id => {
                    133:                                    'exe_uname' => $env{'user.name'},
                    134:                                    'exe_udom'  => $env{'user.domain'},
                    135:                                    'exe_time'  => $now,
                    136:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    137:                                    'delflag'   => $delflag,
                    138:                                    'logentry'  => $storehash,
                    139:                                    'uname'     => $uname,
                    140:                                    'udom'      => $udom,
                    141:                                   }
                    142:                        };
                    143: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       144:     }
                    145: }
1.1       albertel  146: 
1.163     harris41  147: sub logtouch {
                    148:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  149:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  151: 	close $fh;
                    152:     }
                    153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    155: }
                    156: 
1.1       albertel  157: sub logthis {
                    158:     my $message=shift;
                    159:     my $execdir=$perlvar{'lonDaemons'};
                    160:     my $now=time;
                    161:     my $local=localtime($now);
1.1359    raeburn   162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    164: 	print $fh $logstring;
1.448     albertel  165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
                    170: sub logperm {
                    171:     my $message=shift;
                    172:     my $execdir=$perlvar{'lonDaemons'};
                    173:     my $now=time;
                    174:     my $local=localtime($now);
1.1359    raeburn   175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  176: 	print $fh "$now:$message:$local\n";
                    177: 	close($fh);
                    178:     }
1.1       albertel  179:     return 1;
                    180: }
                    181: 
1.850     albertel  182: sub create_connection {
1.853     albertel  183:     my ($hostname,$lonid) = @_;
1.851     albertel  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  185: 				     Type    => SOCK_STREAM,
                    186: 				     Timeout => 10);
                    187:     return 0 if (!$client);
1.1399    raeburn   188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850     albertel  189:     my $result = <$client>;
                    190:     chomp($result);
                    191:     return 1 if ($result eq 'done');
                    192:     return 0;
                    193: }
                    194: 
1.983     raeburn   195: sub get_server_timezone {
                    196:     my ($cnum,$cdom) = @_;
                    197:     my $home=&homeserver($cnum,$cdom);
                    198:     if ($home ne 'no_host') {
                    199:         my $cachetime = 24*3600;
                    200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    201:         if (defined($cached)) {
                    202:             return $timezone;
                    203:         } else {
                    204:             my $timezone = &reply('servertimezone',$home);
                    205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    206:         }
                    207:     }
                    208: }
1.850     albertel  209: 
1.1106    raeburn   210: sub get_server_distarch {
                    211:     my ($lonhost,$ignore_cache) = @_;
                    212:     if (defined($lonhost)) {
                    213:         if (!defined(&hostname($lonhost))) {
                    214:             return;
                    215:         }
                    216:         my $cachetime = 12*3600;
                    217:         if (!$ignore_cache) {
                    218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    219:             if (defined($cached)) {
                    220:                 return $distarch;
                    221:             }
                    222:         }
                    223:         my $rep = &reply('serverdistarch',$lonhost);
                    224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    226:                 $rep eq '') {
                    227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    228:         }
                    229:     }
                    230:     return;
                    231: }
                    232: 
1.1315    raeburn   233: sub get_servercerts_info {
1.1383    raeburn   234:     my ($lonhost,$hostname,$context) = @_;
                    235:     return if ($lonhost eq '');
                    236:     if ($hostname eq '') {
                    237:         $hostname = &hostname($lonhost);
                    238:     }
                    239:     return if ($hostname eq '');
1.1315    raeburn   240:     my ($rep,$uselocal);
1.1388    raeburn   241:     if ($context eq 'install') {
1.1387    raeburn   242:         $uselocal = 1;
                    243:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   244:         $uselocal = 1;
                    245:     }
1.1387    raeburn   246:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   247:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   248:         if ($distro eq '') {
                    249:             $uselocal = 0;
                    250:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   251:             if ($1 < 6) {
                    252:                 $uselocal = 0;
                    253:             }
1.1346    raeburn   254:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    255:             if ($1 < 12) {
                    256:                 $uselocal = 0;
                    257:             }
1.1315    raeburn   258:         }
                    259:     }
                    260:     if ($uselocal) {
1.1383    raeburn   261:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   262:     } else {
                    263:         $rep=&reply('servercerts',$lonhost);
                    264:     }
                    265:     my ($result,%returnhash);
                    266:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    267:         ($rep eq 'unknown_cmd')) {
                    268:         $result = $rep;
                    269:     } else {
                    270:         $result = 'ok';
                    271:         my @pairs=split(/\&/,$rep);
                    272:         foreach my $item (@pairs) {
                    273:             my ($key,$value)=split(/=/,$item,2);
                    274:             my $what = &unescape($key);
                    275:             $returnhash{$what}=&thaw_unescape($value);
                    276:         }
                    277:     }
                    278:     return ($result,\%returnhash);
                    279: }
                    280: 
1.993     raeburn   281: sub get_server_loncaparev {
1.1073    raeburn   282:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   283:     if (defined($lonhost)) {
                    284:         if (!defined(&hostname($lonhost))) {
                    285:             undef($lonhost);
                    286:         }
                    287:     }
                    288:     if (!defined($lonhost)) {
                    289:         if (defined(&domain($dom,'primary'))) {
                    290:             $lonhost=&domain($dom,'primary');
                    291:             if ($lonhost eq 'no_host') {
                    292:                 undef($lonhost);
                    293:             }
                    294:         }
                    295:     }
                    296:     if (defined($lonhost)) {
1.1073    raeburn   297:         my $cachetime = 12*3600;
                    298:         if (!$ignore_cache) {
                    299:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    300:             if (defined($cached)) {
                    301:                 return $loncaparev;
                    302:             }
                    303:         }
                    304:         my ($answer,$loncaparev);
                    305:         my @ids=&current_machine_ids();
                    306:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    307:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   308:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   309:                 $loncaparev = $1;
                    310:             }
                    311:         } else {
                    312:             $answer = &reply('serverloncaparev',$lonhost);
                    313:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    314:                 if ($caller eq 'loncron') {
1.1397    raeburn   315:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   316:                     my $protocol = $protocol{$lonhost};
                    317:                     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn   318:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   319:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   320:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   321:                     unless ($response->is_error()) {
                    322:                         my $content = $response->content;
1.1081    raeburn   323:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   324:                             $loncaparev = $1;
                    325:                         }
                    326:                     }
                    327:                 } else {
                    328:                     $loncaparev = $loncaparevs{$lonhost};
                    329:                 }
1.1081    raeburn   330:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   331:                 $loncaparev = $1;
                    332:             }
1.993     raeburn   333:         }
1.1073    raeburn   334:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   335:     }
                    336: }
                    337: 
1.1074    raeburn   338: sub get_server_homeID {
                    339:     my ($hostname,$ignore_cache,$caller) = @_;
                    340:     unless ($ignore_cache) {
                    341:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    342:         if (defined($cached)) {
                    343:             return $serverhomeID;
                    344:         }
                    345:     }
                    346:     my $cachetime = 12*3600;
                    347:     my $serverhomeID;
                    348:     if ($caller eq 'loncron') { 
                    349:         my @machine_ids = &machine_ids($hostname);
                    350:         foreach my $id (@machine_ids) {
                    351:             my $response = &reply('serverhomeID',$id);
                    352:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    353:                 $serverhomeID = $response;
                    354:                 last;
                    355:             }
                    356:         }
                    357:         if ($serverhomeID eq '') {
                    358:             $serverhomeID = $machine_ids[-1];
                    359:         }
                    360:     } else {
                    361:         $serverhomeID = $serverhomeIDs{$hostname};
                    362:     }
                    363:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    364: }
                    365: 
1.1121    raeburn   366: sub get_remote_globals {
                    367:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   368:     my ($result,%returnhash,%whatneeded);
                    369:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   370:         foreach my $what (sort(keys(%{$whathash}))) {
                    371:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   372:             my ($response,$cached);
1.1121    raeburn   373:             unless ($ignore_cache) {
1.1125    raeburn   374:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   375:             }
                    376:             if (defined($cached)) {
1.1125    raeburn   377:                 $returnhash{$what} = $response;
1.1121    raeburn   378:             } else {
1.1125    raeburn   379:                 $whatneeded{$what} = 1;
1.1121    raeburn   380:             }
                    381:         }
1.1125    raeburn   382:         if (keys(%whatneeded) == 0) {
                    383:             $result = 'ok';
                    384:         } else {
1.1121    raeburn   385:             my $requested = &freeze_escape(\%whatneeded);
                    386:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   387:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    388:                 ($rep eq 'unknown_cmd')) {
                    389:                 $result = $rep;
                    390:             } else {
                    391:                 $result = 'ok';
1.1121    raeburn   392:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   393:                 foreach my $item (@pairs) {
                    394:                     my ($key,$value)=split(/=/,$item,2);
                    395:                     my $what = &unescape($key);
                    396:                     my $hashid = $lonhost.'-'.$what;
                    397:                     $returnhash{$what}=&thaw_unescape($value);
                    398:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   399:                 }
                    400:             }
                    401:         }
                    402:     }
1.1125    raeburn   403:     return ($result,\%returnhash);
1.1121    raeburn   404: }
                    405: 
1.1124    raeburn   406: sub remote_devalidate_cache {
1.1241    raeburn   407:     my ($lonhost,$cachekeys) = @_;
                    408:     my $items;
                    409:     return unless (ref($cachekeys) eq 'ARRAY');
                    410:     my $cachestr = join('&',@{$cachekeys});
                    411:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   412:     return $response;
                    413: }
                    414: 
1.1       albertel  415: # -------------------------------------------------- Non-critical communication
                    416: sub subreply {
                    417:     my ($cmd,$server)=@_;
1.838     albertel  418:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      419:     #
                    420:     #  With loncnew process trimming, there's a timing hole between lonc server
                    421:     #  process exit and the master server picking up the listen on the AF_UNIX
                    422:     #  socket.  In that time interval, a lock file will exist:
                    423: 
                    424:     my $lockfile=$peerfile.".lock";
                    425:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   426: 	sleep(0.1);
1.549     foxr      427:     }
                    428:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      429:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      430:     #
1.550     foxr      431:     #   We'll give the connection a few tries before abandoning it.  If
                    432:     #   connection is not possible, we'll con_lost back to the client.
                    433:     #   
                    434:     my $client;
                    435:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    436: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    437: 				      Type    => SOCK_STREAM,
                    438: 				      Timeout => 10);
1.869     albertel  439: 	if ($client) {
1.550     foxr      440: 	    last;		# Connected!
1.850     albertel  441: 	} else {
1.853     albertel  442: 	    &create_connection(&hostname($server),$server);
1.550     foxr      443: 	}
1.1289    damieng   444:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      445:     }
                    446:     my $answer;
                    447:     if ($client) {
1.704     albertel  448: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      449: 	$answer=<$client>;
                    450: 	if (!$answer) { $answer="con_lost"; }
                    451: 	chomp($answer);
                    452:     } else {
                    453: 	$answer = 'con_lost';	# Failed connection.
                    454:     }
1.1       albertel  455:     return $answer;
                    456: }
                    457: 
                    458: sub reply {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  461:     my $answer=subreply($cmd,$server);
1.65      www       462:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396    raeburn   463:         my $logged = $cmd;
                    464:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    465:             my $subcmd = $1;
                    466:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    467:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    468:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    469:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    470:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    471:                     splice(@rest,2,1,'Hidden');
                    472:                 } elsif ($subcmd eq 'passwd') {
                    473:                     splice(@rest,2,2,('Hidden','Hidden'));
                    474:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    475:                          ($subcmd eq 'autoexportgrades')) {
                    476:                     splice(@rest,3,1,'Hidden');
                    477:                 }
                    478:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    479:             }
                    480:         }
                    481:         &logthis("<font color=\"blue\">WARNING:".
                    482:                  " $logged to $server returned $answer</font>");
1.12      www       483:     }
1.1       albertel  484:     return $answer;
                    485: }
                    486: 
                    487: # ----------------------------------------------------------- Send USR1 to lonc
                    488: 
                    489: sub reconlonc {
1.891     albertel  490:     my ($lonid) = @_;
                    491:     if ($lonid) {
1.1295    raeburn   492:         my $hostname = &hostname($lonid);
1.891     albertel  493: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    494: 	if ($hostname && -e $peerfile) {
                    495: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    496: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    497: 					     Type    => SOCK_STREAM,
                    498: 					     Timeout => 10);
                    499: 	    if ($client) {
                    500: 		print $client ("reset_retries\n");
                    501: 		my $answer=<$client>;
                    502: 		#reset just this one.
                    503: 	    }
                    504: 	}
                    505: 	return;
                    506:     }
                    507: 
1.836     www       508:     &logthis("Trying to reconnect lonc");
1.1       albertel  509:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   510:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  511: 	my $loncpid=<$fh>;
                    512:         chomp($loncpid);
                    513:         if (kill 0 => $loncpid) {
                    514: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    515:             kill USR1 => $loncpid;
                    516:             sleep 1;
1.1295    raeburn   517:         } else {
1.12      www       518: 	    &logthis(
1.672     albertel  519:                "<font color=\"blue\">WARNING:".
1.12      www       520:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  521:         }
                    522:     } else {
1.836     www       523: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  524:     }
                    525: }
                    526: 
                    527: # ------------------------------------------------------ Critical communication
1.12      www       528: 
1.1       albertel  529: sub critical {
                    530:     my ($cmd,$server)=@_;
1.838     albertel  531:     unless (&hostname($server)) {
1.672     albertel  532:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       533:                " Critical message to unknown server ($server)</font>");
                    534:         return 'no_such_host';
                    535:     }
1.1       albertel  536:     my $answer=reply($cmd,$server);
                    537:     if ($answer eq 'con_lost') {
1.1295    raeburn   538: 	&reconlonc($server);
1.589     albertel  539: 	my $answer=reply($cmd,$server);
1.1       albertel  540:         if ($answer eq 'con_lost') {
                    541:             my $now=time;
                    542:             my $middlename=$cmd;
1.5       www       543:             $middlename=substr($middlename,0,16);
1.1       albertel  544:             $middlename=~s/\W//g;
                    545:             my $dfilename=
1.305     www       546:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    547:             $dumpcount++;
1.1       albertel  548:             {
1.448     albertel  549: 		my $dfh;
1.1359    raeburn   550: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  551: 		    print $dfh "$cmd\n"; 
                    552: 		    close($dfh);
                    553: 		}
1.1       albertel  554:             }
1.1288    damieng   555:             sleep 1;
1.1       albertel  556:             my $wcmd='';
                    557:             {
1.448     albertel  558: 		my $dfh;
1.1359    raeburn   559: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  560: 		    $wcmd=<$dfh>; 
                    561: 		    close($dfh);
                    562: 		}
1.1       albertel  563:             }
                    564:             chomp($wcmd);
1.7       www       565:             if ($wcmd eq $cmd) {
1.672     albertel  566: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       567:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  568:                 &logperm("D:$server:$cmd");
                    569: 	        return 'con_delayed';
                    570:             } else {
1.672     albertel  571:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       572:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  573:                 &logperm("F:$server:$cmd");
                    574:                 return 'con_failed';
                    575:             }
                    576:         }
                    577:     }
                    578:     return $answer;
1.405     albertel  579: }
                    580: 
1.755     albertel  581: # ------------------------------------------- check if return value is an error
                    582: 
                    583: sub error {
                    584:     my ($result) = @_;
1.756     albertel  585:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  586: 	if ($2 == 2) { return undef; }
                    587: 	return $1;
                    588:     }
                    589:     return undef;
                    590: }
                    591: 
1.783     albertel  592: sub convert_and_load_session_env {
                    593:     my ($lonidsdir,$handle)=@_;
                    594:     my @profile;
                    595:     {
1.917     albertel  596: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    597: 	if (!$opened) {
1.915     albertel  598: 	    return 0;
                    599: 	}
1.783     albertel  600: 	flock($idf,LOCK_SH);
                    601: 	@profile=<$idf>;
                    602: 	close($idf);
                    603:     }
                    604:     my %temp_env;
                    605:     foreach my $line (@profile) {
1.786     albertel  606: 	if ($line !~ m/=/) {
                    607: 	    return 0;
                    608: 	}
1.783     albertel  609: 	chomp($line);
                    610: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    611: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    612:     }
                    613:     unlink("$lonidsdir/$handle.id");
                    614:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    615: 	    0640)) {
                    616: 	%disk_env = %temp_env;
                    617: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    618: 	untie(%disk_env);
                    619:     }
1.786     albertel  620:     return 1;
1.783     albertel  621: }
                    622: 
1.374     www       623: # ------------------------------------------- Transfer profile into environment
1.780     albertel  624: my $env_loaded;
                    625: sub transfer_profile_to_env {
1.788     albertel  626:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    627:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       628: 
1.720     albertel  629:     if (!defined($lonidsdir)) {
                    630: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    631:     }
                    632:     if (!defined($handle)) {
                    633:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    634:     }
                    635: 
1.786     albertel  636:     my $convert;
                    637:     {
1.917     albertel  638:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    639: 	if (!$opened) {
1.915     albertel  640: 	    return;
                    641: 	}
1.786     albertel  642: 	flock($idf,LOCK_SH);
                    643: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    644: 		&GDBM_READER(),0640)) {
                    645: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    646: 	    untie(%disk_env);
                    647: 	} else {
                    648: 	    $convert = 1;
                    649: 	}
                    650:     }
                    651:     if ($convert) {
                    652: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    653: 	    &logthis("Failed to load session, or convert session.");
                    654: 	}
1.374     www       655:     }
1.783     albertel  656: 
1.786     albertel  657:     my %remove;
1.783     albertel  658:     while ( my $envname = each(%env) ) {
1.433     matthew   659:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    660:             if ($time < time-300) {
1.783     albertel  661:                 $remove{$key}++;
1.433     matthew   662:             }
                    663:         }
                    664:     }
1.783     albertel  665: 
1.619     albertel  666:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  667:     $env_loaded=1;
1.783     albertel  668:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   669:         &delenv($expired_key);
1.374     www       670:     }
1.1       albertel  671: }
                    672: 
1.916     albertel  673: # ---------------------------------------------------- Check for valid session 
                    674: sub check_for_valid_session {
1.1355    raeburn   675:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  676:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   677:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    678:     if ($name eq 'lonDAV') {
                    679:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    680:     } else {
                    681:         $lonidsdir=$r->dir_config('lonIDsDir');
                    682:         if ($name eq '') {
                    683:             $name = 'lonID';
                    684:         }
                    685:     }
                    686:     if ($name eq 'lonID') {
                    687:         $secure = 'lonSID';
1.1337    raeburn   688:         $linkname = 'lonLinkID';
                    689:         $pubname = 'lonPubID';
1.1378    raeburn   690:         if (exists($cookies{$secure})) {
                    691:             $lonid=$cookies{$secure};
                    692:         } elsif (exists($cookies{$name})) {
                    693:             $lonid=$cookies{$name};
1.1400    raeburn   694:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337    raeburn   695:             $lonid=$cookies{$linkname};
1.1378    raeburn   696:         } elsif (exists($cookies{$pubname})) {
                    697:             $lonid=$cookies{$pubname};
1.1337    raeburn   698:         }
1.1378    raeburn   699:     } else {
                    700:         $lonid=$cookies{$name};
1.1337    raeburn   701:     }
1.916     albertel  702:     return undef if (!$lonid);
                    703: 
                    704:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   705:     if (-l "$lonidsdir/$handle.id") {
                    706:         my $link = readlink("$lonidsdir/$handle.id");
                    707:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    708:             $handle = $1;
                    709:         }
1.1155    raeburn   710:     }
1.1355    raeburn   711:     if (!-e "$lonidsdir/$handle.id") {
                    712:         if ((ref($domref)) && ($name eq 'lonID') && 
                    713:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    714:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    715:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    716:                 $$domref = $possudom;
                    717:             }
                    718:         }
                    719:         return undef;
                    720:     }
1.916     albertel  721: 
1.917     albertel  722:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    723:     return undef if (!$opened);
1.916     albertel  724: 
                    725:     flock($idf,LOCK_SH);
                    726:     my %disk_env;
                    727:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    728: 	    &GDBM_READER(),0640)) {
                    729: 	return undef;	
                    730:     }
                    731: 
                    732:     if (!defined($disk_env{'user.name'})
                    733: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   734:         untie(%disk_env);
1.916     albertel  735: 	return undef;
                    736:     }
1.1245    raeburn   737: 
                    738:     if (ref($userhashref) eq 'HASH') {
                    739:         $userhashref->{'name'} = $disk_env{'user.name'};
                    740:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   741:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   742:         if ($userhashref->{'lti'}) {
                    743:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    744:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    745:         }
1.1212    raeburn   746:     }
1.1394    raeburn   747:     untie(%disk_env);
1.1245    raeburn   748: 
1.916     albertel  749:     return $handle;
                    750: }
                    751: 
1.830     albertel  752: sub timed_flock {
                    753:     my ($file,$lock_type) = @_;
                    754:     my $failed=0;
                    755:     eval {
                    756: 	local $SIG{__DIE__}='DEFAULT';
                    757: 	local $SIG{ALRM}=sub {
                    758: 	    $failed=1;
                    759: 	    die("failed lock");
                    760: 	};
                    761: 	alarm(13);
                    762: 	flock($file,$lock_type);
                    763: 	alarm(0);
                    764:     };
                    765:     if ($failed) {
                    766: 	return undef;
                    767:     } else {
                    768: 	return 1;
                    769:     }
                    770: }
                    771: 
1.1392    raeburn   772: sub get_sessionfile_vars {
                    773:     my ($handle,$lonidsdir,$storearr) = @_;
                    774:     my %returnhash;
                    775:     unless (ref($storearr) eq 'ARRAY') {
                    776:         return %returnhash;
                    777:     }
                    778:     if (-l "$lonidsdir/$handle.id") {
                    779:         my $link = readlink("$lonidsdir/$handle.id");
                    780:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    781:             $handle = $1;
                    782:         }
                    783:     }
                    784:     if ((-e "$lonidsdir/$handle.id") &&
                    785:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    786:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    787:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    788:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    789:                 flock($idf,LOCK_SH);
                    790:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    791:                         &GDBM_READER(),0640)) {
                    792:                     foreach my $item (@{$storearr}) {
                    793:                         $returnhash{$item} = $disk_env{$item};
                    794:                     }
                    795:                     untie(%disk_env);
                    796:                 }
                    797:             }
                    798:         }
                    799:     }
                    800:     return %returnhash;
                    801: }
                    802: 
1.5       www       803: # ---------------------------------------------------------- Append Environment
                    804: 
                    805: sub appenv {
1.949     raeburn   806:     my ($newenv,$roles) = @_;
                    807:     if (ref($newenv) eq 'HASH') {
                    808:         foreach my $key (keys(%{$newenv})) {
                    809:             my $refused = 0;
                    810: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    811:                 $refused = 1;
                    812:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   813:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   814:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    815:                         $refused = 0;
                    816:                     }
                    817:                 }
                    818:             }
                    819:             if ($refused) {
                    820:                 &logthis("<font color=\"blue\">WARNING: ".
                    821:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    822:                          .'</font>');
                    823: 	        delete($newenv->{$key});
                    824:             } else {
                    825:                 $env{$key}=$newenv->{$key};
                    826:             }
                    827:         }
1.1376    raeburn   828:         my $lonids = $perlvar{'lonIDsDir'};
                    829:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    830:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    831:             if ($opened
                    832: 	        && &timed_flock($env_file,LOCK_EX)
                    833: 	        &&
                    834: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    835: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    836: 	        while (my ($key,$value) = each(%{$newenv})) {
                    837: 	            $disk_env{$key} = $value;
                    838: 	        }
                    839: 	        untie(%disk_env);
                    840:             }
1.35      www       841:         }
1.191     harris41  842:     }
1.56      www       843:     return 'ok';
                    844: }
                    845: # ----------------------------------------------------- Delete from Environment
                    846: 
                    847: sub delenv {
1.1104    raeburn   848:     my ($delthis,$regexp,$roles) = @_;
                    849:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    850:         my $refused = 1;
                    851:         if (ref($roles) eq 'ARRAY') {
                    852:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    853:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    854:                 $refused = 0;
                    855:             }
                    856:         }
                    857:         if ($refused) {
                    858:             &logthis("<font color=\"blue\">WARNING: ".
                    859:                      "Attempt to delete from environment ".$delthis);
                    860:             return 'error';
                    861:         }
1.56      www       862:     }
1.917     albertel  863:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    864:     if ($opened
1.915     albertel  865: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  866: 	&&
                    867: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    868: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  869: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   870: 	    if ($regexp) {
                    871:                 if ($key=~/^$delthis/) {
                    872:                     delete($env{$key});
                    873:                     delete($disk_env{$key});
                    874:                 } 
                    875:             } else {
                    876:                 if ($key=~/^\Q$delthis\E/) {
                    877: 		    delete($env{$key});
                    878: 		    delete($disk_env{$key});
                    879: 	        }
                    880:             }
1.448     albertel  881: 	}
1.783     albertel  882: 	untie(%disk_env);
1.5       www       883:     }
                    884:     return 'ok';
1.369     albertel  885: }
                    886: 
1.790     albertel  887: sub get_env_multiple {
                    888:     my ($name) = @_;
                    889:     my @values;
                    890:     if (defined($env{$name})) {
                    891:         # exists is it an array
                    892:         if (ref($env{$name})) {
                    893:             @values=@{ $env{$name} };
                    894:         } else {
                    895:             $values[0]=$env{$name};
                    896:         }
                    897:     }
                    898:     return(@values);
                    899: }
                    900: 
1.958     www       901: # ------------------------------------------------------------------- Locking
                    902: 
                    903: sub set_lock {
                    904:     my ($text)=@_;
                    905:     $locknum++;
                    906:     my $id=$$.'-'.$locknum;
                    907:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    908:              'session.lock.'.$id => $text});
                    909:     return $id;
                    910: }
                    911: 
                    912: sub get_locks {
                    913:     my $num=0;
                    914:     my %texts=();
                    915:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    916:        if ($lock=~/\w/) {
                    917:           $num++;
                    918:           $texts{$lock}=$env{'session.lock.'.$lock};
                    919:        }
                    920:    }
                    921:    return ($num,%texts);
                    922: }
                    923: 
                    924: sub remove_lock {
                    925:     my ($id)=@_;
                    926:     my $newlocks='';
                    927:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    928:        if (($lock=~/\w/) && ($lock ne $id)) {
                    929:           $newlocks.=','.$lock;
                    930:        }
                    931:     }
                    932:     &appenv({'session.locks' => $newlocks});
                    933:     &delenv('session.lock.'.$id);
                    934: }
                    935: 
                    936: sub remove_all_locks {
                    937:     my $activelocks=$env{'session.locks'};
                    938:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    939:        if ($lock=~/\w/) {
                    940:           &remove_lock($lock);
                    941:        }
                    942:     }
                    943: }
                    944: 
                    945: 
1.369     albertel  946: # ------------------------------------------ Find out current server userload
                    947: sub userload {
                    948:     my $numusers=0;
                    949:     {
                    950: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    951: 	my $filename;
                    952: 	my $curtime=time;
                    953: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  954: 	    next if ($filename eq '.' || $filename eq '..');
                    955: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   956:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  957: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  958: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  959: 	}
                    960: 	closedir(LONIDS);
                    961:     }
                    962:     my $userloadpercent=0;
                    963:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    964:     if ($maxuserload) {
1.371     albertel  965: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  966:     }
1.372     albertel  967:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  968:     return $userloadpercent;
1.283     www       969: }
                    970: 
1.1       albertel  971: # ------------------------------ Find server with least workload from spare.tab
1.11      www       972: 
1.1       albertel  973: sub spareserver {
1.1083    raeburn   974:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  975:     my $spare_server;
1.370     albertel  976:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  977:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    978:                                                      :  $userloadpercent;
1.1083    raeburn   979:     my ($uint_dom,$remotesessions);
                    980:     if (($udom ne '') && (&domain($udom) ne '')) {
                    981:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    982:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    983:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    984:         $remotesessions = $udomdefaults{'remotesessions'};
                    985:     }
1.1123    raeburn   986:     my $spareshash = &this_host_spares($udom);
                    987:     if (ref($spareshash) eq 'HASH') {
                    988:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    989:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   990:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    991:                                              $try_server));
1.1123    raeburn   992: 	        ($spare_server, $lowest_load) =
                    993: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    994:             }
1.1083    raeburn   995:         }
1.784     albertel  996: 
1.1123    raeburn   997:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    998: 
                    999:         if (!$found_server) {
                   1000:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1001: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1002:                     next unless (&spare_can_host($udom,$uint_dom,
                   1003:                                                  $remotesessions,$try_server));
1.1123    raeburn  1004: 	            ($spare_server, $lowest_load) =
                   1005: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1006:                 }
                   1007: 	    }
                   1008:         }
1.784     albertel 1009:     }
                   1010: 
                   1011:     if (!$want_server_name) {
1.1001    raeburn  1012:         if (defined($spare_server)) {
                   1013:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1014:             if (defined($hostname)) {
1.1397    raeburn  1015:                 my $protocol = 'http';
                   1016:                 if ($protocol{$spare_server} eq 'https') {
                   1017:                     $protocol = $protocol{$spare_server};
                   1018:                 }
1.1001    raeburn  1019: 	        $spare_server = $protocol.'://'.$hostname;
                   1020:             }
                   1021:         }
1.784     albertel 1022:     }
                   1023:     return $spare_server;
                   1024: }
                   1025: 
                   1026: sub compare_server_load {
1.1253    raeburn  1027:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1028: 
                   1029:     if ($required) {
                   1030:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1031:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1032:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1033:         if (($major eq '' && $minor eq '') ||
                   1034:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1035:             return ($spare_server,$lowest_load);
                   1036:         }
                   1037:     }
1.784     albertel 1038: 
                   1039:     my $loadans     = &reply('load',    $try_server);
                   1040:     my $userloadans = &reply('userload',$try_server);
                   1041: 
                   1042:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1043: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1044:     }
                   1045: 
                   1046:     my $load;
                   1047:     if ($loadans =~ /\d/) {
                   1048: 	if ($userloadans =~ /\d/) {
                   1049: 	    #both are numbers, pick the bigger one
                   1050: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1051: 		                              : $userloadans;
1.411     albertel 1052: 	} else {
1.784     albertel 1053: 	    $load = $loadans;
1.411     albertel 1054: 	}
1.784     albertel 1055:     } else {
                   1056: 	$load = $userloadans;
                   1057:     }
                   1058: 
                   1059:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1060: 	$spare_server = $try_server;
                   1061: 	$lowest_load  = $load;
1.370     albertel 1062:     }
1.784     albertel 1063:     return ($spare_server,$lowest_load);
1.202     matthew  1064: }
1.914     albertel 1065: 
                   1066: # --------------------------- ask offload servers if user already has a session
                   1067: sub find_existing_session {
                   1068:     my ($udom,$uname) = @_;
1.1123    raeburn  1069:     my $spareshash = &this_host_spares($udom);
                   1070:     if (ref($spareshash) eq 'HASH') {
                   1071:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1072:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1073:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1074:             }
                   1075:         }
                   1076:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1077:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1078:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1079:             }
                   1080:         }
1.914     albertel 1081:     }
                   1082:     return;
                   1083: }
                   1084: 
1.1411    raeburn  1085: sub delusersession {
                   1086:     my ($lonid,$udom,$uname) = @_;
                   1087:     my $uprimary_id = &domain($udom,'primary');
                   1088:     my $uintdom = &internet_dom($uprimary_id);
                   1089:     my $intdom = &internet_dom($lonid);
                   1090:     my $serverhomedom = &host_domain($lonid);
                   1091:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1092:         return &reply(join(':','delusersession',
                   1093:                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1094:     }
                   1095:     return;
                   1096: }
                   1097: 
1.1389    raeburn  1098: # check if user's browser sent load balancer cookie and server still has session
                   1099: # and is not overloaded.
                   1100: sub check_for_balancer_cookie {
                   1101:     my ($r,$update_mtime) = @_;
                   1102:     my ($otherserver,$cookie);
                   1103:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1104:     if (exists($cookies{'balanceID'})) {
                   1105:         my $balid = $cookies{'balanceID'};
                   1106:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1107:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1108:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1109:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1110:                 my ($possudom,$possuname) = ($1,$2);
                   1111:                 my $has_session = 0;
                   1112:                 if ((&domain($possudom) ne '') &&
                   1113:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1114:                     my $try_server;
                   1115:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1116:                     if ($opened) {
                   1117:                         flock($idf,LOCK_SH);
                   1118:                         while (my $line = <$idf>) {
                   1119:                             chomp($line);
                   1120:                             if (&hostname($line) ne '') {
                   1121:                                 $try_server = $line;
                   1122:                                 last;
                   1123:                             }
                   1124:                         }
                   1125:                         close($idf);
                   1126:                         if (($try_server) &&
                   1127:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1128:                             my $lowest_load = 30000;
                   1129:                             ($otherserver,$lowest_load) =
                   1130:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1131:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1132:                                 $has_session = 1;
                   1133:                             } else {
                   1134:                                 undef($otherserver);
                   1135:                             }
                   1136:                         }
                   1137:                     }
                   1138:                 }
                   1139:                 if ($has_session) {
                   1140:                     if ($update_mtime) {
                   1141:                         my $atime = my $mtime = time;
                   1142:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1143:                     }
                   1144:                 } else {
                   1145:                     unlink("$balancedir/$cookie.id");
                   1146:                 }
                   1147:             }
                   1148:         }
                   1149:     }
                   1150:     return ($otherserver,$cookie);
                   1151: }
                   1152: 
1.1431    raeburn  1153: sub updatebalcookie {
                   1154:     my ($cookie,$balancer,$lastentry)=@_;
                   1155:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1156:         my ($udom,$uname) = ($1,$2);
                   1157:         my $uprimary_id = &domain($udom,'primary');
                   1158:         my $uintdom = &internet_dom($uprimary_id);
                   1159:         my $intdom = &internet_dom($balancer);
                   1160:         my $serverhomedom = &host_domain($balancer);
                   1161:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1162:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1163:         }
                   1164:     }
                   1165:     return;
                   1166: }
                   1167: 
1.1389    raeburn  1168: sub delbalcookie {
                   1169:     my ($cookie,$balancer) =@_;
                   1170:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1171:         my ($udom,$uname) = ($1,$2);
                   1172:         my $uprimary_id = &domain($udom,'primary');
                   1173:         my $uintdom = &internet_dom($uprimary_id);
                   1174:         my $intdom = &internet_dom($balancer);
                   1175:         my $serverhomedom = &host_domain($balancer);
                   1176:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431    raeburn  1177:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389    raeburn  1178:         }
                   1179:     }
                   1180: }
                   1181: 
1.914     albertel 1182: # -------------------------------- ask if server already has a session for user
                   1183: sub has_user_session {
                   1184:     my ($lonid,$udom,$uname) = @_;
                   1185:     my $result = &reply(join(':','userhassession',
                   1186: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1187:     return 1 if ($result eq 'ok');
                   1188: 
                   1189:     return 0;
                   1190: }
                   1191: 
1.1076    raeburn  1192: # --------- determine least loaded server in a user's domain which allows login
                   1193: 
                   1194: sub choose_server {
1.1259    raeburn  1195:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1196:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1197:     my %servers = &get_servers($udom);
1.1076    raeburn  1198:     my $lowest_load = 30000;
1.1259    raeburn  1199:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1200:     if ($skiploadbal) {
                   1201:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1202:         unless (defined($cached)) {
                   1203:             my $cachetime = 60*60*24;
                   1204:             my %domconfig =
                   1205:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1206:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1207:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1208:                                            $cachetime);
                   1209:             }
                   1210:         }
                   1211:     }
1.1076    raeburn  1212:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1213:         if ($skiploadbal) {
                   1214:             if (ref($balancers) eq 'HASH') {
                   1215:                 next if (exists($balancers->{$lonhost}));
                   1216:             }
1.1389    raeburn  1217:         }
1.1115    raeburn  1218:         my $loginvia;
                   1219:         if ($checkloginvia) {
                   1220:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1221:             if ($loginvia) {
                   1222:                 my ($server,$path) = split(/:/,$loginvia);
                   1223:                 ($login_host, $lowest_load) =
1.1253    raeburn  1224:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1225:                 if ($login_host eq $server) {
                   1226:                     $portal_path = $path;
1.1151    raeburn  1227:                     $isredirect = 1;
1.1116    raeburn  1228:                 }
                   1229:             } else {
                   1230:                 ($login_host, $lowest_load) =
1.1253    raeburn  1231:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1232:                 if ($login_host eq $lonhost) {
                   1233:                     $portal_path = '';
1.1151    raeburn  1234:                     $isredirect = ''; 
1.1116    raeburn  1235:                 }
                   1236:             }
                   1237:         } else {
1.1076    raeburn  1238:             ($login_host, $lowest_load) =
1.1253    raeburn  1239:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1240:         }
                   1241:     }
                   1242:     if ($login_host ne '') {
1.1116    raeburn  1243:         $hostname = &hostname($login_host);
1.1076    raeburn  1244:     }
1.1331    raeburn  1245:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1246: }
                   1247: 
1.1420    raeburn  1248: sub get_course_sessions {
                   1249:     my ($cnum,$cdom,$lastactivity) = @_;
                   1250:     my %servers = &internet_dom_servers($cdom);
                   1251:     my %returnhash;
                   1252:     foreach my $server (sort(keys(%servers))) {
                   1253:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1254:         my @pairs=split(/\&/,$rep);
                   1255:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1256:             foreach my $item (@pairs) {
                   1257:                 my ($key,$value)=split(/=/,$item,2);
                   1258:                 $key = &unescape($key);
                   1259:                 next if ($key =~ /^error: 2 /);
                   1260:                 if (exists($returnhash{$key})) {
                   1261:                     next if ($value < $returnhash{$key});
                   1262:                 }
                   1263:                 $returnhash{$key}=$value;
                   1264:             }
                   1265:         }
                   1266:     }
                   1267:     return %returnhash;
                   1268: }
                   1269: 
1.202     matthew  1270: # --------------------------------------------- Try to change a user's password
                   1271: 
                   1272: sub changepass {
1.799     raeburn  1273:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1274:     $currentpass = &escape($currentpass);
                   1275:     $newpass     = &escape($newpass);
1.1030    raeburn  1276:     my $lonhost = $perlvar{'lonHostID'};
                   1277:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1278: 		       $server);
                   1279:     if (! $answer) {
                   1280: 	&logthis("No reply on password change request to $server ".
                   1281: 		 "by $uname in domain $udom.");
                   1282:     } elsif ($answer =~ "^ok") {
                   1283:         &logthis("$uname in $udom successfully changed their password ".
                   1284: 		 "on $server.");
                   1285:     } elsif ($answer =~ "^pwchange_failure") {
                   1286: 	&logthis("$uname in $udom was unable to change their password ".
                   1287: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1288: 		 "or pwchange");
                   1289:     } elsif ($answer =~ "^non_authorized") {
                   1290:         &logthis("$uname in $udom did not get their password correct when ".
                   1291: 		 "attempting to change it on $server.");
                   1292:     } elsif ($answer =~ "^auth_mode_error") {
                   1293:         &logthis("$uname in $udom attempted to change their password despite ".
                   1294: 		 "not being locally or internally authenticated on $server.");
                   1295:     } elsif ($answer =~ "^unknown_user") {
                   1296:         &logthis("$uname in $udom attempted to change their password ".
                   1297: 		 "on $server but were unable to because $server is not ".
                   1298: 		 "their home server.");
                   1299:     } elsif ($answer =~ "^refused") {
                   1300: 	&logthis("$server refused to change $uname in $udom password because ".
                   1301: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1302:     } elsif ($answer =~ "invalid_client") {
                   1303:         &logthis("$server refused to change $uname in $udom password because ".
                   1304:                  "it was a reset by e-mail originating from an invalid server.");
1.1408    raeburn  1305:     } elsif ($answer =~ "^prioruse") {
                   1306:        &logthis("$server refused to change $uname in $udom password because ".
                   1307:                 "the password had been used before");
1.202     matthew  1308:     }
                   1309:     return $answer;
1.1       albertel 1310: }
                   1311: 
1.169     harris41 1312: # ----------------------- Try to determine user's current authentication scheme
                   1313: 
                   1314: sub queryauthenticate {
                   1315:     my ($uname,$udom)=@_;
1.456     albertel 1316:     my $uhome=&homeserver($uname,$udom);
                   1317:     if (!$uhome) {
                   1318: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1319: 	return 'no_host';
                   1320:     }
                   1321:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1322:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1323: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1324:     }
1.456     albertel 1325:     return $answer;
1.169     harris41 1326: }
                   1327: 
1.1       albertel 1328: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1329: 
1.1       albertel 1330: sub authenticate {
1.1073    raeburn  1331:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1332:     $upass=&escape($upass);
                   1333:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1334:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1335:     my $newhome;
1.836     www      1336:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1337: # Maybe the machine was offline and only re-appeared again recently?
                   1338:         &reconlonc();
                   1339: # One more
1.952     raeburn  1340: 	$uhome=&homeserver($uname,$udom,1);
                   1341:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1342:             if (defined(&domain($udom,'primary'))) {
                   1343:                 $newhome=&domain($udom,'primary');
                   1344:             }
                   1345:             if ($newhome ne '') {
                   1346:                 $uhome = $newhome;
                   1347:             }
                   1348:         }
1.836     www      1349: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1350: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1351: 	    return 'no_host';
                   1352:         }
1.1       albertel 1353:     }
1.1073    raeburn  1354:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1355:     if ($answer eq 'authorized') {
1.952     raeburn  1356:         if ($newhome) {
                   1357:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1358:             return 'no_account_on_host'; 
                   1359:         } else {
                   1360:             &logthis("User $uname at $udom authorized by $uhome");
                   1361:             return $uhome;
                   1362:         }
1.471     albertel 1363:     }
                   1364:     if ($answer eq 'non_authorized') {
                   1365: 	&logthis("User $uname at $udom rejected by $uhome");
                   1366: 	return 'no_host'; 
1.9       www      1367:     }
1.471     albertel 1368:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1369:     return 'no_host';
                   1370: }
                   1371: 
1.1073    raeburn  1372: sub can_host_session {
1.1074    raeburn  1373:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1374:     my $canhost = 1;
1.1074    raeburn  1375:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1376:     if (ref($remotesessions) eq 'HASH') {
                   1377:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1378:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1379:                 $canhost = 0;
                   1380:             } else {
                   1381:                 $canhost = 1;
                   1382:             }
                   1383:         }
                   1384:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1385:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1386:                 $canhost = 1;
                   1387:             } else {
                   1388:                 $canhost = 0;
                   1389:             }
                   1390:         }
                   1391:         if ($canhost) {
                   1392:             if ($remotesessions->{'version'} ne '') {
                   1393:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1394:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1395:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1396:                         my $major = $1;
                   1397:                         my $minor = $2;
                   1398:                         if (($major < $reqmajor ) ||
                   1399:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1400:                             $canhost = 0;
                   1401:                         }
                   1402:                     } else {
                   1403:                         $canhost = 0;
                   1404:                     }
                   1405:                 }
                   1406:             }
                   1407:         }
                   1408:     }
                   1409:     if ($canhost) {
                   1410:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1411:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1412:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1413:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1414:                 if (($uint_dom ne '') && 
                   1415:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1416:                     $canhost = 0;
                   1417:                 } else {
                   1418:                     $canhost = 1;
                   1419:                 }
                   1420:             }
                   1421:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1422:                 if (($uint_dom ne '') && 
                   1423:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1424:                     $canhost = 1;
                   1425:                 } else {
                   1426:                     $canhost = 0;
                   1427:                 }
                   1428:             }
                   1429:         }
                   1430:     }
                   1431:     return $canhost;
                   1432: }
                   1433: 
1.1083    raeburn  1434: sub spare_can_host {
                   1435:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1436:     my $canhost=1;
1.1279    raeburn  1437:     my $try_server_hostname = &hostname($try_server);
                   1438:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1439:     my $serverhomedom = &host_domain($serverhomeID);
                   1440:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1441:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1442:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1443:             $canhost = 0;
                   1444:         }
                   1445:     }
                   1446:     if (($canhost) && ($uint_dom)) {
                   1447:         my @intdoms;
                   1448:         my $internet_names = &get_internet_names($try_server);
                   1449:         if (ref($internet_names) eq 'ARRAY') {
                   1450:             @intdoms = @{$internet_names};
                   1451:         }
                   1452:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1453:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1454:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1455:                                          $remotesessions,
                   1456:                                          $defdomdefaults{'hostedsessions'});
                   1457:         }
1.1083    raeburn  1458:     }
                   1459:     return $canhost;
                   1460: }
                   1461: 
1.1123    raeburn  1462: sub this_host_spares {
                   1463:     my ($dom) = @_;
1.1126    raeburn  1464:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1465:     my @hosts = &current_machine_ids();
                   1466:     foreach my $lonhost (@hosts) {
                   1467:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1468:             $dom_in_use = $dom;
                   1469:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1470:             last;
                   1471:         }
                   1472:     }
1.1126    raeburn  1473:     if ($dom_in_use ne '') {
                   1474:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1475:     }
                   1476:     if (ref($result) ne 'HASH') {
                   1477:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1478:         $dom_in_use = &host_domain($lonhost_in_use);
                   1479:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1480:         if (ref($result) ne 'HASH') {
                   1481:             $result = \%spareid;
                   1482:         }
                   1483:     }
                   1484:     return $result;
                   1485: }
                   1486: 
                   1487: sub spares_for_offload  {
                   1488:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1489:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1490:     if (defined($cached)) {
                   1491:         return $result;
                   1492:     } else {
1.1126    raeburn  1493:         my $cachetime = 60*60*24;
                   1494:         my %domconfig =
                   1495:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1496:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1497:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1498:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1499:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1500:                 }
                   1501:             }
                   1502:         }
                   1503:     }
1.1126    raeburn  1504:     return;
1.1123    raeburn  1505: }
                   1506: 
1.1129    raeburn  1507: sub get_lonbalancer_config {
                   1508:     my ($servers) = @_;
                   1509:     my ($currbalancer,$currtargets);
                   1510:     if (ref($servers) eq 'HASH') {
                   1511:         foreach my $server (keys(%{$servers})) {
                   1512:             my %what = (
                   1513:                          spareid => 1,
                   1514:                          perlvar => 1,
                   1515:                        );
                   1516:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1517:             if ($result eq 'ok') {
                   1518:                 if (ref($returnhash) eq 'HASH') {
                   1519:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1520:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1521:                             $currbalancer = $server;
                   1522:                             $currtargets = {};
                   1523:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1524:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1525:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1526:                                 }
                   1527:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1528:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1529:                                 }
                   1530:                             }
                   1531:                             last;
                   1532:                         }
                   1533:                     }
                   1534:                 }
                   1535:             }
                   1536:         }
                   1537:     }
                   1538:     return ($currbalancer,$currtargets);
                   1539: }
                   1540: 
                   1541: sub check_loadbalancing {
1.1331    raeburn  1542:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1543:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1544:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1545:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1546:     my @hosts = &current_machine_ids();
1.1129    raeburn  1547:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1548:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1549:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1550:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1551:     my $domneedscache;
1.1129    raeburn  1552:     my $cachetime = 60*60*24;
                   1553: 
                   1554:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1555:         $dom_in_use = $udom;
                   1556:         $homeintdom = 1;
                   1557:     } else {
                   1558:         $dom_in_use = $serverhomedom;
                   1559:     }
                   1560:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1561:     unless (defined($cached)) {
                   1562:         my %domconfig =
                   1563:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1564:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1565:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1566:         } else {
                   1567:             $domneedscache = $dom_in_use;
1.1129    raeburn  1568:         }
                   1569:     }
                   1570:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1571:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1572:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1573:         if ($is_balancer) {
                   1574:             if (ref($currrules) eq 'HASH') {
                   1575:                 if ($homeintdom) {
                   1576:                     if ($uname ne '') {
                   1577:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1578:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1579:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1580:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1581:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1582:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1583:                             }
                   1584:                         }
                   1585:                         if ($rule_in_effect eq '') {
                   1586:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1587:                             if ($userenv{'inststatus'} ne '') {
                   1588:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1589:                                 my ($othertitle,$usertypes,$types) =
                   1590:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1591:                                 if (ref($types) eq 'ARRAY') {
                   1592:                                     foreach my $type (@{$types}) {
                   1593:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1594:                                             if (exists($currrules->{$type})) {
                   1595:                                                 $rule_in_effect = $currrules->{$type};
                   1596:                                             }
                   1597:                                         }
                   1598:                                     }
                   1599:                                 }
                   1600:                             } else {
                   1601:                                 if (exists($currrules->{'default'})) {
                   1602:                                     $rule_in_effect = $currrules->{'default'};
                   1603:                                 }
                   1604:                             }
                   1605:                         }
                   1606:                     } else {
                   1607:                         if (exists($currrules->{'default'})) {
                   1608:                             $rule_in_effect = $currrules->{'default'};
                   1609:                         }
                   1610:                     }
                   1611:                 } else {
                   1612:                     if ($currrules->{'_LC_external'} ne '') {
                   1613:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1614:                     }
                   1615:                 }
                   1616:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1617:                                                        $uname,$udom);
                   1618:             }
                   1619:         }
                   1620:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1621:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1622:         unless (defined($cached)) {
                   1623:             my %domconfig =
                   1624:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1625:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1626:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1627:             } else {
                   1628:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1629:             }
                   1630:         }
                   1631:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1632:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1633:                 &check_balancer_result($result,@hosts);
                   1634:             if ($is_balancer) {
1.1129    raeburn  1635:                 if (ref($currrules) eq 'HASH') {
                   1636:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1637:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1638:                     }
                   1639:                 }
                   1640:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1641:                                                        $uname,$udom);
                   1642:             }
                   1643:         } else {
                   1644:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1645:                 $is_balancer = 1;
                   1646:                 $offloadto = &this_host_spares($dom_in_use);
                   1647:             }
1.1307    raeburn  1648:             unless (defined($cached)) {
                   1649:                 $domneedscache = $serverhomedom;
                   1650:             }
1.1129    raeburn  1651:         }
                   1652:     } else {
                   1653:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1654:             $is_balancer = 1;
                   1655:             $offloadto = &this_host_spares($dom_in_use);
                   1656:         }
1.1307    raeburn  1657:         unless (defined($cached)) {
                   1658:             $domneedscache = $serverhomedom;
                   1659:         }
                   1660:     }
                   1661:     if ($domneedscache) {
                   1662:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1663:     }
1.1430    raeburn  1664:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176    raeburn  1665:         my $lowest_load = 30000;
                   1666:         if (ref($offloadto) eq 'HASH') {
                   1667:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1668:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1669:                     ($otherserver,$lowest_load) =
                   1670:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1671:                 }
1.1129    raeburn  1672:             }
1.1176    raeburn  1673:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1674: 
1.1176    raeburn  1675:             if (!$found_server) {
                   1676:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1677:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1678:                         ($otherserver,$lowest_load) =
                   1679:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1680:                     }
                   1681:                 }
                   1682:             }
                   1683:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1684:             if (@{$offloadto} == 1) {
                   1685:                 $otherserver = $offloadto->[0];
                   1686:             } elsif (@{$offloadto} > 1) {
                   1687:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1688:                     ($otherserver,$lowest_load) =
                   1689:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1690:                 }
                   1691:             }
                   1692:         }
1.1331    raeburn  1693:         unless ($caller eq 'login') {
                   1694:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1695:                 $is_balancer = 0;
                   1696:                 if ($uname ne '' && $udom ne '') {
                   1697:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1698:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1699:                                  'user.loadbalcheck.time' => time});
                   1700:                     }
1.1176    raeburn  1701:                 }
1.1129    raeburn  1702:             }
                   1703:         }
1.1430    raeburn  1704:     }
                   1705:     if (($is_balancer) && (!$homeintdom)) {
                   1706:         undef($setcookie);
1.1129    raeburn  1707:     }
1.1391    raeburn  1708:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1709: }
                   1710: 
1.1191    raeburn  1711: sub check_balancer_result {
                   1712:     my ($result,@hosts) = @_;
1.1391    raeburn  1713:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1714:     if (ref($result) eq 'HASH') {
                   1715:         if ($result->{'lonhost'} ne '') {
                   1716:             my $currbalancer = $result->{'lonhost'};
                   1717:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1718:                 $is_balancer = 1;
                   1719:                 $currtargets = $result->{'targets'};
                   1720:                 $currrules = $result->{'rules'};
                   1721:             }
1.1391    raeburn  1722:             $dom_balancers = $currbalancer;
1.1191    raeburn  1723:         } else {
1.1391    raeburn  1724:             if (keys(%{$result})) {
                   1725:                 foreach my $key (keys(%{$result})) {
                   1726:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1727:                         (ref($result->{$key}) eq 'HASH')) {
                   1728:                         $is_balancer = 1;
                   1729:                         $currrules = $result->{$key}{'rules'};
                   1730:                         $currtargets = $result->{$key}{'targets'};
                   1731:                         $setcookie = $result->{$key}{'cookie'};
                   1732:                         last;
                   1733:                     }
1.1191    raeburn  1734:                 }
1.1391    raeburn  1735:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1736:             }
                   1737:         }
                   1738:     }
1.1391    raeburn  1739:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1740: }
                   1741: 
1.1129    raeburn  1742: sub get_loadbalancer_targets {
                   1743:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1744:     my $offloadto;
1.1175    raeburn  1745:     if ($rule_in_effect eq 'none') {
                   1746:         return [$perlvar{'lonHostID'}];
                   1747:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1748:         $offloadto = $currtargets;
                   1749:     } else {
                   1750:         if ($rule_in_effect eq 'homeserver') {
                   1751:             my $homeserver = &homeserver($uname,$udom);
                   1752:             if ($homeserver ne 'no_host') {
                   1753:                 $offloadto = [$homeserver];
                   1754:             }
                   1755:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1756:             my %domconfig =
                   1757:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1758:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1759:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1760:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1761:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1762:                     }
                   1763:                 }
                   1764:             } else {
1.1178    raeburn  1765:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1766:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1767:                 if (&hostname($remotebalancer) ne '') {
                   1768:                     $offloadto = [$remotebalancer];
                   1769:                 }
                   1770:             }
                   1771:         } elsif (&hostname($rule_in_effect) ne '') {
                   1772:             $offloadto = [$rule_in_effect];
                   1773:         }
                   1774:     }
                   1775:     return $offloadto;
                   1776: }
                   1777: 
1.1127    raeburn  1778: sub internet_dom_servers {
                   1779:     my ($dom) = @_;
                   1780:     my (%uniqservers,%servers);
                   1781:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1782:     my @machinedoms = &machine_domains($primaryserver);
                   1783:     foreach my $mdom (@machinedoms) {
                   1784:         my %currservers = %servers;
                   1785:         my %server = &get_servers($mdom);
                   1786:         %servers = (%currservers,%server);
                   1787:     }
                   1788:     my %by_hostname;
                   1789:     foreach my $id (keys(%servers)) {
                   1790:         push(@{$by_hostname{$servers{$id}}},$id);
                   1791:     }
                   1792:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1793:         if (@{$by_hostname{$hostname}} > 1) {
                   1794:             my $match = 0;
                   1795:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1796:                 if (&host_domain($id) eq $dom) {
                   1797:                     $uniqservers{$id} = $hostname;
                   1798:                     $match = 1;
                   1799:                 }
                   1800:             }
                   1801:             unless ($match) {
                   1802:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1803:             }
                   1804:         } else {
                   1805:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1806:         }
                   1807:     }
                   1808:     return %uniqservers;
                   1809: }
                   1810: 
1.1347    raeburn  1811: sub trusted_domains {
                   1812:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1813:     my ($trusted,$untrusted);
1.1347    raeburn  1814:     if (&domain($calldom) eq '') {
1.1349    raeburn  1815:         return ($trusted,$untrusted);
1.1347    raeburn  1816:     }
1.1395    raeburn  1817:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1818:         return ($trusted,$untrusted);
1.1347    raeburn  1819:     }
                   1820:     my $callprimary = &domain($calldom,'primary');
                   1821:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1822:     if ($intcalldom eq '') {
1.1349    raeburn  1823:         return ($trusted,$untrusted);
1.1347    raeburn  1824:     }
                   1825: 
                   1826:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1827:     unless (defined($cached)) {
                   1828:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1829:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1830:         $trustconfig = $domconfig{'trust'};
                   1831:     }
                   1832:     if (ref($trustconfig)) {
                   1833:         my (%possexc,%possinc,@allexc,@allinc); 
                   1834:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1835:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1836:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1837:             }
                   1838:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1839:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1840:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1841:             }
                   1842:         }
                   1843:         if (keys(%possexc)) {
                   1844:             if (keys(%possinc)) {
                   1845:                 foreach my $key (sort(keys(%possexc))) {
                   1846:                     next if ($key eq $intcalldom);
                   1847:                     unless ($possinc{$key}) {
                   1848:                         push(@allexc,$key);
                   1849:                     }
                   1850:                 }
                   1851:             } else {
                   1852:                 @allexc = sort(keys(%possexc));
                   1853:             }
                   1854:         }
                   1855:         if (keys(%possinc)) {
                   1856:             $possinc{$intcalldom} = 1;
                   1857:             @allinc = sort(keys(%possinc));
                   1858:         }
                   1859:         if ((@allexc > 0) || (@allinc > 0)) {
                   1860:             my %doms_by_intdom;
                   1861:             my %allintdoms = &all_host_intdom();
                   1862:             my %alldoms = &all_host_domain();
                   1863:             foreach my $key (%allintdoms) {
                   1864:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1865:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1866:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1867:                     }
                   1868:                 } else {
                   1869:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1870:                 }
                   1871:             }
                   1872:             foreach my $exc (@allexc) {
                   1873:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1874:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1875:                 }
                   1876:             }
                   1877:             foreach my $inc (@allinc) {
                   1878:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1879:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1880:                 }
                   1881:             }
                   1882:         }
                   1883:     }
1.1349    raeburn  1884:     return ($trusted,$untrusted);
1.1347    raeburn  1885: }
                   1886: 
                   1887: sub will_trust {
                   1888:     my ($cmdtype,$domain,$possdom) = @_;
                   1889:     return 1 if ($domain eq $possdom);
                   1890:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1891:     my $willtrust; 
                   1892:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1893:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1894:             $willtrust = 1;
                   1895:         }
                   1896:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1897:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1898:             $willtrust = 1;
                   1899:         }
                   1900:     } else {
                   1901:         $willtrust = 1;
                   1902:     }
                   1903:     return $willtrust;
                   1904: }
                   1905: 
1.1       albertel 1906: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1907: 
1.599     albertel 1908: my %homecache;
1.1       albertel 1909: sub homeserver {
1.230     stredwic 1910:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1911:     my $index="$uname:$udom";
1.426     albertel 1912: 
1.599     albertel 1913:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1914: 
                   1915:     my %servers = &get_servers($udom,'library');
                   1916:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1917:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1918: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1919: 
                   1920: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1921: 	if ($answer eq 'found') {
                   1922: 	    delete($badServerCache{$tryserver}); 
                   1923: 	    return $homecache{$index}=$tryserver;
                   1924: 	} elsif ($answer eq 'no_host') {
                   1925: 	    $badServerCache{$tryserver}=1;
                   1926: 	}
1.1       albertel 1927:     }    
                   1928:     return 'no_host';
1.70      www      1929: }
                   1930: 
1.1300    raeburn  1931: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1932: 
                   1933: sub idget {
1.1300    raeburn  1934:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1935:     my %returnhash=();
1.1300    raeburn  1936:     my @ids=(); 
                   1937:     if (ref($idsref) eq 'ARRAY') {
                   1938:         @ids = @{$idsref};
                   1939:     } else {
                   1940:         return %returnhash; 
                   1941:     }
                   1942:     if ($namespace eq '') {
                   1943:         $namespace = 'ids';
                   1944:     }
1.70      www      1945:     
1.841     albertel 1946:     my %servers = &get_servers($udom,'library');
                   1947:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1948: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1949: 	if ($namespace eq 'ids') {
                   1950: 	    $idlist=~tr/A-Z/a-z/;
                   1951: 	}
                   1952: 	my $reply;
                   1953: 	if ($namespace eq 'ids') {
                   1954: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1955: 	} else {
                   1956: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1957: 	}
1.841     albertel 1958: 	my @answer=();
                   1959: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1960: 	    @answer=split(/\&/,$reply);
                   1961: 	}                    ;
                   1962: 	my $i;
                   1963: 	for ($i=0;$i<=$#ids;$i++) {
                   1964: 	    if ($answer[$i]) {
1.1299    raeburn  1965: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1966: 	    }
1.841     albertel 1967: 	}
1.1300    raeburn  1968:     }
1.70      www      1969:     return %returnhash;
                   1970: }
                   1971: 
                   1972: # ------------------------------------- Find the IDs behind a list of usernames
                   1973: 
                   1974: sub idrget {
                   1975:     my ($udom,@unames)=@_;
                   1976:     my %returnhash=();
1.800     albertel 1977:     foreach my $uname (@unames) {
                   1978:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1979:     }
1.70      www      1980:     return %returnhash;
                   1981: }
                   1982: 
1.1300    raeburn  1983: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1984: 
                   1985: sub idput {
1.1300    raeburn  1986:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1987:     my %servers=();
1.1300    raeburn  1988:     my %ids=();
                   1989:     my %byid = ();
                   1990:     if (ref($idsref) eq 'HASH') {
                   1991:         %ids=%{$idsref};
                   1992:     }
                   1993:     if ($namespace eq '') {
                   1994:         $namespace = 'ids'; 
                   1995:     }
1.800     albertel 1996:     foreach my $uname (keys(%ids)) {
                   1997: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1998:         if ($uhom eq '') {
                   1999:             $uhom=&homeserver($uname,$udom);
                   2000:         }
1.70      www      2001:         if ($uhom ne 'no_host') {
1.800     albertel 2002:             my $esc_unam=&escape($uname);
1.1300    raeburn  2003:             if ($namespace eq 'ids') {
                   2004:                 my $id=&escape($ids{$uname});
                   2005:                 $id=~tr/A-Z/a-z/;
                   2006:                 my $esc_unam=&escape($uname);
                   2007:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      2008:             } else {
1.1300    raeburn  2009:                 my @currids = split(/,/,$ids{$uname});
                   2010:                 foreach my $id (@currids) {
                   2011:                     $byid{$uhom}{$id} .= $uname.',';
                   2012:                 }
                   2013:             }
                   2014:         }
                   2015:     }
                   2016:     if ($namespace eq 'clickers') {
                   2017:         foreach my $server (keys(%byid)) {
                   2018:             if (ref($byid{$server}) eq 'HASH') {
                   2019:                 foreach my $id (keys(%{$byid{$server}})) {
                   2020:                     $byid{$server} =~ s/,$//;
                   2021:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   2022:                 }
1.70      www      2023:             }
                   2024:         }
1.191     harris41 2025:     }
1.800     albertel 2026:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2027:         $servers{$server} =~ s/\&$//;
                   2028:         if ($namespace eq 'ids') {     
                   2029:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   2030:         } else {
                   2031:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   2032:         }
1.191     harris41 2033:     }
1.344     www      2034: }
                   2035: 
1.1300    raeburn  2036: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  2037: 
                   2038: sub iddel {
1.1300    raeburn  2039:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  2040:     my %result=();
1.1300    raeburn  2041:     my %ids=();
                   2042:     my %byid = ();
                   2043:     if (ref($idshashref) eq 'HASH') {
                   2044:         %ids=%{$idshashref};
                   2045:     } else {
1.1231    raeburn  2046:         return %result;
                   2047:     }
1.1300    raeburn  2048:     if ($namespace eq '') {
                   2049:         $namespace = 'ids';
                   2050:     }
1.1231    raeburn  2051:     my %servers=();
1.1300    raeburn  2052:     while (my ($id,$unamestr) = each(%ids)) {
                   2053:         if ($namespace eq 'ids') {
                   2054:             my $uhom = $uhome;
                   2055:             if ($uhom eq '') { 
                   2056:                 $uhom=&homeserver($unamestr,$udom);
                   2057:             }
                   2058:             if ($uhom ne 'no_host') {
                   2059:                 $servers{$uhom}.='&'.&escape($id);
                   2060:             }
                   2061:          } else {
                   2062:             my @curritems = split(/,/,$ids{$id});
                   2063:             foreach my $uname (@curritems) {
                   2064:                 my $uhom = $uhome;
                   2065:                 if ($uhom eq '') {
                   2066:                     $uhom=&homeserver($uname,$udom);
                   2067:                 }
                   2068:                 if ($uhom ne 'no_host') { 
                   2069:                     $byid{$uhom}{$id} .= $uname.',';
                   2070:                 }
                   2071:             }
1.1231    raeburn  2072:         }
1.1300    raeburn  2073:     }
                   2074:     if ($namespace eq 'clickers') {
                   2075:         foreach my $server (keys(%byid)) {
                   2076:             if (ref($byid{$server}) eq 'HASH') {
                   2077:                 foreach my $id (keys(%{$byid{$server}})) {
                   2078:                     $byid{$server}{$id} =~ s/,$//;
                   2079:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2080:                 }
1.1231    raeburn  2081:             }
                   2082:         }
                   2083:     }
                   2084:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2085:         $servers{$server} =~ s/\&$//;
                   2086:         if ($namespace eq 'ids') {
                   2087:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2088:         } elsif ($namespace eq 'clickers') {
                   2089:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2090:         }
1.1231    raeburn  2091:     }
                   2092:     return %result;
                   2093: }
                   2094: 
1.1300    raeburn  2095: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2096: 
                   2097: sub updateclickers {
                   2098:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2099:     my %clickers;
                   2100:     if (ref($idshashref) eq 'HASH') {
                   2101:         %clickers=%{$idshashref};
                   2102:     } else {
                   2103:         return;
                   2104:     }
                   2105:     my $items='';
                   2106:     foreach my $item (keys(%clickers)) {
                   2107:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2108:     }
                   2109:     $items=~s/\&$//;
                   2110:     my $request = "updateclickers:$udom:$action:$items";
                   2111:     if ($critical) {
                   2112:         return &critical($request,$uhome);
                   2113:     } else {
                   2114:         return &reply($request,$uhome);
                   2115:     }
                   2116: }
                   2117: 
1.1023    raeburn  2118: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2119: sub dump_dom {
1.1165    droeschl 2120:     my ($namespace, $udom, $regexp) = @_;
                   2121: 
                   2122:     $udom ||= $env{'user.domain'};
                   2123: 
                   2124:     return () unless $udom;
                   2125: 
                   2126:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2127: }
                   2128: 
1.1023    raeburn  2129: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2130: 
                   2131: sub get_dom {
1.860     raeburn  2132:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2133:     return if ($udom eq 'public');
1.806     raeburn  2134:     my $items='';
                   2135:     foreach my $item (@$storearr) {
                   2136:         $items.=&escape($item).'&';
                   2137:     }
                   2138:     $items=~s/\&$//;
1.860     raeburn  2139:     if (!$udom) {
                   2140:         $udom=$env{'user.domain'};
1.1267    raeburn  2141:         return if ($udom eq 'public');
1.860     raeburn  2142:         if (defined(&domain($udom,'primary'))) {
                   2143:             $uhome=&domain($udom,'primary');
                   2144:         } else {
1.874     albertel 2145:             undef($uhome);
1.860     raeburn  2146:         }
                   2147:     } else {
                   2148:         if (!$uhome) {
                   2149:             if (defined(&domain($udom,'primary'))) {
                   2150:                 $uhome=&domain($udom,'primary');
                   2151:             }
                   2152:         }
                   2153:     }
                   2154:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2155:         my $rep;
                   2156:         if ($namespace =~ /^enc/) {
                   2157:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2158:         } else {
                   2159:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2160:         }
1.866     raeburn  2161:         my %returnhash;
1.875     albertel 2162:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2163:             return %returnhash;
                   2164:         }
1.806     raeburn  2165:         my @pairs=split(/\&/,$rep);
                   2166:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2167:             return @pairs;
                   2168:         }
                   2169:         my $i=0;
                   2170:         foreach my $item (@$storearr) {
                   2171:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2172:             $i++;
                   2173:         }
                   2174:         return %returnhash;
                   2175:     } else {
1.880     banghart 2176:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2177:     }
                   2178: }
                   2179: 
                   2180: # -------------------------------------------- put items in domain db files 
                   2181: 
                   2182: sub put_dom {
1.860     raeburn  2183:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2184:     if (!$udom) {
                   2185:         $udom=$env{'user.domain'};
                   2186:         if (defined(&domain($udom,'primary'))) {
                   2187:             $uhome=&domain($udom,'primary');
                   2188:         } else {
1.874     albertel 2189:             undef($uhome);
1.860     raeburn  2190:         }
                   2191:     } else {
                   2192:         if (!$uhome) {
                   2193:             if (defined(&domain($udom,'primary'))) {
                   2194:                 $uhome=&domain($udom,'primary');
                   2195:             }
                   2196:         }
                   2197:     } 
                   2198:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2199:         my $items='';
                   2200:         foreach my $item (keys(%$storehash)) {
                   2201:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2202:         }
                   2203:         $items=~s/\&$//;
1.1344    raeburn  2204:         if ($namespace =~ /^enc/) {
                   2205:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2206:         } else {
                   2207:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2208:         }
1.806     raeburn  2209:     } else {
1.860     raeburn  2210:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2211:     }
                   2212: }
                   2213: 
1.1023    raeburn  2214: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2215: sub newput_dom {
1.1023    raeburn  2216:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2217:     my $result;
                   2218:     if (!$udom) {
                   2219:         $udom=$env{'user.domain'};
                   2220:     }
1.1023    raeburn  2221:     if ($udom) {
                   2222:         my $uname = &get_domainconfiguser($udom);
                   2223:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2224:     }
                   2225:     return $result;
                   2226: }
                   2227: 
1.1023    raeburn  2228: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2229: sub del_dom {
1.1023    raeburn  2230:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2231:     if (ref($storearr) eq 'ARRAY') {
                   2232:         if (!$udom) {
                   2233:             $udom=$env{'user.domain'};
                   2234:         }
1.1023    raeburn  2235:         if ($udom) {
                   2236:             my $uname = &get_domainconfiguser($udom); 
                   2237:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2238:         }
                   2239:     }
                   2240: }
                   2241: 
1.1023    raeburn  2242: # ----------------------------------construct domainconfig user for a domain 
                   2243: sub get_domainconfiguser {
                   2244:     my ($udom) = @_;
                   2245:     return $udom.'-domainconfig';
                   2246: }
                   2247: 
1.837     raeburn  2248: sub retrieve_inst_usertypes {
                   2249:     my ($udom) = @_;
                   2250:     my (%returnhash,@order);
1.989     raeburn  2251:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2252:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2253:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2254:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2255:     } else {
                   2256:         if (defined(&domain($udom,'primary'))) {
                   2257:             my $uhome=&domain($udom,'primary');
                   2258:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2259:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2260:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2261:                 return (\%returnhash,\@order);
                   2262:             }
                   2263:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2264:             my @pairs=split(/\&/,$hashitems);
                   2265:             foreach my $item (@pairs) {
                   2266:                 my ($key,$value)=split(/=/,$item,2);
                   2267:                 $key = &unescape($key);
                   2268:                 next if ($key =~ /^error: 2 /);
                   2269:                 $returnhash{$key}=&thaw_unescape($value);
                   2270:             }
                   2271:             my @esc_order = split(/\&/,$orderitems);
                   2272:             foreach my $item (@esc_order) {
                   2273:                 push(@order,&unescape($item));
                   2274:             }
                   2275:         } else {
1.1256    raeburn  2276:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2277:         }
1.1256    raeburn  2278:         return (\%returnhash,\@order);
1.837     raeburn  2279:     }
                   2280: }
                   2281: 
1.868     raeburn  2282: sub is_domainimage {
                   2283:     my ($url) = @_;
1.1306    raeburn  2284:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2285:         if (&domain($1) ne '') {
                   2286:             return '1';
                   2287:         }
                   2288:     }
                   2289:     return;
                   2290: }
                   2291: 
1.899     raeburn  2292: sub inst_directory_query {
                   2293:     my ($srch) = @_;
                   2294:     my $udom = $srch->{'srchdomain'};
                   2295:     my %results;
                   2296:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2297:     my $outcome;
1.899     raeburn  2298:     if ($homeserver ne '') {
1.1357    raeburn  2299:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2300:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2301:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2302:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2303:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2304:                     (($major == 2) && ($minor < 12))) {
                   2305:                     return;
                   2306:                 }
                   2307:             }
                   2308:         }
1.904     albertel 2309: 	my $queryid=&reply("querysend:instdirsearch:".
                   2310: 			   &escape($srch->{'srchby'}).':'.
                   2311: 			   &escape($srch->{'srchterm'}).':'.
                   2312: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2313: 	my $host=&hostname($homeserver);
                   2314: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2315: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2316: 	    return;
                   2317: 	}
                   2318: 	my $response = &get_query_reply($queryid);
                   2319: 	my $maxtries = 5;
                   2320: 	my $tries = 1;
                   2321: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2322: 	    $response = &get_query_reply($queryid);
                   2323: 	    $tries ++;
                   2324: 	}
                   2325: 
                   2326:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2327:             if ($response eq 'unavailable') {
                   2328:                 $outcome = $response;
                   2329:             } else {
                   2330:                 $outcome = 'ok';
                   2331:                 my @matches = split(/\n/,$response);
                   2332:                 foreach my $match (@matches) {
                   2333:                     my ($key,$value) = split(/=/,$match);
                   2334:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2335:                 }
1.899     raeburn  2336:             }
                   2337:         }
                   2338:     }
1.909     raeburn  2339:     return ($outcome,%results);
1.899     raeburn  2340: }
                   2341: 
                   2342: sub usersearch {
                   2343:     my ($srch) = @_;
                   2344:     my $dom = $srch->{'srchdomain'};
                   2345:     my %results;
                   2346:     my %libserv = &all_library();
                   2347:     my $query = 'usersearch';
                   2348:     foreach my $tryserver (keys(%libserv)) {
                   2349:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2350:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2351:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2352:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2353:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2354:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2355:                              (($major == 2) && ($minor < 12)));
                   2356:                 }
                   2357:             }
1.899     raeburn  2358:             my $host=&hostname($tryserver);
                   2359:             my $queryid=
1.911     raeburn  2360:                 &reply("querysend:".&escape($query).':'.
                   2361:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2362:                        &escape($srch->{'srchtype'}).':'.
                   2363:                        &escape($srch->{'srchterm'}),$tryserver);
                   2364:             if ($queryid !~/^\Q$host\E\_/) {
                   2365:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2366:                 next;
1.899     raeburn  2367:             }
                   2368:             my $reply = &get_query_reply($queryid);
                   2369:             my $maxtries = 1;
                   2370:             my $tries = 1;
                   2371:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2372:                 $reply = &get_query_reply($queryid);
                   2373:                 $tries ++;
                   2374:             }
                   2375:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2376:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2377:             } else {
1.911     raeburn  2378:                 my @matches;
                   2379:                 if ($reply =~ /\n/) {
                   2380:                     @matches = split(/\n/,$reply);
                   2381:                 } else {
                   2382:                     @matches = split(/\&/,$reply);
                   2383:                 }
1.899     raeburn  2384:                 foreach my $match (@matches) {
                   2385:                     my ($uname,$udom,%userhash);
1.911     raeburn  2386:                     foreach my $entry (split(/:/,$match)) {
                   2387:                         my ($key,$value) =
                   2388:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2389:                         $userhash{$key} = $value;
                   2390:                         if ($key eq 'username') {
                   2391:                             $uname = $value;
                   2392:                         } elsif ($key eq 'domain') {
                   2393:                             $udom = $value;
1.911     raeburn  2394:                         }
1.899     raeburn  2395:                     }
                   2396:                     $results{$uname.':'.$udom} = \%userhash;
                   2397:                 }
                   2398:             }
                   2399:         }
                   2400:     }
                   2401:     return %results;
                   2402: }
                   2403: 
1.912     raeburn  2404: sub get_instuser {
                   2405:     my ($udom,$uname,$id) = @_;
                   2406:     my $homeserver = &domain($udom,'primary');
                   2407:     my ($outcome,%results);
                   2408:     if ($homeserver ne '') {
                   2409:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2410:                            &escape($id).':'.&escape($udom),$homeserver);
                   2411:         my $host=&hostname($homeserver);
                   2412:         if ($queryid !~/^\Q$host\E\_/) {
                   2413:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2414:             return;
                   2415:         }
                   2416:         my $response = &get_query_reply($queryid);
                   2417:         my $maxtries = 5;
                   2418:         my $tries = 1;
                   2419:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2420:             $response = &get_query_reply($queryid);
                   2421:             $tries ++;
                   2422:         }
                   2423:         if (!&error($response) && $response ne 'refused') {
                   2424:             if ($response eq 'unavailable') {
                   2425:                 $outcome = $response;
                   2426:             } else {
                   2427:                 $outcome = 'ok';
                   2428:                 my @matches = split(/\n/,$response);
                   2429:                 foreach my $match (@matches) {
                   2430:                     my ($key,$value) = split(/=/,$match);
                   2431:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2432:                 }
                   2433:             }
                   2434:         }
                   2435:     }
                   2436:     my %userinfo;
                   2437:     if (ref($results{$uname}) eq 'HASH') {
                   2438:         %userinfo = %{$results{$uname}};
                   2439:     } 
                   2440:     return ($outcome,%userinfo);
                   2441: }
                   2442: 
1.1290    raeburn  2443: sub get_multiple_instusers {
                   2444:     my ($udom,$users,$caller) = @_;
                   2445:     my ($outcome,$results);
                   2446:     if (ref($users) eq 'HASH') {
                   2447:         my $count = keys(%{$users}); 
                   2448:         my $requested = &freeze_escape($users);
                   2449:         my $homeserver = &domain($udom,'primary');
                   2450:         if ($homeserver ne '') {
                   2451:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2452:             my $host=&hostname($homeserver);
                   2453:             if ($queryid !~/^\Q$host\E\_/) {
                   2454:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2455:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2456:                 return ($outcome,$results);
                   2457:             }
                   2458:             my $response = &get_query_reply($queryid);
                   2459:             my $maxtries = 5;
                   2460:             if ($count > 100) {
                   2461:                 $maxtries = 1+int($count/20);
                   2462:             }
                   2463:             my $tries = 1;
                   2464:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2465:                 $response = &get_query_reply($queryid);
                   2466:                 $tries ++;
                   2467:             }
                   2468:             if ($response eq '') {
                   2469:                 $results = {};
                   2470:                 foreach my $key (keys(%{$users})) {
                   2471:                     my ($uname,$id);
                   2472:                     if ($caller eq 'id') {
                   2473:                         $id = $key;
                   2474:                     } else {
                   2475:                         $uname = $key;
                   2476:                     }
                   2477:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2478:                     $outcome = $resp;
1.1290    raeburn  2479:                     if ($resp eq 'ok') {
                   2480:                         %{$results} = (%{$results}, %info);
                   2481:                     } else {
                   2482:                         last;
                   2483:                     }
                   2484:                 }
                   2485:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2486:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2487:                     $outcome = $response;
                   2488:                 } else {
1.1291    raeburn  2489:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2490:                     if ($outcome eq 'ok') {
                   2491:                         $results = &thaw_unescape($userdata); 
                   2492:                     }
                   2493:                 }
                   2494:             }
                   2495:         }
                   2496:     }
                   2497:     return ($outcome,$results);
                   2498: }
                   2499: 
1.912     raeburn  2500: sub inst_rulecheck {
1.923     raeburn  2501:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2502:     my %returnhash;
                   2503:     if ($udom ne '') {
                   2504:         if (ref($rules) eq 'ARRAY') {
                   2505:             @{$rules} = map {&escape($_);} (@{$rules});
                   2506:             my $rulestr = join(':',@{$rules});
                   2507:             my $homeserver=&domain($udom,'primary');
                   2508:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2509:                 my $response;
                   2510:                 if ($item eq 'username') {                
                   2511:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2512:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2513:                                               $homeserver));
1.923     raeburn  2514:                 } elsif ($item eq 'id') {
                   2515:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2516:                                               ':'.&escape($id).':'.$rulestr,
                   2517:                                               $homeserver));
1.945     raeburn  2518:                 } elsif ($item eq 'selfcreate') {
                   2519:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2520:                                                &escape($udom).':'.&escape($uname).
                   2521:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2522:                 }
1.912     raeburn  2523:                 if ($response ne 'refused') {
                   2524:                     my @pairs=split(/\&/,$response);
                   2525:                     foreach my $item (@pairs) {
                   2526:                         my ($key,$value)=split(/=/,$item,2);
                   2527:                         $key = &unescape($key);
                   2528:                         next if ($key =~ /^error: 2 /);
                   2529:                         $returnhash{$key}=&thaw_unescape($value);
                   2530:                     }
                   2531:                 }
                   2532:             }
                   2533:         }
                   2534:     }
                   2535:     return %returnhash;
                   2536: }
                   2537: 
                   2538: sub inst_userrules {
1.923     raeburn  2539:     my ($udom,$check) = @_;
1.912     raeburn  2540:     my (%ruleshash,@ruleorder);
                   2541:     if ($udom ne '') {
                   2542:         my $homeserver=&domain($udom,'primary');
                   2543:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2544:             my $response;
                   2545:             if ($check eq 'id') {
                   2546:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2547:                                  $homeserver);
1.943     raeburn  2548:             } elsif ($check eq 'email') {
                   2549:                 $response=&reply('instemailrules:'.&escape($udom),
                   2550:                                  $homeserver);
1.923     raeburn  2551:             } else {
                   2552:                 $response=&reply('instuserrules:'.&escape($udom),
                   2553:                                  $homeserver);
                   2554:             }
1.912     raeburn  2555:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2556:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2557:                 ($response ne 'no_such_host')) {
                   2558:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2559:                 my @pairs=split(/\&/,$hashitems);
                   2560:                 foreach my $item (@pairs) {
                   2561:                     my ($key,$value)=split(/=/,$item,2);
                   2562:                     $key = &unescape($key);
                   2563:                     next if ($key =~ /^error: 2 /);
                   2564:                     $ruleshash{$key}=&thaw_unescape($value);
                   2565:                 }
                   2566:                 my @esc_order = split(/\&/,$orderitems);
                   2567:                 foreach my $item (@esc_order) {
                   2568:                     push(@ruleorder,&unescape($item));
                   2569:                 }
                   2570:             }
                   2571:         }
                   2572:     }
                   2573:     return (\%ruleshash,\@ruleorder);
                   2574: }
                   2575: 
1.976     raeburn  2576: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2577: 
                   2578: sub get_domain_defaults {
1.1240    raeburn  2579:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2580:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2581:     my $cachetime = 60*60*24;
1.1240    raeburn  2582:     unless ($ignore_cache) {
                   2583:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2584:         if (defined($cached)) {
                   2585:             if (ref($result) eq 'HASH') {
                   2586:                 return %{$result};
                   2587:             }
1.943     raeburn  2588:         }
                   2589:     }
                   2590:     my %domdefaults;
                   2591:     my %domconfig =
1.989     raeburn  2592:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2593:                                   'requestcourses','inststatus',
1.1183    raeburn  2594:                                   'coursedefaults','usersessions',
1.1258    raeburn  2595:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2596:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2597:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2598:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2599:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2600:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2601:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2602:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2603:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2604:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2605:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2606:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2607:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2608:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2609:     } else {
                   2610:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2611:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2612:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2613:     }
1.976     raeburn  2614:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2615:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2616:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2617:         } else {
                   2618:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2619:         }
1.1177    raeburn  2620:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2621:         foreach my $item (@usertools) {
                   2622:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2623:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2624:             }
                   2625:         }
1.1229    raeburn  2626:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2627:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2628:         }
1.976     raeburn  2629:     }
1.985     raeburn  2630:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2631:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2632:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2633:         }
                   2634:     }
1.1183    raeburn  2635:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2636:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2637:     }
1.989     raeburn  2638:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2639:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2640:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2641:         }
                   2642:     }
1.1047    raeburn  2643:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2644:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2645:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2646:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2647:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2648:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2649:         }
1.1254    raeburn  2650:         foreach my $type (@coursetypes) {
                   2651:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2652:                 unless ($type eq 'community') {
                   2653:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2654:                 }
                   2655:             }
                   2656:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2657:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2658:             }
1.1277    raeburn  2659:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2660:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2661:                     $domdefaults{$type.'postsubtimeout'} = 
                   2662:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2663:                 }
                   2664:             }
1.1230    raeburn  2665:         }
1.1286    raeburn  2666:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2667:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2668:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2669:                 if (@clonecodes) {
                   2670:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2671:                 }
                   2672:             }
                   2673:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2674:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2675:         }
1.1356    raeburn  2676:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2677:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2678:         } 
1.1047    raeburn  2679:     }
1.1073    raeburn  2680:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2681:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2682:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2683:         }
                   2684:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2685:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2686:         }
1.1279    raeburn  2687:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2688:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2689:         }
1.1073    raeburn  2690:     }
1.1254    raeburn  2691:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2692:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2693:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2694:                             'approval','limit');
                   2695:             foreach my $type (@coursetypes) {
                   2696:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2697:                     my @mgrdc = ();
                   2698:                     foreach my $item (@settings) {
                   2699:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2700:                             push(@mgrdc,$item);
                   2701:                         }
                   2702:                     }
                   2703:                     if (@mgrdc) {
                   2704:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2705:                     }
                   2706:                 }
                   2707:             }
                   2708:         }
                   2709:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2710:             foreach my $type (@coursetypes) {
                   2711:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2712:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2713:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2714:                     }
                   2715:                 }
                   2716:             }
                   2717:         }
                   2718:     }
1.1258    raeburn  2719:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2720:         $domdefaults{'catauth'} = 'std';
                   2721:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2722:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2723:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2724:         }
                   2725:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2726:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2727:         }
                   2728:     }
1.1315    raeburn  2729:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2730:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2731:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2732:         }
1.1338    raeburn  2733:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2734:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2735:         }
                   2736:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2737:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2738:         }
                   2739:     }
1.1320    raeburn  2740:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2741:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2742:         foreach my $prefix (@prefixes) {
                   2743:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2744:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2745:             }
                   2746:         }
                   2747:     }
1.1314    raeburn  2748:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2749:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2750:     }
1.1332    raeburn  2751:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2752:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2753:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2754:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2755:         }
                   2756:     }
1.1219    raeburn  2757:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2758:     return %domdefaults;
                   2759: }
                   2760: 
1.1412    raeburn  2761: sub get_dom_cats {
                   2762:     my ($dom) = @_;
                   2763:     return unless (&domain($dom));
                   2764:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2765:     unless (defined($cached)) {
                   2766:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2767:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2768:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2769:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2770:             } else {
                   2771:                 $cats = {};
                   2772:             }
                   2773:         } else {
                   2774:             $cats = {};
                   2775:         }
                   2776:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2777:     }
1.1413    raeburn  2778:     return $cats;
                   2779: }
                   2780: 
                   2781: sub get_dom_instcats {
                   2782:     my ($dom) = @_;
                   2783:     return unless (&domain($dom));
                   2784:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2785:     unless (defined($cached)) {
                   2786:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2787:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2788:         if ($totcodes > 0) {
                   2789:             my $caller = 'global';
                   2790:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2791:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2792:                 $instcats = {
                   2793:                                 codes => \%codes,
                   2794:                                 codetitles => \@codetitles,
                   2795:                                 cat_titles => \%cat_titles,
                   2796:                                 cat_order => \%cat_order,
                   2797:                             };
                   2798:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2799:             }
                   2800:         }
                   2801:     }
                   2802:     return $instcats;
                   2803: }
                   2804: 
                   2805: sub retrieve_instcodes {
                   2806:     my ($coursecodes,$dom) = @_;
                   2807:     my $totcodes;
                   2808:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2809:     foreach my $course (keys(%courses)) {
                   2810:         if (ref($courses{$course}) eq 'HASH') {
                   2811:             if ($courses{$course}{'inst_code'} ne '') {
                   2812:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2813:                 $totcodes ++;
                   2814:             }
                   2815:         }
                   2816:     }
                   2817:     return $totcodes;
1.1412    raeburn  2818: }
                   2819: 
1.1311    raeburn  2820: sub course_portal_url {
                   2821:     my ($cnum,$cdom) = @_;
                   2822:     my $chome = &homeserver($cnum,$cdom);
                   2823:     my $hostname = &hostname($chome);
                   2824:     my $protocol = $protocol{$chome};
                   2825:     $protocol = 'http' if ($protocol ne 'https');
                   2826:     my %domdefaults = &get_domain_defaults($cdom);
                   2827:     my $firsturl;
                   2828:     if ($domdefaults{'portal_def'}) {
                   2829:         $firsturl = $domdefaults{'portal_def'};
                   2830:     } else {
                   2831:         $firsturl = $protocol.'://'.$hostname;
                   2832:     }
                   2833:     return $firsturl;
                   2834: }
                   2835: 
1.1407    raeburn  2836: # --------------------------------------------- Get domain config for passwords
                   2837: 
                   2838: sub get_passwdconf {
                   2839:     my ($dom) = @_;
                   2840:     my (%passwdconf,$gotconf,$lookup);
                   2841:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2842:     if (defined($cached)) {
                   2843:         if (ref($result) eq 'HASH') {
                   2844:             %passwdconf = %{$result};
                   2845:             $gotconf = 1;
                   2846:         }
                   2847:     }
                   2848:     unless ($gotconf) {
                   2849:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2850:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2851:             %passwdconf = %{$domconfig{'passwords'}};
                   2852:         }
                   2853:         my $cachetime = 24*60*60;
                   2854:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2855:     }
                   2856:     return %passwdconf;
                   2857: }
                   2858: 
1.344     www      2859: # --------------------------------------------------- Assign a key to a student
                   2860: 
                   2861: sub assign_access_key {
1.364     www      2862: #
                   2863: # a valid key looks like uname:udom#comments
                   2864: # comments are being appended
                   2865: #
1.498     www      2866:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2867:     $kdom=
1.620     albertel 2868:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2869:     $knum=
1.620     albertel 2870:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2871:     $cdom=
1.620     albertel 2872:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2873:     $cnum=
1.620     albertel 2874:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2875:     $udom=$env{'user.name'} unless (defined($udom));
                   2876:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2877:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2878:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2879:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2880:                                                   # assigned to this person
                   2881:                                                   # - this should not happen,
1.345     www      2882:                                                   # unless something went wrong
                   2883:                                                   # the first time around
                   2884: # ready to assign
1.364     www      2885:         $logentry=$1.'; '.$logentry;
1.496     www      2886:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2887:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2888: # key now belongs to user
1.346     www      2889: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2890:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2891:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2892:                 return 'ok';
                   2893:             } else {
                   2894:                 return 
                   2895:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2896: 	    }
                   2897:         } else {
                   2898:             return 'error: Could not assign key, try again later.';
                   2899:         }
1.364     www      2900:     } elsif (!$existing{$ckey}) {
1.345     www      2901: # the key does not exist
                   2902: 	return 'error: The key does not exist';
                   2903:     } else {
                   2904: # the key is somebody else's
                   2905: 	return 'error: The key is already in use';
                   2906:     }
1.344     www      2907: }
                   2908: 
1.364     www      2909: # ------------------------------------------ put an additional comment on a key
                   2910: 
                   2911: sub comment_access_key {
                   2912: #
                   2913: # a valid key looks like uname:udom#comments
                   2914: # comments are being appended
                   2915: #
                   2916:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2917:     $cdom=
1.620     albertel 2918:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2919:     $cnum=
1.620     albertel 2920:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2921:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2922:     if ($existing{$ckey}) {
                   2923:         $existing{$ckey}.='; '.$logentry;
                   2924: # ready to assign
1.367     www      2925:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2926:                                                  $cdom,$cnum) eq 'ok') {
                   2927: 	    return 'ok';
                   2928:         } else {
                   2929: 	    return 'error: Count not store comment.';
                   2930:         }
                   2931:     } else {
                   2932: # the key does not exist
                   2933: 	return 'error: The key does not exist';
                   2934:     }
                   2935: }
                   2936: 
1.344     www      2937: # ------------------------------------------------------ Generate a set of keys
                   2938: 
                   2939: sub generate_access_keys {
1.364     www      2940:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2941:     $cdom=
1.620     albertel 2942:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2943:     $cnum=
1.620     albertel 2944:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2945:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2946:     unless (($cdom) && ($cnum)) { return 0; }
                   2947:     if ($number>10000) { return 0; }
                   2948:     sleep(2); # make sure don't get same seed twice
                   2949:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2950:     my $total=0;
                   2951:     for (my $i=1;$i<=$number;$i++) {
                   2952:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2953:                   sprintf("%lx",int(100000*rand)).'-'.
                   2954:                   sprintf("%lx",int(100000*rand));
                   2955:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2956:        $newkey=~s/0/h/g; # and also 0 and O
                   2957:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2958:        if ($existing{$newkey}) {
                   2959:            $i--;
                   2960:        } else {
1.364     www      2961: 	  if (&put('accesskeys',
                   2962:               { $newkey => '# generated '.localtime().
1.620     albertel 2963:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2964:                            '; '.$logentry },
                   2965: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2966:               $total++;
                   2967: 	  }
                   2968:        }
                   2969:     }
1.620     albertel 2970:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2971:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2972:     return $total;
                   2973: }
                   2974: 
                   2975: # ------------------------------------------------------- Validate an accesskey
                   2976: 
                   2977: sub validate_access_key {
                   2978:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2979:     $cdom=
1.620     albertel 2980:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2981:     $cnum=
1.620     albertel 2982:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2983:     $udom=$env{'user.domain'} unless (defined($udom));
                   2984:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2985:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2986:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2987: }
                   2988: 
                   2989: # ------------------------------------- Find the section of student in a course
1.652     albertel 2990: sub devalidate_getsection_cache {
                   2991:     my ($udom,$unam,$courseid)=@_;
                   2992:     my $hashid="$udom:$unam:$courseid";
                   2993:     &devalidate_cache_new('getsection',$hashid);
                   2994: }
1.298     matthew  2995: 
1.815     albertel 2996: sub courseid_to_courseurl {
                   2997:     my ($courseid) = @_;
                   2998:     #already url style courseid
                   2999:     return $courseid if ($courseid =~ m{^/});
                   3000: 
                   3001:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3002: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3003: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3004: 	return "/$cdom/$cnum";
                   3005:     }
                   3006: 
                   3007:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   3008:     if (exists($courseinfo{'num'})) {
                   3009: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3010:     }
                   3011: 
                   3012:     return undef;
                   3013: }
                   3014: 
1.298     matthew  3015: sub getsection {
                   3016:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3017:     my $cachetime=1800;
1.551     albertel 3018: 
                   3019:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3020:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3021:     if (defined($cached)) { return $result; }
                   3022: 
1.298     matthew  3023:     my %Pending; 
                   3024:     my %Expired;
                   3025:     #
                   3026:     # Each role can either have not started yet (pending), be active, 
                   3027:     #    or have expired.
                   3028:     #
                   3029:     # If there is an active role, we are done.
                   3030:     #
                   3031:     # If there is more than one role which has not started yet, 
                   3032:     #     choose the one which will start sooner
                   3033:     # If there is one role which has not started yet, return it.
                   3034:     #
                   3035:     # If there is more than one expired role, choose the one which ended last.
                   3036:     # If there is a role which has expired, return it.
                   3037:     #
1.815     albertel 3038:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3039:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3040:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3041:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3042:         my $section=$1;
                   3043:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3044:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3045:         my $now=time;
1.548     albertel 3046:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3047:             $Expired{$end}=$section;
                   3048:             next;
                   3049:         }
1.548     albertel 3050:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3051:             $Pending{$start}=$section;
                   3052:             next;
                   3053:         }
1.599     albertel 3054:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3055:     }
                   3056:     #
                   3057:     # Presumedly there will be few matching roles from the above
                   3058:     # loop and the sorting time will be negligible.
                   3059:     if (scalar(keys(%Pending))) {
                   3060:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3061:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3062:     } 
                   3063:     if (scalar(keys(%Expired))) {
                   3064:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3065:         my $time = pop(@sorted);
1.599     albertel 3066:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3067:     }
1.599     albertel 3068:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3069: }
1.70      www      3070: 
1.599     albertel 3071: sub save_cache {
                   3072:     &purge_remembered();
1.722     albertel 3073:     #&Apache::loncommon::validate_page();
1.620     albertel 3074:     undef(%env);
1.780     albertel 3075:     undef($env_loaded);
1.599     albertel 3076: }
1.452     albertel 3077: 
1.599     albertel 3078: my $to_remember=-1;
                   3079: my %remembered;
                   3080: my %accessed;
                   3081: my $kicks=0;
                   3082: my $hits=0;
1.849     albertel 3083: sub make_key {
                   3084:     my ($name,$id) = @_;
1.872     albertel 3085:     if (length($id) > 65 
                   3086: 	&& length(&escape($id)) > 200) {
                   3087: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3088:     }
1.849     albertel 3089:     return &escape($name.':'.$id);
                   3090: }
                   3091: 
1.599     albertel 3092: sub devalidate_cache_new {
                   3093:     my ($name,$id,$debug) = @_;
                   3094:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3095:     my $remembered_id=$name.':'.$id;
1.849     albertel 3096:     $id=&make_key($name,$id);
1.599     albertel 3097:     $memcache->delete($id);
1.1319    damieng  3098:     delete($remembered{$remembered_id});
                   3099:     delete($accessed{$remembered_id});
1.599     albertel 3100: }
                   3101: 
                   3102: sub is_cached_new {
                   3103:     my ($name,$id,$debug) = @_;
1.1319    damieng  3104:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3105:     if (exists($remembered{$remembered_id})) {
                   3106: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3107: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3108: 	$hits++;
1.1319    damieng  3109: 	return ($remembered{$remembered_id},1);
1.599     albertel 3110:     }
1.1319    damieng  3111:     $id=&make_key($name,$id);
1.599     albertel 3112:     my $value = $memcache->get($id);
                   3113:     if (!(defined($value))) {
                   3114: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3115: 	return (undef,undef);
1.416     albertel 3116:     }
1.599     albertel 3117:     if ($value eq '__undef__') {
                   3118: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3119: 	$value=undef;
                   3120:     }
1.1319    damieng  3121:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3122:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3123:     return ($value,1);
                   3124: }
                   3125: 
                   3126: sub do_cache_new {
                   3127:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3128:     my $remembered_id=$name.':'.$id;
1.849     albertel 3129:     $id=&make_key($name,$id);
1.599     albertel 3130:     my $setvalue=$value;
                   3131:     if (!defined($setvalue)) {
                   3132: 	$setvalue='__undef__';
                   3133:     }
1.623     albertel 3134:     if (!defined($time) ) {
                   3135: 	$time=600;
                   3136:     }
1.599     albertel 3137:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3138:     my $result = $memcache->set($id,$setvalue,$time);
                   3139:     if (! $result) {
1.872     albertel 3140: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3141: 	$memcache->disconnect_all();
1.872     albertel 3142:     }
1.600     albertel 3143:     # need to make a copy of $value
1.1319    damieng  3144:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3145:     return $value;
                   3146: }
                   3147: 
                   3148: sub make_room {
1.1319    damieng  3149:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3150: 
1.1319    damieng  3151:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3152:                                     : $value;
1.599     albertel 3153:     if ($to_remember<0) { return; }
1.1319    damieng  3154:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3155:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3156:     my $to_kick;
                   3157:     my $max_time=0;
                   3158:     foreach my $other (keys(%accessed)) {
                   3159: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3160: 	    $to_kick=$other;
                   3161: 	    $max_time=&tv_interval($accessed{$other});
                   3162: 	}
                   3163:     }
                   3164:     delete($remembered{$to_kick});
                   3165:     delete($accessed{$to_kick});
                   3166:     $kicks++;
                   3167:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3168:     return;
                   3169: }
                   3170: 
1.599     albertel 3171: sub purge_remembered {
1.604     albertel 3172:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3173:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3174:     undef(%remembered);
                   3175:     undef(%accessed);
1.428     albertel 3176: }
1.70      www      3177: # ------------------------------------- Read an entry from a user's environment
                   3178: 
                   3179: sub userenvironment {
                   3180:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3181:     my $items;
                   3182:     foreach my $item (@what) {
                   3183:         $items.=&escape($item).'&';
                   3184:     }
                   3185:     $items=~s/\&$//;
1.70      www      3186:     my %returnhash=();
1.1009    raeburn  3187:     my $uhome = &homeserver($unam,$udom);
                   3188:     unless ($uhome eq 'no_host') {
                   3189:         my @answer=split(/\&/, 
                   3190:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3191:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3192:             return %returnhash;
                   3193:         }
1.1009    raeburn  3194:         my $i;
                   3195:         for ($i=0;$i<=$#what;$i++) {
                   3196: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3197:         }
1.70      www      3198:     }
                   3199:     return %returnhash;
1.1       albertel 3200: }
                   3201: 
1.617     albertel 3202: # ---------------------------------------------------------- Get a studentphoto
                   3203: sub studentphoto {
                   3204:     my ($udom,$unam,$ext) = @_;
                   3205:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3206:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3207:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3208:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3209:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3210:             } else {
                   3211:                 my ($result,$perm_reqd)=
1.707     albertel 3212: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3213:                 if ($result eq 'ok') {
                   3214:                     if (!($perm_reqd eq 'yes')) {
                   3215:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3216:                     }
                   3217:                 }
                   3218:             }
                   3219:         }
                   3220:     } else {
                   3221:         my ($result,$perm_reqd) = 
1.707     albertel 3222: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3223:         if ($result eq 'ok') {
                   3224:             if (!($perm_reqd eq 'yes')) {
                   3225:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3226:             }
                   3227:         }
                   3228:     }
                   3229:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3230: }
                   3231: 
                   3232: sub retrievestudentphoto {
                   3233:     my ($udom,$unam,$ext,$type) = @_;
                   3234:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3235:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3236:     if ($ret eq 'ok') {
                   3237:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3238:         if ($type eq 'thumbnail') {
                   3239:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3240:         }
                   3241:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3242:         return $tokenurl;
                   3243:     } else {
                   3244:         if ($type eq 'thumbnail') {
                   3245:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3246:         } else { 
                   3247:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3248:         }
1.617     albertel 3249:     }
                   3250: }
                   3251: 
1.263     www      3252: # -------------------------------------------------------------------- New chat
                   3253: 
                   3254: sub chatsend {
1.724     raeburn  3255:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3256:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3257:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3258:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3259:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3260: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3261: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3262: }
                   3263: 
                   3264: # ------------------------------------------ Find current version of a resource
                   3265: 
                   3266: sub getversion {
                   3267:     my $fname=&clutter(shift);
1.1189    raeburn  3268:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3269:     return &currentversion(&filelocation('',$fname));
                   3270: }
                   3271: 
                   3272: sub currentversion {
                   3273:     my $fname=shift;
                   3274:     my $author=$fname;
                   3275:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3276:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3277:     my $home=&homeserver($uname,$udom);
1.292     www      3278:     if ($home eq 'no_host') { 
                   3279:         return -1; 
                   3280:     }
1.1112    www      3281:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3282:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3283: 	return -1;
                   3284:     }
1.1112    www      3285:     return $answer;
1.263     www      3286: }
                   3287: 
1.1111    www      3288: #
                   3289: # Return special version number of resource if set by override, empty otherwise
                   3290: #
                   3291: sub usedversion {
                   3292:     my $fname=shift;
                   3293:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3294:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3295:     if ($urlversion) { return $urlversion; }
                   3296:     return '';
                   3297: }
                   3298: 
1.1       albertel 3299: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3300: 
1.1       albertel 3301: sub subscribe {
                   3302:     my $fname=shift;
1.761     raeburn  3303:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3304:     $fname=~s/[\n\r]//g;
1.1       albertel 3305:     my $author=$fname;
                   3306:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3307:     my ($udom,$uname)=split(/\//,$author);
                   3308:     my $home=homeserver($uname,$udom);
1.335     albertel 3309:     if ($home eq 'no_host') {
                   3310:         return 'not_found';
1.1       albertel 3311:     }
                   3312:     my $answer=reply("sub:$fname",$home);
1.64      www      3313:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3314: 	$answer.=' by '.$home;
                   3315:     }
1.1       albertel 3316:     return $answer;
                   3317: }
                   3318:     
1.8       www      3319: # -------------------------------------------------------------- Replicate file
                   3320: 
                   3321: sub repcopy {
                   3322:     my $filename=shift;
1.23      www      3323:     $filename=~s/\/+/\//g;
1.1142    raeburn  3324:     my $londocroot = $perlvar{'lonDocRoot'};
                   3325:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3326:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3327:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3328: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3329: 	return &repcopy_userfile($filename);
                   3330:     }
1.532     albertel 3331:     $filename=~s/[\n\r]//g;
1.8       www      3332:     my $transname="$filename.in.transfer";
1.828     www      3333: # FIXME: this should flock
1.607     raeburn  3334:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3335:     my $remoteurl=subscribe($filename);
1.64      www      3336:     if ($remoteurl =~ /^con_lost by/) {
                   3337: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3338:            return 'unavailable';
1.8       www      3339:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3340: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3341: 	   return 'not_found';
1.64      www      3342:     } elsif ($remoteurl =~ /^rejected by/) {
                   3343: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3344:            return 'forbidden';
1.20      www      3345:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3346:            return 'ok';
1.8       www      3347:     } else {
1.290     www      3348:         my $author=$filename;
                   3349:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3350:         my ($udom,$uname)=split(/\//,$author);
                   3351:         my $home=homeserver($uname,$udom);
                   3352:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3353:            my @parts=split(/\//,$filename);
                   3354:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3355:            if ($path ne "$londocroot/res") {
1.8       www      3356:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3357: 	       return 'bad_request';
1.8       www      3358:            }
                   3359:            my $count;
                   3360:            for ($count=5;$count<$#parts;$count++) {
                   3361:                $path.="/$parts[$count]";
                   3362:                if ((-e $path)!=1) {
                   3363: 		   mkdir($path,0777);
                   3364:                }
                   3365:            }
                   3366:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3367:            my $response;
                   3368:            if ($remoteurl =~ m{/raw/}) {
                   3369:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3370:            } else {
                   3371:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3372:            }
1.8       www      3373:            if ($response->is_error()) {
                   3374: 	       unlink($transname);
                   3375:                my $message=$response->status_line;
1.672     albertel 3376:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3377:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3378:                return 'unavailable';
1.8       www      3379:            } else {
1.16      www      3380: 	       if ($remoteurl!~/\.meta$/) {
                   3381:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3382:                   my $mresponse;
                   3383:                   if ($remoteurl =~ m{/raw/}) {
                   3384:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3385:                   } else {
                   3386:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3387:                   }
1.16      www      3388:                   if ($mresponse->is_error()) {
                   3389: 		      unlink($filename.'.meta');
                   3390:                       &logthis(
1.672     albertel 3391:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3392:                   }
                   3393: 	       }
1.8       www      3394:                rename($transname,$filename);
1.607     raeburn  3395:                return 'ok';
1.8       www      3396:            }
1.290     www      3397:        }
1.8       www      3398:     }
1.330     www      3399: }
                   3400: 
1.1422    raeburn  3401: # ------------------------------------------------- Unsubscribe from a resource
                   3402: 
                   3403: sub unsubscribe {
                   3404:     my ($fname) = @_;
                   3405:     my $answer;
                   3406:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3407:     $fname=~s/[\n\r]//g;
                   3408:     my $author=$fname;
                   3409:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3410:     my ($udom,$uname)=split(/\//,$author);
                   3411:     my $home=homeserver($uname,$udom);
                   3412:     if ($home eq 'no_host') {
                   3413:         $answer = 'no_host';
                   3414:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3415:         $answer = 'home';
                   3416:     } else {
                   3417:         my $defdom = $perlvar{'lonDefDomain'};
                   3418:         if (&will_trust('content',$defdom,$udom)) {
                   3419:             $answer = reply("unsub:$fname",$home);
                   3420:         } else {
                   3421:             $answer = 'untrusted';
                   3422:         }
                   3423:     }
                   3424:     return $answer;
                   3425: }
                   3426: 
1.330     www      3427: # ------------------------------------------------ Get server side include body
                   3428: sub ssi_body {
1.381     albertel 3429:     my ($filelink,%form)=@_;
1.606     matthew  3430:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3431:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3432:     }
1.953     www      3433:     my $output='';
                   3434:     my $response;
1.980     raeburn  3435:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3436:        ($output,$response)=&externalssi($filelink);
1.953     www      3437:     } else {
1.1004    droeschl 3438:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3439:        $filelink .= 'inhibitmenu=yes';
1.953     www      3440:        ($output,$response)=&ssi($filelink,%form);
                   3441:     }
1.778     albertel 3442:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3443:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3444:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3445:     if (wantarray) {
                   3446:         return ($output, $response);
                   3447:     } else {
                   3448:         return $output;
                   3449:     }
1.8       www      3450: }
                   3451: 
1.15      www      3452: # --------------------------------------------------------- Server Side Include
                   3453: 
1.782     albertel 3454: sub absolute_url {
                   3455:     my ($host_name) = @_;
                   3456:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3457:     if ($host_name eq '') {
                   3458: 	$host_name = $ENV{'SERVER_NAME'};
                   3459:     }
                   3460:     return $protocol.$host_name;
                   3461: }
                   3462: 
1.942     foxr     3463: #
                   3464: #   Server side include.
                   3465: # Parameters:
                   3466: #  fn     Possibly encrypted resource name/id.
                   3467: #  form   Hash that describes how the rendering should be done
                   3468: #         and other things.
1.944     foxr     3469: # Returns:
1.950     raeburn  3470: #   Scalar context: The content of the response.
                   3471: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3472: #     
1.15      www      3473: sub ssi {
                   3474: 
1.944     foxr     3475:     my ($fn,%form)=@_;
1.23      www      3476:     my $request;
1.711     albertel 3477: 
                   3478:     $form{'no_update_last_known'}=1;
1.895     albertel 3479:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3480:     if (%form) {
1.782     albertel 3481:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3482:       $request->content(join('&',map { 
                   3483:             my $name = escape($_);
                   3484:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3485:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3486:             : &escape($form{$_}) );    
                   3487:         } keys(%form)));
1.23      www      3488:     } else {
1.782     albertel 3489:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3490:     }
                   3491: 
1.15      www      3492:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3493:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3494:     my $islocal;
                   3495:     if (($env{'request.course.id'}) &&
                   3496:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3497:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3498:         ($form{'grade_symb'} ne '') &&
                   3499:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3500:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3501:         $islocal = 1;
                   3502:     }
1.1384    raeburn  3503:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3504:                                                 '','','',$islocal);
1.1182    foxr     3505: 
1.944     foxr     3506:     if (wantarray) {
1.1345    raeburn  3507: 	return ($response->content, $response);
1.944     foxr     3508:     } else {
1.1345    raeburn  3509: 	return $response->content;
1.942     foxr     3510:     }
1.324     www      3511: }
                   3512: 
                   3513: sub externalssi {
                   3514:     my ($url)=@_;
                   3515:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3516:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3517:     if (wantarray) {
                   3518:         return ($response->content, $response);
                   3519:     } else {
                   3520:         return $response->content;
                   3521:     }
1.15      www      3522: }
1.254     www      3523: 
1.1354    raeburn  3524: 
                   3525: # If the local copy of a replicated resource is outdated, trigger a  
                   3526: # connection from the homeserver to flush the delayed queue. If no update 
                   3527: # happens, remove local copies of outdated resource (and corresponding
                   3528: # metadata file).
                   3529: 
1.1352    raeburn  3530: sub remove_stale_resfile {
                   3531:     my ($url) = @_;
1.1354    raeburn  3532:     my $removed;
1.1352    raeburn  3533:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3534:         my $audom = $1;
                   3535:         my $auname = $2;
1.1353    raeburn  3536:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3537:             my $homeserver = &homeserver($auname,$audom);
                   3538:             unless (($homeserver eq 'no_host') ||
                   3539:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3540:                 my $fname = &filelocation('',$url);
                   3541:                 if (-e $fname) {
                   3542:                     my $hostname = &hostname($homeserver);
                   3543:                     if ($hostname) {
1.1397    raeburn  3544:                         my $protocol = $protocol{$homeserver};
                   3545:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3546:                         my $uri = &declutter($url);
                   3547:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3548:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3549:                         if ($response->is_success()) {
                   3550:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3551:                             my $locmodtime = (stat($fname))[9];
                   3552:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3553:                                 my $stale;
                   3554:                                 my $answer = &reply('pong',$homeserver);
                   3555:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3556:                                     sleep(0.2);
                   3557:                                     $locmodtime = (stat($fname))[9];
                   3558:                                     if ($locmodtime < $remmodtime) {
                   3559:                                         my $posstransfer = $fname.'.in.transfer';
                   3560:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3561:                                             $removed = 1;
                   3562:                                         } else {
                   3563:                                             $stale = 1;
                   3564:                                         }
                   3565:                                     } else {
                   3566:                                         $removed = 1;
                   3567:                                     }
                   3568:                                 } else {
                   3569:                                     $stale = 1;
                   3570:                                 }
                   3571:                                 if ($stale) {
1.1421    raeburn  3572:                                     if (unlink($fname)) {
                   3573:                                         if ($uri!~/\.meta$/) {
                   3574:                                             if (-e $fname.'.meta') {
                   3575:                                                 unlink($fname.'.meta');
                   3576:                                             }
                   3577:                                         }
1.1422    raeburn  3578:                                         my $unsubresult = &unsubscribe($fname);
                   3579:                                         unless ($unsubresult eq 'ok') {
                   3580:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3581:                                         }
1.1421    raeburn  3582:                                         $removed = 1;
1.1354    raeburn  3583:                                     }
1.1352    raeburn  3584:                                 }
                   3585:                             }
                   3586:                         }
                   3587:                     }
                   3588:                 }
                   3589:             }
                   3590:         }
                   3591:     }
1.1354    raeburn  3592:     return $removed;
1.1352    raeburn  3593: }
                   3594: 
1.492     albertel 3595: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3596: 
                   3597: sub allowuploaded {
                   3598:     my ($srcurl,$url)=@_;
                   3599:     $url=&clutter(&declutter($url));
                   3600:     my $dir=$url;
                   3601:     $dir=~s/\/[^\/]+$//;
                   3602:     my %httpref=();
                   3603:     my $httpurl=&hreflocation('',$url);
                   3604:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3605:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3606: }
1.477     raeburn  3607: 
1.1193    raeburn  3608: #
                   3609: # Determine if the current user should be able to edit a particular resource,
                   3610: # when viewing in course context.
                   3611: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3612: #     Functions.
                   3613: # (b) When displaying folder contents in course editor, used to determine if
                   3614: #     "Edit" link will be displayed alongside resource.
                   3615: #
1.1196    raeburn  3616: #  input: six args -- filename (decluttered), course number, course domain,
                   3617: #                   url, symb (if registered) and group (if this is a group
                   3618: #                   item -- e.g., bulletin board, group page etc.).
                   3619: #  output: array of five scalars -- 
1.1193    raeburn  3620: #          $cfile -- url for file editing if editable on current server
                   3621: #          $home -- homeserver of resource (i.e., for author if published,
                   3622: #                                           or course if uploaded.).
                   3623: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3624: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3625: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3626: #
                   3627: 
                   3628: sub can_edit_resource {
1.1194    raeburn  3629:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3630:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3631: #
                   3632: # For aboutme pages user can only edit his/her own.
                   3633: #
1.1199    raeburn  3634:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3635:         my ($sdom,$sname) = ($1,$2);
                   3636:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3637:             $home = $env{'user.home'};
                   3638:             $cfile = $resurl;
                   3639:             if ($env{'form.forceedit'}) {
                   3640:                 $forceview = 1;
                   3641:             } else {
                   3642:                 $forceedit = 1;
                   3643:             }
                   3644:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3645:         } else {
                   3646:             return;
                   3647:         }
                   3648:     }
                   3649: 
                   3650:     if ($env{'request.course.id'}) {
                   3651:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3652:         if ($group ne '') {
                   3653: # if this is a group homepage or group bulletin board, check group privs
                   3654:             my $allowed = 0;
1.1197    raeburn  3655:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3656:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3657:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3658:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3659:                     $allowed = 1;
                   3660:                 }
1.1197    raeburn  3661:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3662:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3663:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3664:                     $allowed = 1;
                   3665:                 }
                   3666:             }
                   3667:             if ($allowed) {
                   3668:                 $home=&homeserver($cnum,$cdom);
                   3669:                 if ($env{'form.forceedit'}) {
                   3670:                     $forceview = 1;
                   3671:                 } else {
                   3672:                     $forceedit = 1;
                   3673:                 }
                   3674:                 $cfile = $resurl;
                   3675:             } else {
                   3676:                 return;
                   3677:             }
                   3678:         } else {
1.1208    raeburn  3679:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3680:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3681:                     return;
                   3682:                 }
                   3683:             } elsif (!$crsedit) {
1.1194    raeburn  3684: #
                   3685: # No edit allowed where CC has switched to student role.
                   3686: #
                   3687:                 return;
                   3688:             }
                   3689:         }
                   3690:     }
                   3691: 
1.1193    raeburn  3692:     if ($file ne '') {
                   3693:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3694:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3695:                 $uploaded = 1;
                   3696:                 $incourse = 1;
1.1193    raeburn  3697:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3698:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3699:                     if ($env{'form.forceedit'}) {
                   3700:                         $forceview = 1;
                   3701:                     } else {
                   3702:                         $forceedit = 1;
                   3703:                     }
1.1194    raeburn  3704:                 }
                   3705:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3706:                 $incourse = 1;
                   3707:                 if ($env{'form.forceedit'}) {
                   3708:                     $forceview = 1;
                   3709:                 } else {
                   3710:                     $forceedit = 1;
                   3711:                 }
                   3712:                 $cfile = $resurl;
                   3713:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3714:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3715:                     $incourse = 1;
                   3716:                     if ($env{'form.forceedit'}) {
                   3717:                         $forceview = 1;
                   3718:                     } else {
                   3719:                         $forceedit = 1;
                   3720:                     }
                   3721:                     $cfile = $resurl;
1.1199    raeburn  3722:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3723:                     $incourse = 1;
                   3724:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3725:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3726:                     $incourse = 1;
1.1199    raeburn  3727:                     if ($env{'form.forceedit'}) {
                   3728:                         $forceview = 1;
                   3729:                     } else {
                   3730:                         $forceedit = 1;
                   3731:                     }
                   3732:                     $cfile = $resurl;
1.1419    raeburn  3733:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3734:                     my ($map,$id,$res) = &decode_symb($symb);
                   3735:                     if ($map =~ /\.page$/) {
                   3736:                         $incourse = 1;
                   3737:                         if ($env{'form.forceedit'}) {
                   3738:                             $forceview = 1;
                   3739:                             $cfile = $map;
                   3740:                         } else {
                   3741:                             $forceedit = 1;
                   3742:                             $cfile =  '/adm/wrapper'.$resurl;
                   3743:                         }
                   3744:                     }
1.1343    raeburn  3745:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3746:                     $incourse = 1;
                   3747:                     if ($env{'form.forceedit'}) {
                   3748:                         $forceview = 1;
                   3749:                     } else {
                   3750:                         $forceedit = 1;
                   3751:                     }
                   3752:                     $cfile = $resurl;
1.1208    raeburn  3753:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3754:                     $incourse = 1;
                   3755:                     if ($env{'form.forceedit'}) {
                   3756:                         $forceview = 1;
                   3757:                     } else {
                   3758:                         $forceedit = 1;
                   3759:                     }
                   3760:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3761:                 }
                   3762:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3763:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3764:                 if (&is_on_map($template)) { 
                   3765:                     $incourse = 1;
                   3766:                     $forceview = 1;
                   3767:                     $cfile = $template;
1.1193    raeburn  3768:                 }
1.1199    raeburn  3769:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  3770:                 $incourse = 1;
                   3771:                 if ($env{'form.forceedit'}) {
                   3772:                     $forceview = 1;
                   3773:                 } else {
                   3774:                     $forceedit = 1;
                   3775:                 }
                   3776:                 $cfile = $resurl;
1.1343    raeburn  3777:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3778:                 $incourse = 1;
                   3779:                 if ($env{'form.forceedit'}) {
                   3780:                     $forceview = 1;
                   3781:                 } else {
                   3782:                     $forceedit = 1;
                   3783:                 }
                   3784:                 $cfile = $resurl;
1.1199    raeburn  3785:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3786:                 $incourse = 1;
                   3787:                 $forceview = 1;
                   3788:                 if ($symb) {
                   3789:                     my ($map,$id,$res)=&decode_symb($symb);
                   3790:                     $env{'request.symb'} = $symb;
                   3791:                     $cfile = &clutter($res);
                   3792:                 } else {
                   3793:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3794:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3795:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3796:                         $cfile = '/adm/wrapper'.$escfile;
                   3797:                     } else {
                   3798:                         $escfile =~ s{^http://}{};
                   3799:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3800:                     }
1.1199    raeburn  3801:                 }
1.1234    raeburn  3802:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3803:                 if ($env{'form.forceedit'}) {
                   3804:                     $forceview = 1;
                   3805:                 } else {
                   3806:                     $forceedit = 1;
                   3807:                 }
                   3808:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3809:             }
                   3810:         }
1.1194    raeburn  3811:         if ($uploaded || $incourse) {
                   3812:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3813:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3814:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3815:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3816:             # Check that the user has permission to edit this resource
                   3817:             my $setpriv = 1;
                   3818:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3819:             if (defined($cfudom)) {
                   3820:                 $home=&homeserver($cfuname,$cfudom);
                   3821:                 $cfile=$file;
                   3822:             }
                   3823:         }
1.1194    raeburn  3824:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3825:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3826:             my @ids=&current_machine_ids();
                   3827:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3828:                 $switchserver=1;
                   3829:             }
                   3830:         }
                   3831:     }
1.1194    raeburn  3832:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3833: }
                   3834: 
                   3835: sub is_course_upload {
                   3836:     my ($file,$cnum,$cdom) = @_;
                   3837:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3838:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3839:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3840:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3841:         return 1;
                   3842:     }
                   3843:     return;
                   3844: }
                   3845: 
1.1194    raeburn  3846: sub in_course {
1.1195    raeburn  3847:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3848:     if ($hideprivileged) {
                   3849:         my $skipuser;
1.1219    raeburn  3850:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3851:         my @possdoms = ($cdom);  
                   3852:         if ($coursehash{'checkforpriv'}) { 
                   3853:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3854:         }
                   3855:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3856:             $skipuser = 1;
                   3857:             if ($coursehash{'nothideprivileged'}) {
                   3858:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3859:                     my $user;
                   3860:                     if ($item =~ /:/) {
                   3861:                         $user = $item;
                   3862:                     } else {
                   3863:                         $user = join(':',split(/[\@]/,$item));
                   3864:                     }
                   3865:                     if ($user eq $uname.':'.$udom) {
                   3866:                         undef($skipuser);
                   3867:                         last;
                   3868:                     }
                   3869:                 }
                   3870:             }
                   3871:             if ($skipuser) {
                   3872:                 return 0;
                   3873:             }
                   3874:         }
                   3875:     }
1.1194    raeburn  3876:     $type ||= 'any';
                   3877:     if (!defined($cdom) || !defined($cnum)) {
                   3878:         my $cid  = $env{'request.course.id'};
                   3879:         $cdom = $env{'course.'.$cid.'.domain'};
                   3880:         $cnum = $env{'course.'.$cid.'.num'};
                   3881:     }
                   3882:     my $typesref;
1.1195    raeburn  3883:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3884:         $typesref = ['active','previous','future'];
                   3885:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3886:         $typesref = [$type];
                   3887:     }
                   3888:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3889:                               $typesref,undef,[$cdom]);
                   3890:     my ($tmp) = keys(%roles);
                   3891:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3892:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3893:     if (@course_roles > 0) {
                   3894:         return 1;
                   3895:     }
                   3896:     return 0;
                   3897: }
                   3898: 
1.478     albertel 3899: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3900: # input: action, courseID, current domain, intended
1.637     raeburn  3901: #        path to file, source of file, instruction to parse file for objects,
                   3902: #        ref to hash for embedded objects,
                   3903: #        ref to hash for codebase of java objects.
1.1095    raeburn  3904: #        reference to scalar to accommodate mime type determined
                   3905: #          from File::MMagic if $parser = parse.
1.637     raeburn  3906: #
1.485     raeburn  3907: # output: url to file (if action was uploaddoc), 
                   3908: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3909: #
1.478     albertel 3910: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3911: # course.
1.477     raeburn  3912: #
1.478     albertel 3913: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3914: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3915: #          course's home server.
1.477     raeburn  3916: #
1.478     albertel 3917: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3918: #          be copied from $source (current location) to 
                   3919: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3920: #         and will then be copied to
                   3921: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3922: #         course's home server.
1.485     raeburn  3923: #
1.481     raeburn  3924: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3925: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3926: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3927: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3928: #         in course's home server.
1.637     raeburn  3929: #
1.477     raeburn  3930: 
                   3931: sub process_coursefile {
1.1095    raeburn  3932:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3933:         $mimetype)=@_;
1.477     raeburn  3934:     my $fetchresult;
1.638     albertel 3935:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3936:     if ($action eq 'propagate') {
1.638     albertel 3937:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3938: 			     $home);
1.481     raeburn  3939:     } else {
1.477     raeburn  3940:         my $fpath = '';
                   3941:         my $fname = $file;
1.478     albertel 3942:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3943:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3944:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3945:         if ($action eq 'copy') {
                   3946:             if ($source eq '') {
                   3947:                 $fetchresult = 'no source file';
                   3948:                 return $fetchresult;
                   3949:             } else {
                   3950:                 my $destination = $filepath.'/'.$fname;
                   3951:                 rename($source,$destination);
                   3952:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3953:                                  $home);
1.481     raeburn  3954:             }
                   3955:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3956:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3957:             print $fh $env{'form.'.$source};
1.481     raeburn  3958:             close($fh);
1.637     raeburn  3959:             if ($parser eq 'parse') {
1.1024    raeburn  3960:                 my $mm = new File::MMagic;
1.1095    raeburn  3961:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3962:                 if ($type eq 'text/html') {
1.1024    raeburn  3963:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3964:                     unless ($parse_result eq 'ok') {
                   3965:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3966:                     }
1.637     raeburn  3967:                 }
1.1095    raeburn  3968:                 if (ref($mimetype)) {
                   3969:                     $$mimetype = $type;
                   3970:                 } 
1.637     raeburn  3971:             }
1.477     raeburn  3972:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3973:                                  $home);
1.481     raeburn  3974:             if ($fetchresult eq 'ok') {
                   3975:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3976:             } else {
                   3977:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3978:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3979:                 return '/adm/notfound.html';
                   3980:             }
1.477     raeburn  3981:         }
                   3982:     }
1.485     raeburn  3983:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3984:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3985:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3986:     }
                   3987:     return $fetchresult;
                   3988: }
                   3989: 
1.637     raeburn  3990: sub build_filepath {
                   3991:     my ($fpath) = @_;
                   3992:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3993:     unless ($fpath eq '') {
                   3994:         my @parts=split('/',$fpath);
                   3995:         foreach my $part (@parts) {
                   3996:             $filepath.= '/'.$part;
                   3997:             if ((-e $filepath)!=1) {
                   3998:                 mkdir($filepath,0777);
                   3999:             }
                   4000:         }
                   4001:     }
                   4002:     return $filepath;
                   4003: }
                   4004: 
                   4005: sub store_edited_file {
1.638     albertel 4006:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4007:     my $file = $primary_url;
                   4008:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4009:     my $fpath = '';
                   4010:     my $fname = $file;
                   4011:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4012:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4013:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4014:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4015:     print $fh $content;
                   4016:     close($fh);
1.638     albertel 4017:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4018:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4019: 			  $home);
1.637     raeburn  4020:     if ($$fetchresult eq 'ok') {
                   4021:         return '/uploaded/'.$fpath.'/'.$fname;
                   4022:     } else {
1.638     albertel 4023:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4024: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4025:         return '/adm/notfound.html';
                   4026:     }
                   4027: }
                   4028: 
1.531     albertel 4029: sub clean_filename {
1.831     albertel 4030:     my ($fname,$args)=@_;
1.315     www      4031: # Replace Windows backslashes by forward slashes
1.257     www      4032:     $fname=~s/\\/\//g;
1.831     albertel 4033:     if (!$args->{'keep_path'}) {
                   4034:         # Get rid of everything but the actual filename
                   4035: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4036:     }
1.315     www      4037: # Replace spaces by underscores
                   4038:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4039: # Transliterate non-ascii text to ascii
                   4040:     my $lang = &Apache::lonlocal::current_language();
                   4041:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4042: # Replace all other weird characters by nothing
1.831     albertel 4043:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4044: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4045: # numbers
                   4046:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 4047:     return $fname;
                   4048: }
1.1406    raeburn  4049: 
1.1051    raeburn  4050: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4051: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4052: # image with the same aspect ratio as the original, but with dimensions which do 
                   4053: # not exceed $resizewidth and $resizeheight.
                   4054:  
1.984     neumanie 4055: sub resizeImage {
1.1051    raeburn  4056:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4057:     my $ima = Image::Magick->new;
                   4058:     my $resized;
                   4059:     if (-e $img_path) {
                   4060:         $ima->Read($img_path);
                   4061:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4062:             my $width = $ima->Get('width');
                   4063:             my $height = $ima->Get('height');
                   4064:             if ($width > $resizewidth) {
                   4065: 	        my $factor = $width/$resizewidth;
                   4066:                 my $newheight = $height/$factor;
                   4067:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4068:                 $resized = 1;
                   4069:             }
                   4070:         }
                   4071:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4072:             my $width = $ima->Get('width');
                   4073:             my $height = $ima->Get('height');
                   4074:             if ($height > $resizeheight) {
                   4075:                 my $factor = $height/$resizeheight;
                   4076:                 my $newwidth = $width/$factor;
                   4077:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4078:                 $resized = 1;
                   4079:             }
                   4080:         }
                   4081:         if ($resized) {
                   4082:             $ima->Write($img_path);
                   4083:         }
                   4084:     }
                   4085:     return;
1.977     amueller 4086: }
                   4087: 
1.608     albertel 4088: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4089: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4090: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4091: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  4092: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  4093: #                   if 'coursedoc': upload to the current course
                   4094: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4095: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4096: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4097: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4098: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4099: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4100: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4101: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4102: #        $allfiles - reference to hash for embedded objects
                   4103: #        $codebase - reference to hash for codebase of java objects
                   4104: #        $desuname - username for permanent storage of uploaded file
                   4105: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4106: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4107: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4108: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4109: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4110: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4111: #                    from File::MMagic.
1.858     raeburn  4112: # 
1.686     albertel 4113: # output: url of file in userspace, or error: <message> 
                   4114: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4115: 
1.531     albertel 4116: sub userfileupload {
1.1090    raeburn  4117:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4118:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4119:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4120:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4121:     $fname=&clean_filename($fname);
1.1090    raeburn  4122:     # See if there is anything left
1.257     www      4123:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4124:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4125:     if ($fname =~ /^\./) {
                   4126:         my ($s,$usec) = &gettimeofday();
                   4127:         while (length($usec) < 6) {
                   4128:             $usec = '0'.$usec;
                   4129:         }
                   4130:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4131:     }
1.1090    raeburn  4132:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4133:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4134:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4135:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4136:         my $now = time;
1.1090    raeburn  4137:         my $filepath;
1.1095    raeburn  4138:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4139:              $filepath = 'tmp/helprequests/'.$now;
                   4140:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4141:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4142:                          '_'.$env{'user.domain'}.'/pending';
                   4143:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4144:             my ($docuname,$docudom);
1.1350    raeburn  4145:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4146:                 $docudom = $destudom;
                   4147:             } else {
                   4148:                 $docudom = $env{'user.domain'};
                   4149:             }
1.1350    raeburn  4150:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4151:                 $docuname = $destuname;
                   4152:             } else {
                   4153:                 $docuname = $env{'user.name'};
                   4154:             }
                   4155:             if (exists($env{'form.group'})) {
                   4156:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4157:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4158:             }
                   4159:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4160:             if ($context eq 'canceloverwrite') {
                   4161:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4162:                 if (-e  $tempfile) {
                   4163:                     my @info = stat($tempfile);
                   4164:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4165:                         unlink($tempfile);
                   4166:                     }
                   4167:                 }
                   4168:                 return;
1.523     raeburn  4169:             }
                   4170:         }
1.1090    raeburn  4171:         # Create the directory if not present
1.741     raeburn  4172:         my @parts=split(/\//,$filepath);
                   4173:         my $fullpath = $perlvar{'lonDaemons'};
                   4174:         for (my $i=0;$i<@parts;$i++) {
                   4175:             $fullpath .= '/'.$parts[$i];
                   4176:             if ((-e $fullpath)!=1) {
                   4177:                 mkdir($fullpath,0777);
                   4178:             }
                   4179:         }
1.1359    raeburn  4180:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4181:         print $fh $env{'form.'.$formname};
                   4182:         close($fh);
1.1090    raeburn  4183:         if ($context eq 'existingfile') {
                   4184:             my @info = stat($fullpath.'/'.$fname);
                   4185:             return ($fullpath.'/'.$fname,$info[9]);
                   4186:         } else {
                   4187:             return $fullpath.'/'.$fname;
                   4188:         }
1.523     raeburn  4189:     }
1.995     raeburn  4190:     if ($subdir eq 'scantron') {
                   4191:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4192:     } else {
1.995     raeburn  4193:         $fname="$subdir/$fname";
                   4194:     }
1.1090    raeburn  4195:     if ($context eq 'coursedoc') {
1.638     albertel 4196: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4197: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4198:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4199:             return &finishuserfileupload($docuname,$docudom,
                   4200: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4201: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4202:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4203:         } else {
1.1218    raeburn  4204:             if ($env{'form.folder'}) {
                   4205:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4206:             }
1.638     albertel 4207:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4208: 				       $fname,$formname,$parser,
1.1095    raeburn  4209: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4210:         }
1.719     banghart 4211:     } elsif (defined($destuname)) {
                   4212:         my $docuname=$destuname;
                   4213:         my $docudom=$destudom;
1.860     raeburn  4214: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4215: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4216:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4217:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4218:     } else {
1.638     albertel 4219:         my $docuname=$env{'user.name'};
                   4220:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4221:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4222:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4223:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4224:         }
1.860     raeburn  4225: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4226: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4227:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4228:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4229:     }
1.271     www      4230: }
                   4231: 
                   4232: sub finishuserfileupload {
1.860     raeburn  4233:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4234:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4235:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4236:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4237:   
1.860     raeburn  4238:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4239:     $file=$fname;
                   4240:     if ($fname=~m|/|) {
                   4241:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4242: 	$path.=$fnamepath.'/';
                   4243:     }
1.259     www      4244:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4245:     my $count;
                   4246:     for ($count=4;$count<=$#parts;$count++) {
                   4247:         $filepath.="/$parts[$count]";
                   4248:         if ((-e $filepath)!=1) {
                   4249: 	    mkdir($filepath,0777);
                   4250:         }
                   4251:     }
1.984     neumanie 4252: 
1.258     www      4253: # Save the file
                   4254:     {
1.1359    raeburn  4255: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4256: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4257: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4258: 	    return '/adm/notfound.html';
                   4259: 	}
1.1090    raeburn  4260:         if ($context eq 'overwrite') {
1.1117    foxr     4261:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4262:             my $target = $filepath.'/'.$file;
                   4263:             if (-e $source) {
                   4264:                 my @info = stat($source);
                   4265:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4266:                     unless (&File::Copy::move($source,$target)) {
                   4267:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4268:                         return "Moving from $source failed";
                   4269:                     }
                   4270:                 } else {
                   4271:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4272:                 }
                   4273:             } else {
                   4274:                 return "Temporary file: $source missing";
                   4275:             }
                   4276:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4277: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4278: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4279: 	    return '/adm/notfound.html';
                   4280: 	}
1.570     albertel 4281: 	close(FH);
1.1051    raeburn  4282:         if ($resizewidth && $resizeheight) {
                   4283:             my $mm = new File::MMagic;
                   4284:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4285:             if ($mime_type =~ m{^image/}) {
                   4286: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4287:             }  
1.977     amueller 4288: 	}
1.258     www      4289:     }
1.1152    raeburn  4290:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4291:         if (ref($mimetype)) {
                   4292:             if ($$mimetype eq '') {
                   4293:                 my $mm = new File::MMagic;
                   4294:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4295:                 $$mimetype = $type;
                   4296:             }
                   4297:         }
                   4298:     }
1.1401    raeburn  4299:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4300:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4301:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4302:                                                        $allfiles,$codebase);
                   4303:             unless ($parse_result eq 'ok') {
                   4304:                 &logthis('Failed to parse '.$filepath.$file.
                   4305: 	   	         ' for embedded media: '.$parse_result); 
                   4306:             }
1.637     raeburn  4307:         }
1.1401    raeburn  4308:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4309:         my $format = $env{'form.scantron_format'};
                   4310:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4311:     }
1.860     raeburn  4312:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4313:         my $input = $filepath.'/'.$file;
                   4314:         my $output = $filepath.'/'.'tn-'.$file;
                   4315:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4316:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4317:         system({$args[0]} @args);
1.860     raeburn  4318:         if (-e $filepath.'/'.'tn-'.$file) {
                   4319:             $fetchthumb  = 1; 
                   4320:         }
                   4321:     }
1.858     raeburn  4322:  
1.259     www      4323: # Notify homeserver to grep it
                   4324: #
1.984     neumanie 4325:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4326:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4327:     if ($fetchresult eq 'ok') {
1.860     raeburn  4328:         if ($fetchthumb) {
                   4329:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4330:             if ($thumbresult ne 'ok') {
                   4331:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4332:                          $docuhome.': '.$thumbresult);
                   4333:             }
                   4334:         }
1.259     www      4335: #
1.258     www      4336: # Return the URL to it
1.494     albertel 4337:         return '/uploaded/'.$path.$file;
1.263     www      4338:     } else {
1.494     albertel 4339:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4340: 		 ': '.$fetchresult);
1.263     www      4341:         return '/adm/notfound.html';
1.858     raeburn  4342:     }
1.493     albertel 4343: }
                   4344: 
1.637     raeburn  4345: sub extract_embedded_items {
1.961     raeburn  4346:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4347:     my @state = ();
1.1164    raeburn  4348:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4349:     my %javafiles = (
                   4350:                       codebase => '',
                   4351:                       code => '',
                   4352:                       archive => ''
                   4353:                     );
                   4354:     my %mediafiles = (
                   4355:                       src => '',
                   4356:                       movie => '',
                   4357:                      );
1.648     raeburn  4358:     my $p;
                   4359:     if ($content) {
                   4360:         $p = HTML::LCParser->new($content);
                   4361:     } else {
1.961     raeburn  4362:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4363:     }
1.641     albertel 4364:     while (my $t=$p->get_token()) {
1.640     albertel 4365: 	if ($t->[0] eq 'S') {
                   4366: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4367: 	    push(@state, $tagname);
1.648     raeburn  4368:             if (lc($tagname) eq 'allow') {
                   4369:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4370:             }
1.640     albertel 4371: 	    if (lc($tagname) eq 'img') {
                   4372: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4373: 	    }
1.886     albertel 4374: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4375:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4376:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4377:                 }
1.886     albertel 4378: 	    }
1.645     raeburn  4379:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4380:                 my $src;
1.645     raeburn  4381:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4382:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4383:                 } else {
1.1164    raeburn  4384:                     if ($attr->{'src'} ne '') {
                   4385:                         $src = $attr->{'src'};
                   4386:                         &add_filetype($allfiles,$src,'src');
                   4387:                     }
                   4388:                 }
                   4389:                 my $text = $p->get_trimmed_text();
                   4390:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4391:                     my @swfargs = split(/,/,$1);
                   4392:                     foreach my $item (@swfargs) {
                   4393:                         $item =~ s/["']//g;
                   4394:                         $item =~ s/^\s+//;
                   4395:                         $item =~ s/\s+$//;
                   4396:                     }
                   4397:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4398:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4399:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4400:                         } else {
                   4401:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4402:                         }
                   4403:                     }
1.645     raeburn  4404:                 }
                   4405:             }
                   4406:             if (lc($tagname) eq 'link') {
                   4407:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4408:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4409:                 }
                   4410:             }
1.640     albertel 4411: 	    if (lc($tagname) eq 'object' ||
                   4412: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4413: 		foreach my $item (keys(%javafiles)) {
                   4414: 		    $javafiles{$item} = '';
                   4415: 		}
1.1164    raeburn  4416:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4417:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4418:                 }
1.640     albertel 4419: 	    }
                   4420: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4421: 		my $name = lc($attr->{'name'});
                   4422: 		foreach my $item (keys(%javafiles)) {
                   4423: 		    if ($name eq $item) {
                   4424: 			$javafiles{$item} = $attr->{'value'};
                   4425: 			last;
                   4426: 		    }
                   4427: 		}
1.1164    raeburn  4428:                 my $pathfrom;
1.640     albertel 4429: 		foreach my $item (keys(%mediafiles)) {
                   4430: 		    if ($name eq $item) {
1.1164    raeburn  4431:                         $pathfrom = $attr->{'value'};
                   4432:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4433: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4434: 			last;
                   4435: 		    }
                   4436: 		}
1.1164    raeburn  4437:                 if ($name eq 'flashvars') {
                   4438:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4439:                 }
                   4440:                 if ($pathfrom ne '') {
                   4441:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4442:                                          $pathfrom);
                   4443:                 }
1.640     albertel 4444: 	    }
                   4445: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4446: 		foreach my $item (keys(%javafiles)) {
                   4447: 		    if ($attr->{$item}) {
                   4448: 			$javafiles{$item} = $attr->{$item};
                   4449: 			last;
                   4450: 		    }
                   4451: 		}
                   4452: 		foreach my $item (keys(%mediafiles)) {
                   4453: 		    if ($attr->{$item}) {
                   4454: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4455: 			last;
                   4456: 		    }
                   4457: 		}
1.1164    raeburn  4458:                 if (lc($tagname) eq 'embed') {
                   4459:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4460:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4461:                                              $attr->{'src'});
                   4462:                     }
                   4463:                 }
1.640     albertel 4464: 	    }
1.1243    raeburn  4465:             if (lc($tagname) eq 'iframe') {
                   4466:                 my $src = $attr->{'src'} ;
                   4467:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4468:                     &add_filetype($allfiles,$src,'src');
                   4469:                 } elsif ($src =~ m{^/}) {
                   4470:                     if ($env{'request.course.id'}) {
                   4471:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4472:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4473:                         my $url = &hreflocation('',$fullpath);
                   4474:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4475:                             my $relpath = $1;
                   4476:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4477:                                 &add_filetype($allfiles,$1,'src');
                   4478:                             }
                   4479:                         }
                   4480:                     }
                   4481:                 }
                   4482:             }
1.1164    raeburn  4483:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4484:                 pop(@state);
1.1164    raeburn  4485:             }
1.640     albertel 4486: 	} elsif ($t->[0] eq 'E') {
                   4487: 	    my ($tagname) = ($t->[1]);
                   4488: 	    if ($javafiles{'codebase'} ne '') {
                   4489: 		$javafiles{'codebase'} .= '/';
                   4490: 	    }  
                   4491: 	    if (lc($tagname) eq 'applet' ||
                   4492: 		lc($tagname) eq 'object' ||
                   4493: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4494: 		) {
                   4495: 		foreach my $item (keys(%javafiles)) {
                   4496: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4497: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4498: 			&add_filetype($allfiles,$file,$item);
                   4499: 		    }
                   4500: 		}
                   4501: 	    } 
                   4502: 	    pop @state;
                   4503: 	}
                   4504:     }
1.1164    raeburn  4505:     foreach my $id (sort(keys(%flashvars))) {
                   4506:         if ($shockwave{$id} ne '') {
                   4507:             my @pairs = split(/\&/,$flashvars{$id});
                   4508:             foreach my $pair (@pairs) {
                   4509:                 my ($key,$value) = split(/\=/,$pair);
                   4510:                 if ($key eq 'thumb') {
                   4511:                     &add_filetype($allfiles,$value,$key);
                   4512:                 } elsif ($key eq 'content') {
                   4513:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4514:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4515:                     if ($ext ne '') {
                   4516:                         &add_filetype($allfiles,$path.$value,$ext);
                   4517:                     }
                   4518:                 }
                   4519:             }
                   4520:         }
                   4521:     }
1.637     raeburn  4522:     return 'ok';
                   4523: }
                   4524: 
1.639     albertel 4525: sub add_filetype {
                   4526:     my ($allfiles,$file,$type)=@_;
                   4527:     if (exists($allfiles->{$file})) {
                   4528: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4529: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4530: 	}
                   4531:     } else {
                   4532: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4533:     }
                   4534: }
                   4535: 
1.1164    raeburn  4536: sub embedded_dependency {
                   4537:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4538:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4539:         if (($identifier ne '') &&
                   4540:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4541:             ($pathfrom ne '')) {
                   4542:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4543:             foreach my $dep (@{$related->{$identifier}}) {
                   4544:                 &add_filetype($allfiles,$path.$dep,'object');
                   4545:             }
                   4546:         }
                   4547:     }
                   4548:     return;
                   4549: }
                   4550: 
1.1401    raeburn  4551: sub bubblesheet_converter {
                   4552:     my ($cdom,$fullpath,$config,$format) = @_;
                   4553:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4554:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4555:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4556:         my (%csvcols,%csvoptions);
                   4557:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4558:             %csvcols = %{$config->{'fields'}};
                   4559:         }
                   4560:         if (ref($config->{'options'}) eq 'HASH') {
                   4561:             %csvoptions = %{$config->{'options'}};
                   4562:         }
1.1401    raeburn  4563:         my %csvbynum = reverse(%csvcols);
                   4564:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4565:         if (keys(%scantronconf)) {
                   4566:             my %bynum = (
                   4567:                           $scantronconf{CODEstart} => 'CODEstart',
                   4568:                           $scantronconf{IDstart}   => 'IDstart',
                   4569:                           $scantronconf{PaperID}   => 'PaperID',
                   4570:                           $scantronconf{FirstName} => 'FirstName',
                   4571:                           $scantronconf{LastName}  => 'LastName',
                   4572:                           $scantronconf{Qstart}    => 'Qstart',
                   4573:                         );
                   4574:             my @ordered;
                   4575:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4576:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4577:             }
                   4578:             my %mapstart = (
                   4579:                               CODEstart => 'CODE',
                   4580:                               IDstart   => 'ID',
                   4581:                               PaperID   => 'PaperID',
                   4582:                               FirstName => 'FirstName',
                   4583:                               LastName  => 'LastName',
                   4584:                               Qstart    => 'FirstQuestion',
                   4585:                            );
                   4586:             my %maplength = (
                   4587:                               CODEstart => 'CODElength',
                   4588:                               IDstart   => 'IDlength',
                   4589:                               PaperID   => 'PaperIDlength',
                   4590:                               FirstName => 'FirstNamelength',
                   4591:                               LastName  => 'LastNamelength',
                   4592:             );
                   4593:             if (open(my $fh,'<',$fullpath)) {
                   4594:                 my $output;
1.1403    raeburn  4595:                 my %lettdig = &letter_to_digits();
                   4596:                 my %diglett = reverse(%lettdig);
                   4597:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4598:                 my $num = 0;
1.1401    raeburn  4599:                 while (my $line=<$fh>) {
1.1404    raeburn  4600:                     $num ++;
                   4601:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4602:                     $line =~ s{[\r\n]+$}{};
                   4603:                     my %found;
                   4604:                     my @values = split(/,/,$line);
                   4605:                     my ($qstart,$record);
                   4606:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4607:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4608:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4609:                             if ($values[$i] eq '') {
                   4610:                                 $values[$i] = $scantronconf{'Qoff'};
                   4611:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4612:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4613:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4614:                                 }
                   4615:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4616:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4617:                                     $values[$i] = $diglett{$values[$i]};
                   4618:                                 }
                   4619:                             } else {
                   4620:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4621:                                     my $digit;
                   4622:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4623:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4624:                                         if ($values[$i] eq 'J') {
                   4625:                                             $digit += $numletts;
                   4626:                                         }
                   4627:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4628:                                         $digit = $values[$i]-1;
                   4629:                                         if ($values[$i] eq '0') {
                   4630:                                             $digit += $numletts;
                   4631:                                         }
                   4632:                                     }
                   4633:                                     my $qval='';
                   4634:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4635:                                         if ($j == $digit) {
                   4636:                                             $qval .= $scantronconf{'Qon'};
                   4637:                                         } else {
                   4638:                                             $qval .= $scantronconf{'Qoff'};
                   4639:                                         }
                   4640:                                     }
                   4641:                                     $values[$i] = $qval;
                   4642:                                 }
                   4643:                             }
                   4644:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4645:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4646:                             }
                   4647:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4648:                             if ($numblank > 0) {
                   4649:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4650:                             }
1.1401    raeburn  4651:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4652:                                 $qstart = $i;
1.1403    raeburn  4653:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4654:                             } else {
1.1403    raeburn  4655:                                 $found{'FirstQuestion'} .= $values[$i];
                   4656:                             }
                   4657:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4658:                             if ($csvoptions{'rem'}) {
                   4659:                                 $values[$i] =~ s/^\s+//;
                   4660:                             }
                   4661:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4662:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4663:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4664:                                 }
                   4665:                             }
                   4666:                             $found{$csvbynum{$i}} = $values[$i];
                   4667:                         }
                   4668:                     }
                   4669:                     foreach my $item (@ordered) {
                   4670:                         my $currlength = 1+length($record);
                   4671:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4672:                         if ($numspaces > 0) {
                   4673:                             $record .= (' ' x $numspaces);
                   4674:                         }
                   4675:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4676:                             unless ($item eq 'Qstart') {
                   4677:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4678:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4679:                                 }
                   4680:                             }
                   4681:                             $record .= $found{$mapstart{$item}};
                   4682:                         }
                   4683:                     }
                   4684:                     $output .= "$record\n";
                   4685:                 }
                   4686:                 close($fh);
                   4687:                 if ($output) {
                   4688:                     if (open(my $fh,'>',$fullpath)) {
                   4689:                         print $fh $output;
                   4690:                         close($fh);
                   4691:                     }
                   4692:                 }
                   4693:             }
                   4694:         }
                   4695:         return;
                   4696:     }
                   4697: }
                   4698: 
1.1403    raeburn  4699: sub letter_to_digits {
                   4700:     my %lettdig = (
                   4701:                     A => 1,
                   4702:                     B => 2,
                   4703:                     C => 3,
                   4704:                     D => 4,
                   4705:                     E => 5,
                   4706:                     F => 6,
                   4707:                     G => 7,
                   4708:                     H => 8,
                   4709:                     I => 9,
                   4710:                     J => 0,
                   4711:                   );
                   4712:     return %lettdig;
                   4713: }
                   4714: 
1.1401    raeburn  4715: sub get_scantron_config {
                   4716:     my ($which,$cdom) = @_;
                   4717:     my @lines = &get_scantronformat_file($cdom);
                   4718:     my %config;
                   4719:     #FIXME probably should move to XML it has already gotten a bit much now
                   4720:     foreach my $line (@lines) {
                   4721:         my ($name,$descrip)=split(/:/,$line);
                   4722:         if ($name ne $which ) { next; }
                   4723:         chomp($line);
                   4724:         my @config=split(/:/,$line);
                   4725:         $config{'name'}=$config[0];
                   4726:         $config{'description'}=$config[1];
                   4727:         $config{'CODElocation'}=$config[2];
                   4728:         $config{'CODEstart'}=$config[3];
                   4729:         $config{'CODElength'}=$config[4];
                   4730:         $config{'IDstart'}=$config[5];
                   4731:         $config{'IDlength'}=$config[6];
                   4732:         $config{'Qstart'}=$config[7];
                   4733:         $config{'Qlength'}=$config[8];
                   4734:         $config{'Qoff'}=$config[9];
                   4735:         $config{'Qon'}=$config[10];
                   4736:         $config{'PaperID'}=$config[11];
                   4737:         $config{'PaperIDlength'}=$config[12];
                   4738:         $config{'FirstName'}=$config[13];
                   4739:         $config{'FirstNamelength'}=$config[14];
                   4740:         $config{'LastName'}=$config[15];
                   4741:         $config{'LastNamelength'}=$config[16];
                   4742:         $config{'BubblesPerRow'}=$config[17];
                   4743:         last;
                   4744:     }
                   4745:     return %config;
                   4746: }
                   4747: 
                   4748: sub get_scantronformat_file {
                   4749:     my ($cdom) = @_;
                   4750:     if ($cdom eq '') {
                   4751:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4752:     }
                   4753:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4754:     my $gottab = 0;
                   4755:     my @lines;
                   4756:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4757:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4758:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4759:             if ($formatfile ne '-1') {
                   4760:                 @lines = split("\n",$formatfile,-1);
                   4761:                 $gottab = 1;
                   4762:             }
                   4763:         }
                   4764:     }
                   4765:     if (!$gottab) {
                   4766:         my $confname = $cdom.'-domainconfig';
                   4767:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4768:         my $formatfile = &getfile($default);
                   4769:         if ($formatfile ne '-1') {
                   4770:             @lines = split("\n",$formatfile,-1);
                   4771:             $gottab = 1;
                   4772:         }
                   4773:     }
                   4774:     if (!$gottab) {
                   4775:         my @domains = &current_machine_domains();
                   4776:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4777:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4778:                 @lines = <$fh>;
                   4779:                 close($fh);
1.1403    raeburn  4780:             }
1.1401    raeburn  4781:         } else {
                   4782:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4783:                 @lines = <$fh>;
                   4784:                 close($fh);
                   4785:             }
                   4786:         }
                   4787:     }
                   4788:     return @lines;
                   4789: }
                   4790: 
1.493     albertel 4791: sub removeuploadedurl {
1.984     neumanie 4792:     my ($url)=@_;	
                   4793:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4794:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4795: }
                   4796: 
                   4797: sub removeuserfile {
                   4798:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4799:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4800:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4801:     if ($result eq 'ok') {	
1.798     raeburn  4802:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4803:             my $metafile = $fname.'.meta';
                   4804:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4805: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4806:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4807:             my $sqlresult = 
1.823     albertel 4808:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4809:                                         'portfolio_metadata',$group,
                   4810:                                         'delete');
1.798     raeburn  4811:         }
                   4812:     }
                   4813:     return $result;
1.257     www      4814: }
1.15      www      4815: 
1.530     albertel 4816: sub mkdiruserfile {
                   4817:     my ($docuname,$docudom,$dir)=@_;
                   4818:     my $home=&homeserver($docuname,$docudom);
                   4819:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4820: }
                   4821: 
1.531     albertel 4822: sub renameuserfile {
                   4823:     my ($docuname,$docudom,$old,$new)=@_;
                   4824:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4825:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4826:                         &escape("$old").':'.&escape("$new"),$home);
                   4827:     if ($result eq 'ok') {
                   4828:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4829:             my $oldmeta = $old.'.meta';
                   4830:             my $newmeta = $new.'.meta';
                   4831:             my $metaresult = 
                   4832:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4833: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4834:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4835:             my $sqlresult = 
1.823     albertel 4836:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4837:                                         'portfolio_metadata',$group,
                   4838:                                         'delete');
1.798     raeburn  4839:         }
                   4840:     }
                   4841:     return $result;
1.531     albertel 4842: }
                   4843: 
1.14      www      4844: # ------------------------------------------------------------------------- Log
                   4845: 
                   4846: sub log {
                   4847:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4848:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4849: }
                   4850: 
                   4851: # ------------------------------------------------------------------ Course Log
1.352     www      4852: #
                   4853: # This routine flushes several buffers of non-mission-critical nature
                   4854: #
1.157     www      4855: 
                   4856: sub flushcourselogs {
1.352     www      4857:     &logthis('Flushing log buffers');
                   4858: #
                   4859: # course logs
                   4860: # This is a log of all transactions in a course, which can be used
                   4861: # for data mining purposes
                   4862: #
                   4863: # It also collects the courseid database, which lists last transaction
                   4864: # times and course titles for all courseids
                   4865: #
                   4866:     my %courseidbuffer=();
1.921     raeburn  4867:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4868:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4869: 		          &escape($courselogs{$crsid}),
                   4870: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4871: 	    delete $courselogs{$crsid};
                   4872:         } else {
                   4873:             &logthis('Failed to flush log buffer for '.$crsid);
                   4874:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4875:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4876:                         " exceeded maximum size, deleting.</font>");
                   4877:                delete $courselogs{$crsid};
                   4878:             }
1.352     www      4879:         }
1.920     raeburn  4880:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4881:             'description' => $coursedescrbuf{$crsid},
                   4882:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4883:             'type'        => $coursetypebuf{$crsid},
                   4884:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4885:         };
1.191     harris41 4886:     }
1.352     www      4887: #
                   4888: # Write course id database (reverse lookup) to homeserver of courses 
                   4889: # Is used in pickcourse
                   4890: #
1.840     albertel 4891:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4892:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4893:                                     $courseidbuffer{$crs_home},
                   4894:                                     $crs_home,'timeonly');
1.352     www      4895:     }
                   4896: #
                   4897: # File accesses
                   4898: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4899: #
1.449     matthew  4900:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4901:         if ($entry =~ /___count$/) {
                   4902:             my ($dom,$name);
1.807     albertel 4903:             ($dom,$name,undef)=
1.811     albertel 4904: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4905:             if (! defined($dom) || $dom eq '' || 
                   4906:                 ! defined($name) || $name eq '') {
1.620     albertel 4907:                 my $cid = $env{'request.course.id'};
                   4908:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4909:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4910:             }
1.450     matthew  4911:             my $value = $accesshash{$entry};
                   4912:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4913:             my %temphash=($url => $value);
1.449     matthew  4914:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4915:             if ($result eq 'ok') {
                   4916:                 delete $accesshash{$entry};
                   4917:             }
                   4918:         } else {
1.811     albertel 4919:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4920:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4921:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4922:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4923:                 delete $accesshash{$entry};
                   4924:             }
1.185     www      4925:         }
1.191     harris41 4926:     }
1.352     www      4927: #
                   4928: # Roles
                   4929: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4930: #
1.800     albertel 4931:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4932:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4933: 	    split(/\:/,$entry);
                   4934:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4935:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4936:                 $rudom,$runame) eq 'ok') {
                   4937: 	    delete $userrolehash{$entry};
                   4938:         }
                   4939:     }
1.662     raeburn  4940: #
1.1334    raeburn  4941: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4942: #
                   4943:     my %domrolebuffer = ();
1.1000    raeburn  4944:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4945:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4946:         if ($domrolebuffer{$rudom}) {
                   4947:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4948:                       '='.&escape($domainrolehash{$entry});
                   4949:         } else {
                   4950:             $domrolebuffer{$rudom}.=&escape($entry).
                   4951:                       '='.&escape($domainrolehash{$entry});
                   4952:         }
                   4953:         delete $domainrolehash{$entry};
                   4954:     }
                   4955:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4956: 	my %servers;
                   4957: 	if (defined(&domain($dom,'primary'))) {
                   4958: 	    my $primary=&domain($dom,'primary');
                   4959: 	    my $hostname=&hostname($primary);
                   4960: 	    $servers{$primary} = $hostname;
                   4961: 	} else { 
                   4962: 	    %servers = &get_servers($dom,'library');
                   4963: 	}
1.841     albertel 4964: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4965: 	    if (&reply('domroleput:'.$dom.':'.
                   4966: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4967: 		last;
                   4968: 	    } else {  
1.841     albertel 4969: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4970: 	    }
1.662     raeburn  4971:         }
                   4972:     }
1.186     www      4973:     $dumpcount++;
1.157     www      4974: }
                   4975: 
                   4976: sub courselog {
                   4977:     my $what=shift;
1.158     www      4978:     $what=time.':'.$what;
1.620     albertel 4979:     unless ($env{'request.course.id'}) { return ''; }
                   4980:     $coursedombuf{$env{'request.course.id'}}=
                   4981:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4982:     $coursenumbuf{$env{'request.course.id'}}=
                   4983:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4984:     $coursehombuf{$env{'request.course.id'}}=
                   4985:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4986:     $coursedescrbuf{$env{'request.course.id'}}=
                   4987:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4988:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4989:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4990:     $courseownerbuf{$env{'request.course.id'}}=
                   4991:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4992:     $coursetypebuf{$env{'request.course.id'}}=
                   4993:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4994:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4995: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4996:     } else {
1.620     albertel 4997: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4998:     }
1.620     albertel 4999:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5000: 	&flushcourselogs();
                   5001:     }
1.158     www      5002: }
                   5003: 
                   5004: sub courseacclog {
                   5005:     my $fnsymb=shift;
1.620     albertel 5006:     unless ($env{'request.course.id'}) { return ''; }
                   5007:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5008:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5009:         $what.=':POST';
1.583     matthew  5010:         # FIXME: Probably ought to escape things....
1.800     albertel 5011: 	foreach my $key (keys(%env)) {
                   5012:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5013:                 my $formitem = $1;
                   5014:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5015:                     $what.=':'.$formitem.'='.$env{$key};
                   5016:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5017:                     if ($formitem eq 'proctorpassword') {
1.1433  ! raeburn  5018:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5019:                     } else {
                   5020:                         $what.=':'.$formitem.'='.$env{$key};
                   5021:                     }
1.975     raeburn  5022:                 }
1.158     www      5023:             }
1.191     harris41 5024:         }
1.583     matthew  5025:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5026:         # FIXME: We should not be depending on a form parameter that someone
                   5027:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5028:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5029:             $what.= ':POST';
                   5030:             # FIXME: Probably ought to escape things....
                   5031:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5032:                                  'crsdiscuss') {
1.620     albertel 5033:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5034:             }
                   5035:         }
1.158     www      5036:     }
                   5037:     &courselog($what);
1.149     www      5038: }
                   5039: 
1.185     www      5040: sub countacc {
                   5041:     my $url=&declutter(shift);
1.458     matthew  5042:     return if (! defined($url) || $url eq '');
1.620     albertel 5043:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5044: #
                   5045: # Mark that this url was used in this course
                   5046: #
1.620     albertel 5047:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5048: #
                   5049: # Increase the access count for this resource in this child process
                   5050: #
1.281     www      5051:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5052:     $accesshash{$key}++;
1.185     www      5053: }
1.349     www      5054: 
1.361     www      5055: sub linklog {
                   5056:     my ($from,$to)=@_;
                   5057:     $from=&declutter($from);
                   5058:     $to=&declutter($to);
                   5059:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5060:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5061: }
1.1160    www      5062: 
                   5063: sub statslog {
                   5064:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5065:     if ($users<2) { return; }
                   5066:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5067:             'course'       => $env{'request.course.id'},
                   5068:             'sections'     => '"all"',
                   5069:             'num_students' => $users,
                   5070:             'part'         => $part,
                   5071:             'symb'         => $symb,
                   5072:             'mean_tries'   => $av_attempts,
                   5073:             'deg_of_diff'  => $degdiff});
                   5074:     foreach my $key (keys(%dynstore)) {
                   5075:         $accesshash{$key}=$dynstore{$key};
                   5076:     }
                   5077: }
1.361     www      5078:   
1.349     www      5079: sub userrolelog {
                   5080:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5081:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5082:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5083:        $userrolehash
                   5084:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5085:                     =$tend.':'.$tstart;
1.662     raeburn  5086:     }
1.1169    droeschl 5087:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5088:        $userrolehash
                   5089:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5090:                     =$tend.':'.$tstart;
                   5091:     }
1.1334    raeburn  5092:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5093:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5094:        $domainrolehash
                   5095:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5096:                     = $tend.':'.$tstart;
                   5097:     }
1.351     www      5098: }
                   5099: 
1.957     raeburn  5100: sub courserolelog {
                   5101:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  5102:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5103:         my $cdom = $1;
                   5104:         my $cnum = $2;
                   5105:         my $sec = $3;
                   5106:         my $namespace = 'rolelog';
                   5107:         my %storehash = (
                   5108:                            role    => $trole,
                   5109:                            start   => $tstart,
                   5110:                            end     => $tend,
                   5111:                            selfenroll => $selfenroll,
                   5112:                            context    => $context,
                   5113:                         );
                   5114:         if ($trole eq 'gr') {
                   5115:             $namespace = 'groupslog';
                   5116:             $storehash{'group'} = $sec;
                   5117:         } else {
                   5118:             $storehash{'section'} = $sec;
                   5119:         }
1.1188    raeburn  5120:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5121:                    $domain,$cnum,$cdom);
1.1184    raeburn  5122:         if (($trole ne 'st') || ($sec ne '')) {
                   5123:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5124:         }
                   5125:     }
                   5126:     return;
                   5127: }
                   5128: 
1.1184    raeburn  5129: sub domainrolelog {
                   5130:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5131:     if ($area =~ m{^/($match_domain)/$}) {
                   5132:         my $cdom = $1;
                   5133:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5134:         my $namespace = 'rolelog';
                   5135:         my %storehash = (
                   5136:                            role    => $trole,
                   5137:                            start   => $tstart,
                   5138:                            end     => $tend,
                   5139:                            context => $context,
                   5140:                         );
1.1188    raeburn  5141:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5142:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5143:     }
                   5144:     return;
                   5145: 
                   5146: }
                   5147: 
                   5148: sub coauthorrolelog {
                   5149:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5150:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5151:         my $audom = $1;
                   5152:         my $auname = $2;
                   5153:         my $namespace = 'rolelog';
                   5154:         my %storehash = (
                   5155:                            role    => $trole,
                   5156:                            start   => $tstart,
                   5157:                            end     => $tend,
                   5158:                            context => $context,
                   5159:                         );
1.1188    raeburn  5160:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5161:                    $domain,$auname,$audom);
1.1184    raeburn  5162:     }
                   5163:     return;
                   5164: }
                   5165: 
1.351     www      5166: sub get_course_adv_roles {
1.948     raeburn  5167:     my ($cid,$codes) = @_;
1.620     albertel 5168:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5169:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5170:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5171:     my %nothide=();
1.800     albertel 5172:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5173:         if ($user !~ /:/) {
                   5174: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5175:         } else {
                   5176:             $nothide{$user}=1;
                   5177:         }
1.470     www      5178:     }
1.1219    raeburn  5179:     my @possdoms = ($coursehash{'domain'});
                   5180:     if ($coursehash{'checkforpriv'}) {
                   5181:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5182:     }
1.351     www      5183:     my %returnhash=();
                   5184:     my %dumphash=
                   5185:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5186:     my $now=time;
1.997     raeburn  5187:     my %privileged;
1.1000    raeburn  5188:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5189: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5190:         if (($tstart) && ($tstart<0)) { next; }
                   5191:         if (($tend) && ($tend<$now)) { next; }
                   5192:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5193:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5194: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5195:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5196:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5197: 	if ($role eq 'cr') { next; }
1.948     raeburn  5198:         if ($codes) {
                   5199:             if ($section) { $role .= ':'.$section; }
                   5200:             if ($returnhash{$role}) {
                   5201:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5202:             } else {
                   5203:                 $returnhash{$role}=$username.':'.$domain;
                   5204:             }
1.351     www      5205:         } else {
1.988     raeburn  5206:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5207:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5208:             if ($returnhash{$key}) {
                   5209: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5210:             } else {
                   5211:                 $returnhash{$key}=$username.':'.$domain;
                   5212:             }
1.351     www      5213:         }
1.948     raeburn  5214:     }
1.400     www      5215:     return %returnhash;
                   5216: }
                   5217: 
                   5218: sub get_my_roles {
1.937     raeburn  5219:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5220:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5221:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5222:     my (%dumphash,%nothide);
1.1086    raeburn  5223:     if ($context eq 'userroles') {
1.1166    raeburn  5224:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5225:     } else {
1.1219    raeburn  5226:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5227:         if ($hidepriv) {
                   5228:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5229:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5230:                 if ($user !~ /:/) {
                   5231:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5232:                 } else {
                   5233:                     $nothide{$user} = 1;
                   5234:                 }
                   5235:             }
                   5236:         }
1.858     raeburn  5237:     }
1.400     www      5238:     my %returnhash=();
                   5239:     my $now=time;
1.999     raeburn  5240:     my %privileged;
1.800     albertel 5241:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5242:         my ($role,$tend,$tstart);
                   5243:         if ($context eq 'userroles') {
1.1149    raeburn  5244:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5245: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5246:         } else {
                   5247:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5248:         }
1.400     www      5249:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5250:         my $status = 'active';
1.939     raeburn  5251:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5252:             $status = 'previous';
                   5253:         } 
                   5254:         if (($tstart) && ($now<$tstart)) {
                   5255:             $status = 'future';
                   5256:         }
                   5257:         if (ref($types) eq 'ARRAY') {
                   5258:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5259:                 next;
                   5260:             } 
                   5261:         } else {
                   5262:             if ($status ne 'active') {
                   5263:                 next;
                   5264:             }
                   5265:         }
1.867     raeburn  5266:         my ($rolecode,$username,$domain,$section,$area);
                   5267:         if ($context eq 'userroles') {
1.1186    raeburn  5268:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5269:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5270:         } else {
                   5271:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5272:         }
1.832     raeburn  5273:         if (ref($roledoms) eq 'ARRAY') {
                   5274:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5275:                 next;
                   5276:             }
                   5277:         }
                   5278:         if (ref($roles) eq 'ARRAY') {
                   5279:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5280:                 if ($role =~ /^cr\//) {
                   5281:                     if (!grep(/^cr$/,@{$roles})) {
                   5282:                         next;
                   5283:                     }
1.1104    raeburn  5284:                 } elsif ($role =~ /^gr\//) {
                   5285:                     if (!grep(/^gr$/,@{$roles})) {
                   5286:                         next;
                   5287:                     }
1.922     raeburn  5288:                 } else {
                   5289:                     next;
                   5290:                 }
1.832     raeburn  5291:             }
1.867     raeburn  5292:         }
1.937     raeburn  5293:         if ($hidepriv) {
1.1219    raeburn  5294:             my @privroles = ('dc','su');
1.999     raeburn  5295:             if ($context eq 'userroles') {
1.1219    raeburn  5296:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5297:             } else {
1.1219    raeburn  5298:                 my $possdoms = [$domain];
                   5299:                 if (ref($roledoms) eq 'ARRAY') {
                   5300:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5301:                 }
1.1219    raeburn  5302:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5303:                     if (!$nothide{$username.':'.$domain}) {
                   5304:                         next;
                   5305:                     }
                   5306:                 }
1.937     raeburn  5307:             }
                   5308:         }
1.933     raeburn  5309:         if ($withsec) {
                   5310:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5311:                 $tstart.':'.$tend;
                   5312:         } else {
                   5313:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5314:         }
1.832     raeburn  5315:     }
1.373     www      5316:     return %returnhash;
1.399     www      5317: }
                   5318: 
1.1333    raeburn  5319: sub get_all_adhocroles {
                   5320:     my ($dom) = @_;
                   5321:     my @roles_by_num = ();
                   5322:     my %domdefaults = &get_domain_defaults($dom);
                   5323:     my (%description,%access_in_dom,%access_info);
                   5324:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5325:         my $count = 0;
                   5326:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5327:         my %ordered;
                   5328:         foreach my $role (sort(keys(%domcurrent))) {
                   5329:             my ($order,$desc,$access_in_dom);
                   5330:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5331:                 $order = $domcurrent{$role}{'order'};
                   5332:                 $desc = $domcurrent{$role}{'desc'};
                   5333:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5334:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5335:             }
                   5336:             if ($order eq '') {
                   5337:                 $order = $count;
                   5338:             }
                   5339:             $ordered{$order} = $role;
                   5340:             if ($desc ne '') {
                   5341:                 $description{$role} = $desc;
                   5342:             } else {
                   5343:                 $description{$role}= $role;
                   5344:             }
                   5345:             $count++;
                   5346:         }
                   5347:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5348:             push(@roles_by_num,$ordered{$item});
                   5349:         }
                   5350:     }
                   5351:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5352: }
                   5353: 
1.1332    raeburn  5354: sub get_my_adhocroles {
1.1333    raeburn  5355:     my ($cid,$checkreg) = @_;
                   5356:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5357:     if ($env{'request.course.id'} eq $cid) {
                   5358:         $cdom = $env{'course.'.$cid.'.domain'};
                   5359:         $cnum = $env{'course.'.$cid.'.num'};
                   5360:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5361:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5362:         $cdom = $1;
                   5363:         $cnum = $2;
                   5364:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5365:                                      $cdom,$cnum);
                   5366:     }
                   5367:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5368:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5369:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5370:         if ($rosterhash{$user} ne '') {
                   5371:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5372:             return ([],{}) if ($type eq 'auto');
                   5373:         }
                   5374:     }
                   5375:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5376:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5377:             my $then=$env{'user.login.time'};
                   5378:             my $update=$env{'user.update.time'};
1.1335    raeburn  5379:             if (!$update) {
                   5380:                 $update = $then;
                   5381:             }
                   5382:             my @liveroles;
1.1334    raeburn  5383:             foreach my $role ('dh','da') {
                   5384:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5385:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5386:                     my $limit = $update;
                   5387:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5388:                         $limit = $then;
                   5389:                     }
1.1335    raeburn  5390:                     my $activerole = 1;
                   5391:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5392:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5393:                     if ($activerole) {
                   5394:                         push(@liveroles,$role);
                   5395:                     }
1.1334    raeburn  5396:                 }
1.1332    raeburn  5397:             }
1.1335    raeburn  5398:             if (@liveroles) {
1.1332    raeburn  5399:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5400:                     my ($accessref,$accessinfo,%access_in_dom);
                   5401:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5402:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5403:                         if (@{$roles_by_num}) {
1.1332    raeburn  5404:                             my %settings;
                   5405:                             if ($env{'request.course.id'} eq $cid) {
                   5406:                                 foreach my $envkey (keys(%env)) {
                   5407:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5408:                                         $settings{$1} = $env{$envkey};
                   5409:                                     }
                   5410:                                 }
                   5411:                             } else {
                   5412:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5413:                             }
                   5414:                             my %setincrs;
                   5415:                             if ($settings{'internal.adhocaccess'}) {
                   5416:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5417:                             }
                   5418:                             my @statuses;
                   5419:                             if ($env{'environment.inststatus'}) {
                   5420:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5421:                             }
                   5422:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5423:                             if (ref($accessref) eq 'HASH') {
                   5424:                                 %access_in_dom = %{$accessref};
                   5425:                             }
                   5426:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5427:                                 my ($curraccess,@okstatus,@personnel);
                   5428:                                 if ($setincrs{$role}) {
                   5429:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5430:                                     if ($curraccess eq 'status') {
                   5431:                                         @okstatus = split(/\&/,$rest);
                   5432:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5433:                                         @personnel = split(/\&/,$rest);
                   5434:                                     }
                   5435:                                 } else {
                   5436:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5437:                                     if (ref($accessinfo) eq 'HASH') {
                   5438:                                         if ($curraccess eq 'status') {
                   5439:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5440:                                                 @okstatus = @{$accessinfo->{$role}};
                   5441:                                             }
                   5442:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5443:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5444:                                                 @personnel = @{$accessinfo->{$role}};
                   5445:                                             }
1.1332    raeburn  5446:                                         }
                   5447:                                     }
                   5448:                                 }
                   5449:                                 if ($curraccess eq 'none') {
                   5450:                                     next;
                   5451:                                 } elsif ($curraccess eq 'all') {
                   5452:                                     push(@possroles,$role);
1.1336    raeburn  5453:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5454:                                     if (grep(/^dh$/,@liveroles)) {
                   5455:                                         push(@possroles,$role);
                   5456:                                     } else {
                   5457:                                         next;
                   5458:                                     }
1.1336    raeburn  5459:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5460:                                     if (grep(/^da$/,@liveroles)) {
                   5461:                                         push(@possroles,$role);
                   5462:                                     } else {
                   5463:                                         next;
                   5464:                                     }
1.1332    raeburn  5465:                                 } elsif ($curraccess eq 'status') {
                   5466:                                     if (@okstatus) {
                   5467:                                         if (!@statuses) {
                   5468:                                             if (grep(/^default$/,@okstatus)) {
                   5469:                                                 push(@possroles,$role);
                   5470:                                             }
                   5471:                                         } else {
                   5472:                                             foreach my $status (@okstatus) {
                   5473:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5474:                                                     push(@possroles,$role);
                   5475:                                                     last;
                   5476:                                                 }
                   5477:                                             }
                   5478:                                         }
                   5479:                                     }
                   5480:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5481:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5482:                                         if ($curraccess eq 'exc') {
                   5483:                                             push(@possroles,$role);
                   5484:                                         }
                   5485:                                     } elsif ($curraccess eq 'inc') {
                   5486:                                         push(@possroles,$role);
                   5487:                                     }
                   5488:                                 }
                   5489:                             }
                   5490:                         }
                   5491:                     }
                   5492:                 }
                   5493:             }
                   5494:         }
                   5495:     }
1.1333    raeburn  5496:     unless (ref($description) eq 'HASH') {
                   5497:         if (ref($roles_by_num) eq 'ARRAY') {
                   5498:             my %desc;
                   5499:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5500:             $description = \%desc;
                   5501:         } else {
                   5502:             $description = {};
                   5503:         }
                   5504:     }
                   5505:     return (\@possroles,$description);
1.1332    raeburn  5506: }
                   5507: 
1.399     www      5508: # ----------------------------------------------------- Frontpage Announcements
                   5509: #
                   5510: #
                   5511: 
                   5512: sub postannounce {
                   5513:     my ($server,$text)=@_;
1.844     albertel 5514:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5515:     unless ($text=~/\w/) { $text=''; }
                   5516:     return &reply('setannounce:'.&escape($text),$server);
                   5517: }
                   5518: 
                   5519: sub getannounce {
1.448     albertel 5520: 
1.1359    raeburn  5521:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5522: 	my $announcement='';
1.800     albertel 5523: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5524: 	close($fh);
1.399     www      5525: 	if ($announcement=~/\w/) { 
                   5526: 	    return 
                   5527:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5528:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5529: 	} else {
                   5530: 	    return '';
                   5531: 	}
                   5532:     } else {
                   5533: 	return '';
                   5534:     }
1.351     www      5535: }
1.353     www      5536: 
                   5537: # ---------------------------------------------------------- Course ID routines
                   5538: # Deal with domain's nohist_courseid.db files
                   5539: #
                   5540: 
                   5541: sub courseidput {
1.921     raeburn  5542:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5543:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5544:     my $outcome;
                   5545:     if ($caller eq 'timeonly') {
                   5546:         my $cids = '';
                   5547:         foreach my $item (keys(%$storehash)) {
                   5548:             $cids.=&escape($item).'&';
                   5549:         }
                   5550:         $cids=~s/\&$//;
                   5551:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5552:                           $coursehome);       
                   5553:     } else {
                   5554:         my $items = '';
                   5555:         foreach my $item (keys(%$storehash)) {
                   5556:             $items.= &escape($item).'='.
                   5557:                      &freeze_escape($$storehash{$item}).'&';
                   5558:         }
                   5559:         $items=~s/\&$//;
                   5560:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5561:                           $coursehome);
1.918     raeburn  5562:     }
                   5563:     if ($outcome eq 'unknown_cmd') {
                   5564:         my $what;
                   5565:         foreach my $cid (keys(%$storehash)) {
                   5566:             $what .= &escape($cid).'=';
1.921     raeburn  5567:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5568:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5569:             }
                   5570:             $what =~ s/\:$/&/;
                   5571:         }
                   5572:         $what =~ s/\&$//;  
                   5573:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5574:     } else {
                   5575:         return $outcome;
                   5576:     }
1.353     www      5577: }
                   5578: 
                   5579: sub courseiddump {
1.921     raeburn  5580:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5581:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5582:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5583:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5584:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5585:     my $as_hash = 1;
                   5586:     my %returnhash;
                   5587:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5588:     my %libserv = &all_library();
                   5589:     foreach my $tryserver (keys(%libserv)) {
                   5590:         if ( (  $hostidflag == 1 
                   5591: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5592: 	     || (!defined($hostidflag)) ) {
                   5593: 
1.918     raeburn  5594: 	    if (($domfilter eq '') ||
                   5595: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5596:                 my $rep;
                   5597:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5598:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5599:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5600:                                 &escape($descfilter), &escape($instcodefilter), 
                   5601:                                 &escape($ownerfilter), &escape($coursefilter),
                   5602:                                 &escape($typefilter), &escape($regexp_ok), 
                   5603:                                 $as_hash, &escape($selfenrollonly), 
                   5604:                                 &escape($catfilter), $showhidden, $caller, 
                   5605:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5606:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5607:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5608:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5609:                 } else {
                   5610:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5611:                              $sincefilter.':'.&escape($descfilter).':'.
                   5612:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5613:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5614:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5615:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5616:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5617:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5618:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5619:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5620:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5621:                 }
                   5622:                      
1.918     raeburn  5623:                 my @pairs=split(/\&/,$rep);
                   5624:                 foreach my $item (@pairs) {
                   5625:                     my ($key,$value)=split(/\=/,$item,2);
                   5626:                     $key = &unescape($key);
                   5627:                     next if ($key =~ /^error: 2 /);
                   5628:                     my $result = &thaw_unescape($value);
                   5629:                     if (ref($result) eq 'HASH') {
                   5630:                         $returnhash{$key}=$result;
                   5631:                     } else {
1.921     raeburn  5632:                         my @responses = split(/:/,$value);
                   5633:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5634:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5635:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5636:                         }
1.1008    raeburn  5637:                     }
1.353     www      5638:                 }
                   5639:             }
                   5640:         }
                   5641:     }
                   5642:     return %returnhash;
                   5643: }
                   5644: 
1.1055    raeburn  5645: sub courselastaccess {
                   5646:     my ($cdom,$cnum,$hostidref) = @_;
                   5647:     my %returnhash;
                   5648:     if ($cdom && $cnum) {
                   5649:         my $chome = &homeserver($cnum,$cdom);
                   5650:         if ($chome ne 'no_host') {
                   5651:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5652:             &extract_lastaccess(\%returnhash,$rep);
                   5653:         }
                   5654:     } else {
                   5655:         if (!$cdom) { $cdom=''; }
                   5656:         my %libserv = &all_library();
                   5657:         foreach my $tryserver (keys(%libserv)) {
                   5658:             if (ref($hostidref) eq 'ARRAY') {
                   5659:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5660:             } 
                   5661:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5662:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5663:                 &extract_lastaccess(\%returnhash,$rep);
                   5664:             }
                   5665:         }
                   5666:     }
                   5667:     return %returnhash;
                   5668: }
                   5669: 
                   5670: sub extract_lastaccess {
                   5671:     my ($returnhash,$rep) = @_;
                   5672:     if (ref($returnhash) eq 'HASH') {
                   5673:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5674:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5675:                  $rep eq '') {
                   5676:             my @pairs=split(/\&/,$rep);
                   5677:             foreach my $item (@pairs) {
                   5678:                 my ($key,$value)=split(/\=/,$item,2);
                   5679:                 $key = &unescape($key);
                   5680:                 next if ($key =~ /^error: 2 /);
                   5681:                 $returnhash->{$key} = &thaw_unescape($value);
                   5682:             }
                   5683:         }
                   5684:     }
                   5685:     return;
                   5686: }
                   5687: 
1.658     raeburn  5688: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5689: 
                   5690: sub dcmailput {
1.685     raeburn  5691:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5692:     my $status = &Apache::lonnet::critical(
1.740     www      5693:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5694:        &escape($message),$server);
1.662     raeburn  5695:     return $status;
                   5696: }
                   5697: 
1.658     raeburn  5698: sub dcmaildump {
                   5699:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5700:     my %returnhash=();
1.846     albertel 5701: 
                   5702:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5703:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5704:                                                          &escape($enddate).':';
                   5705: 	my @esc_senders=map { &escape($_)} @$senders;
                   5706: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5707: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5708:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5709:             if (($key) && ($value)) {
                   5710:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5711:             }
                   5712:         }
                   5713:     }
                   5714:     return %returnhash;
                   5715: }
1.662     raeburn  5716: # ---------------------------------------------------------- Domain roles
                   5717: 
                   5718: sub get_domain_roles {
                   5719:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5720:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5721:         $startdate = '.';
                   5722:     }
1.1018    raeburn  5723:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5724:         $enddate = '.';
                   5725:     }
1.922     raeburn  5726:     my $rolelist;
                   5727:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5728:         $rolelist = join('&',@{$roles});
1.922     raeburn  5729:     }
1.662     raeburn  5730:     my %personnel = ();
1.841     albertel 5731: 
                   5732:     my %servers = &get_servers($dom,'library');
                   5733:     foreach my $tryserver (keys(%servers)) {
                   5734: 	%{$personnel{$tryserver}}=();
                   5735: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5736: 					    &escape($startdate).':'.
                   5737: 					    &escape($enddate).':'.
                   5738: 					    &escape($rolelist), $tryserver))) {
                   5739: 	    my ($key,$value) = split(/\=/,$line,2);
                   5740: 	    if (($key) && ($value)) {
                   5741: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5742: 	    }
                   5743: 	}
1.662     raeburn  5744:     }
                   5745:     return %personnel;
                   5746: }
1.658     raeburn  5747: 
1.1332    raeburn  5748: sub get_active_domroles {
                   5749:     my ($dom,$roles) = @_;
                   5750:     return () unless (ref($roles) eq 'ARRAY');
                   5751:     my $now = time;
                   5752:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5753:     my %domroles;
                   5754:     foreach my $server (keys(%dompersonnel)) {
                   5755:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5756:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5757:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5758:         }
                   5759:     }
                   5760:     return %domroles;
                   5761: }
                   5762: 
1.1057    www      5763: # ----------------------------------------------------------- Interval timing 
1.149     www      5764: 
1.1153    www      5765: {
                   5766: # Caches needed for speedup of navmaps
                   5767: # We don't want to cache this for very long at all (5 seconds at most)
                   5768: # 
                   5769: # The user for whom we cache
                   5770: my $cachedkey='';
                   5771: # The cached times for this user
                   5772: my %cachedtimes=();
                   5773: # When this was last done
1.1282    raeburn  5774: my $cachedtime='';
1.1153    www      5775: 
                   5776: sub load_all_first_access {
1.1308    raeburn  5777:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5778:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5779:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5780:         (!$ignorecache)) {
1.1154    raeburn  5781:         return;
                   5782:     }
                   5783:     $cachedtime=time;
                   5784:     $cachedkey=$uname.':'.$udom;
                   5785:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5786: }
                   5787: 
1.504     albertel 5788: sub get_first_access {
1.1308    raeburn  5789:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5790:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5791:     if ($argsymb) { $symb=$argsymb; }
                   5792:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5793:     if ($argmap) { $map = $argmap; }
1.926     albertel 5794:     if ($type eq 'course') {
                   5795: 	$res='course';
                   5796:     } elsif ($type eq 'map') {
1.588     albertel 5797: 	$res=&symbread($map);
                   5798:     } else {
                   5799: 	$res=$symb;
                   5800:     }
1.1308    raeburn  5801:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5802:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5803: }
                   5804: 
                   5805: sub set_first_access {
1.1162    raeburn  5806:     my ($type,$interval)=@_;
1.790     albertel 5807:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5808:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5809:     if ($type eq 'course') {
                   5810: 	$res='course';
                   5811:     } elsif ($type eq 'map') {
1.588     albertel 5812: 	$res=&symbread($map);
                   5813:     } else {
                   5814: 	$res=$symb;
                   5815:     }
1.1153    www      5816:     $cachedkey='';
1.1162    raeburn  5817:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5818:     if ($firstaccess) {
                   5819:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5820:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5821:                  "in $courseid");
1.1386    raeburn  5822:         return 'already_set';
                   5823:     } else {
1.1162    raeburn  5824:         my $start = time;
                   5825: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5826:                           $udom,$uname);
                   5827:         if ($putres eq 'ok') {
                   5828:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5829:                  $udom,$uname); 
                   5830:             &appenv(
                   5831:                      {
                   5832:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5833:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5834:                      }
                   5835:                   );
1.1365    raeburn  5836:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5837:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5838:             }
1.1386    raeburn  5839:         } elsif ($putres ne 'refused') {
                   5840:             &logthis("Result: $putres when attempting to set first access time ".
                   5841:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5842:         }
                   5843:         return $putres;
1.505     albertel 5844:     }
                   5845:     return 'already_set';
1.504     albertel 5846: }
1.1153    www      5847: }
1.1282    raeburn  5848: 
1.110     www      5849: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5850: 
                   5851: sub expirespread {
                   5852:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5853:     my $cid=$env{'request.course.id'}; 
1.110     www      5854:     if ($cid) {
                   5855:        my $now=time;
                   5856:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5857:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5858:                             $env{'course.'.$cid.'.num'}.
1.110     www      5859: 	        	    ':nohist_expirationdates:'.
                   5860:                             &escape($key).'='.$now,
1.620     albertel 5861:                             $env{'course.'.$cid.'.home'})
1.110     www      5862:     }
                   5863:     return 'ok';
1.14      www      5864: }
                   5865: 
1.109     www      5866: # ----------------------------------------------------- Devalidate Spreadsheets
                   5867: 
                   5868: sub devalidate {
1.325     www      5869:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5870:     my $cid=$env{'request.course.id'}; 
1.109     www      5871:     if ($cid) {
1.391     matthew  5872:         # delete the stored spreadsheets for
                   5873:         # - the student level sheet of this user in course's homespace
                   5874:         # - the assessment level sheet for this resource 
                   5875:         #   for this user in user's homespace
1.553     albertel 5876: 	# - current conditional state info
1.325     www      5877: 	my $key=$uname.':'.$udom.':';
1.109     www      5878:         my $status=
1.299     matthew  5879: 	    &del('nohist_calculatedsheets',
1.391     matthew  5880: 		 [$key.'studentcalc:'],
1.620     albertel 5881: 		 $env{'course.'.$cid.'.domain'},
                   5882: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5883: 		.' '.
                   5884: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5885: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5886:         unless ($status eq 'ok ok') {
                   5887:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5888:                     $uname.' at '.$udom.' for '.
1.109     www      5889: 		    $symb.': '.$status);
1.133     albertel 5890:         }
1.553     albertel 5891: 	&delenv('user.state.'.$cid);
1.109     www      5892:     }
                   5893: }
                   5894: 
1.265     albertel 5895: sub get_scalar {
                   5896:     my ($string,$end) = @_;
                   5897:     my $value;
                   5898:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5899: 	$value = $1;
                   5900:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5901: 	$value = $1;
                   5902:     }
                   5903:     return &unescape($value);
                   5904: }
                   5905: 
                   5906: sub array2str {
                   5907:   my (@array) = @_;
                   5908:   my $result=&arrayref2str(\@array);
                   5909:   $result=~s/^__ARRAY_REF__//;
                   5910:   $result=~s/__END_ARRAY_REF__$//;
                   5911:   return $result;
                   5912: }
                   5913: 
1.204     albertel 5914: sub arrayref2str {
                   5915:   my ($arrayref) = @_;
1.265     albertel 5916:   my $result='__ARRAY_REF__';
1.204     albertel 5917:   foreach my $elem (@$arrayref) {
1.265     albertel 5918:     if(ref($elem) eq 'ARRAY') {
                   5919:       $result.=&arrayref2str($elem).'&';
                   5920:     } elsif(ref($elem) eq 'HASH') {
                   5921:       $result.=&hashref2str($elem).'&';
                   5922:     } elsif(ref($elem)) {
                   5923:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5924:     } else {
                   5925:       $result.=&escape($elem).'&';
                   5926:     }
                   5927:   }
                   5928:   $result=~s/\&$//;
1.265     albertel 5929:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5930:   return $result;
                   5931: }
                   5932: 
1.168     albertel 5933: sub hash2str {
1.204     albertel 5934:   my (%hash) = @_;
                   5935:   my $result=&hashref2str(\%hash);
1.265     albertel 5936:   $result=~s/^__HASH_REF__//;
                   5937:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5938:   return $result;
                   5939: }
                   5940: 
                   5941: sub hashref2str {
                   5942:   my ($hashref)=@_;
1.265     albertel 5943:   my $result='__HASH_REF__';
1.800     albertel 5944:   foreach my $key (sort(keys(%$hashref))) {
                   5945:     if (ref($key) eq 'ARRAY') {
                   5946:       $result.=&arrayref2str($key).'=';
                   5947:     } elsif (ref($key) eq 'HASH') {
                   5948:       $result.=&hashref2str($key).'=';
                   5949:     } elsif (ref($key)) {
1.265     albertel 5950:       $result.='=';
1.800     albertel 5951:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5952:     } else {
1.1132    raeburn  5953: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5954:     }
                   5955: 
1.800     albertel 5956:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5957:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5958:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5959:       $result.=&hashref2str($hashref->{$key}).'&';
                   5960:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5961:        $result.='&';
1.800     albertel 5962:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5963:     } else {
1.800     albertel 5964:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5965:     }
                   5966:   }
1.168     albertel 5967:   $result=~s/\&$//;
1.265     albertel 5968:   $result .= '__END_HASH_REF__';
1.168     albertel 5969:   return $result;
                   5970: }
                   5971: 
                   5972: sub str2hash {
1.265     albertel 5973:     my ($string)=@_;
                   5974:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5975:     return %$hash;
                   5976: }
                   5977: 
                   5978: sub str2hashref {
1.168     albertel 5979:   my ($string) = @_;
1.265     albertel 5980: 
                   5981:   my %hash;
                   5982: 
                   5983:   if($string !~ /^__HASH_REF__/) {
                   5984:       if (! ($string eq '' || !defined($string))) {
                   5985: 	  $hash{'error'}='Not hash reference';
                   5986:       }
                   5987:       return (\%hash, $string);
                   5988:   }
                   5989: 
                   5990:   $string =~ s/^__HASH_REF__//;
                   5991: 
                   5992:   while($string !~ /^__END_HASH_REF__/) {
                   5993:       #key
                   5994:       my $key='';
                   5995:       if($string =~ /^__HASH_REF__/) {
                   5996:           ($key, $string)=&str2hashref($string);
                   5997:           if(defined($key->{'error'})) {
                   5998:               $hash{'error'}='Bad data';
                   5999:               return (\%hash, $string);
                   6000:           }
                   6001:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6002:           ($key, $string)=&str2arrayref($string);
                   6003:           if($key->[0] eq 'Array reference error') {
                   6004:               $hash{'error'}='Bad data';
                   6005:               return (\%hash, $string);
                   6006:           }
                   6007:       } else {
                   6008:           $string =~ s/^(.*?)=//;
1.267     albertel 6009: 	  $key=&unescape($1);
1.265     albertel 6010:       }
                   6011:       $string =~ s/^=//;
                   6012: 
                   6013:       #value
                   6014:       my $value='';
                   6015:       if($string =~ /^__HASH_REF__/) {
                   6016:           ($value, $string)=&str2hashref($string);
                   6017:           if(defined($value->{'error'})) {
                   6018:               $hash{'error'}='Bad data';
                   6019:               return (\%hash, $string);
                   6020:           }
                   6021:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6022:           ($value, $string)=&str2arrayref($string);
                   6023:           if($value->[0] eq 'Array reference error') {
                   6024:               $hash{'error'}='Bad data';
                   6025:               return (\%hash, $string);
                   6026:           }
                   6027:       } else {
                   6028: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6029:       }
                   6030:       $string =~ s/^&//;
                   6031: 
                   6032:       $hash{$key}=$value;
1.204     albertel 6033:   }
1.265     albertel 6034: 
                   6035:   $string =~ s/^__END_HASH_REF__//;
                   6036: 
                   6037:   return (\%hash, $string);
1.204     albertel 6038: }
                   6039: 
                   6040: sub str2array {
1.265     albertel 6041:     my ($string)=@_;
                   6042:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6043:     return @$array;
                   6044: }
                   6045: 
                   6046: sub str2arrayref {
1.204     albertel 6047:   my ($string) = @_;
1.265     albertel 6048:   my @array;
                   6049: 
                   6050:   if($string !~ /^__ARRAY_REF__/) {
                   6051:       if (! ($string eq '' || !defined($string))) {
                   6052: 	  $array[0]='Array reference error';
                   6053:       }
                   6054:       return (\@array, $string);
                   6055:   }
                   6056: 
                   6057:   $string =~ s/^__ARRAY_REF__//;
                   6058: 
                   6059:   while($string !~ /^__END_ARRAY_REF__/) {
                   6060:       my $value='';
                   6061:       if($string =~ /^__HASH_REF__/) {
                   6062:           ($value, $string)=&str2hashref($string);
                   6063:           if(defined($value->{'error'})) {
                   6064:               $array[0] ='Array reference error';
                   6065:               return (\@array, $string);
                   6066:           }
                   6067:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6068:           ($value, $string)=&str2arrayref($string);
                   6069:           if($value->[0] eq 'Array reference error') {
                   6070:               $array[0] ='Array reference error';
                   6071:               return (\@array, $string);
                   6072:           }
                   6073:       } else {
                   6074: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6075:       }
                   6076:       $string =~ s/^&//;
                   6077: 
                   6078:       push(@array, $value);
1.191     harris41 6079:   }
1.265     albertel 6080: 
                   6081:   $string =~ s/^__END_ARRAY_REF__//;
                   6082: 
                   6083:   return (\@array, $string);
1.168     albertel 6084: }
                   6085: 
1.167     albertel 6086: # -------------------------------------------------------------------Temp Store
                   6087: 
1.168     albertel 6088: sub tmpreset {
                   6089:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6090:   if (!$symb) {
                   6091:     $symb=&symbread();
1.620     albertel 6092:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6093:   }
                   6094:   $symb=escape($symb);
                   6095: 
1.620     albertel 6096:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6097:   $namespace=~s/\//\_/g;
                   6098:   $namespace=~s/\W//g;
                   6099: 
1.620     albertel 6100:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6101:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6102:   if ($domain eq 'public' && $stuname eq 'public') {
                   6103:       $stuname=$ENV{'REMOTE_ADDR'};
                   6104:   }
1.1117    foxr     6105:   my $path=LONCAPA::tempdir();
1.168     albertel 6106:   my %hash;
                   6107:   if (tie(%hash,'GDBM_File',
                   6108: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6109: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6110:     foreach my $key (keys(%hash)) {
1.180     albertel 6111:       if ($key=~ /:$symb/) {
1.168     albertel 6112: 	delete($hash{$key});
                   6113:       }
                   6114:     }
                   6115:   }
                   6116: }
                   6117: 
1.167     albertel 6118: sub tmpstore {
1.168     albertel 6119:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6120: 
                   6121:   if (!$symb) {
                   6122:     $symb=&symbread();
1.620     albertel 6123:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6124:   }
                   6125:   $symb=escape($symb);
                   6126: 
                   6127:   if (!$namespace) {
                   6128:     # I don't think we would ever want to store this for a course.
                   6129:     # it seems this will only be used if we don't have a course.
1.620     albertel 6130:     #$namespace=$env{'request.course.id'};
1.168     albertel 6131:     #if (!$namespace) {
1.620     albertel 6132:       $namespace=$env{'request.state'};
1.168     albertel 6133:     #}
                   6134:   }
                   6135:   $namespace=~s/\//\_/g;
                   6136:   $namespace=~s/\W//g;
1.620     albertel 6137:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6138:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6139:   if ($domain eq 'public' && $stuname eq 'public') {
                   6140:       $stuname=$ENV{'REMOTE_ADDR'};
                   6141:   }
1.168     albertel 6142:   my $now=time;
                   6143:   my %hash;
1.1117    foxr     6144:   my $path=LONCAPA::tempdir();
1.168     albertel 6145:   if (tie(%hash,'GDBM_File',
                   6146: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6147: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6148:     $hash{"version:$symb"}++;
                   6149:     my $version=$hash{"version:$symb"};
                   6150:     my $allkeys=''; 
                   6151:     foreach my $key (keys(%$storehash)) {
                   6152:       $allkeys.=$key.':';
1.591     albertel 6153:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6154:     }
                   6155:     $hash{"$version:$symb:timestamp"}=$now;
                   6156:     $allkeys.='timestamp';
                   6157:     $hash{"$version:keys:$symb"}=$allkeys;
                   6158:     if (untie(%hash)) {
                   6159:       return 'ok';
                   6160:     } else {
                   6161:       return "error:$!";
                   6162:     }
                   6163:   } else {
                   6164:     return "error:$!";
                   6165:   }
                   6166: }
1.167     albertel 6167: 
1.168     albertel 6168: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6169: 
1.168     albertel 6170: sub tmprestore {
                   6171:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6172: 
1.168     albertel 6173:   if (!$symb) {
                   6174:     $symb=&symbread();
1.620     albertel 6175:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6176:   }
                   6177:   $symb=escape($symb);
                   6178: 
1.620     albertel 6179:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6180: 
1.620     albertel 6181:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6182:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6183:   if ($domain eq 'public' && $stuname eq 'public') {
                   6184:       $stuname=$ENV{'REMOTE_ADDR'};
                   6185:   }
1.168     albertel 6186:   my %returnhash;
                   6187:   $namespace=~s/\//\_/g;
                   6188:   $namespace=~s/\W//g;
                   6189:   my %hash;
1.1117    foxr     6190:   my $path=LONCAPA::tempdir();
1.168     albertel 6191:   if (tie(%hash,'GDBM_File',
                   6192: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6193: 	  &GDBM_READER(),0640)) {
1.168     albertel 6194:     my $version=$hash{"version:$symb"};
                   6195:     $returnhash{'version'}=$version;
                   6196:     my $scope;
                   6197:     for ($scope=1;$scope<=$version;$scope++) {
                   6198:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6199:       my @keys=split(/:/,$vkeys);
                   6200:       my $key;
                   6201:       $returnhash{"$scope:keys"}=$vkeys;
                   6202:       foreach $key (@keys) {
1.591     albertel 6203: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6204: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6205:       }
                   6206:     }
1.168     albertel 6207:     if (!(untie(%hash))) {
                   6208:       return "error:$!";
                   6209:     }
                   6210:   } else {
                   6211:     return "error:$!";
                   6212:   }
                   6213:   return %returnhash;
1.167     albertel 6214: }
                   6215: 
1.9       www      6216: # ----------------------------------------------------------------------- Store
                   6217: 
                   6218: sub store {
1.1269    raeburn  6219:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6220:     my $home='';
                   6221: 
1.168     albertel 6222:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6223: 
1.213     www      6224:     $symb=&symbclean($symb);
1.122     albertel 6225:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6226: 
1.620     albertel 6227:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6228:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6229: 
                   6230:     &devalidate($symb,$stuname,$domain);
1.109     www      6231: 
                   6232:     $symb=escape($symb);
1.187     www      6233:     if (!$namespace) { 
1.620     albertel 6234:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6235:           return ''; 
                   6236:        } 
                   6237:     }
1.620     albertel 6238:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6239: 
                   6240:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6241:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6242: 
1.12      www      6243:     my $namevalue='';
1.800     albertel 6244:     foreach my $key (keys(%$storehash)) {
                   6245:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6246:     }
1.12      www      6247:     $namevalue=~s/\&$//;
1.187     www      6248:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6249:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6250: }
                   6251: 
1.47      www      6252: # -------------------------------------------------------------- Critical Store
                   6253: 
                   6254: sub cstore {
1.1269    raeburn  6255:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6256:     my $home='';
                   6257: 
1.168     albertel 6258:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6259: 
1.213     www      6260:     $symb=&symbclean($symb);
1.122     albertel 6261:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6262: 
1.620     albertel 6263:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6264:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6265: 
                   6266:     &devalidate($symb,$stuname,$domain);
1.109     www      6267: 
                   6268:     $symb=escape($symb);
1.187     www      6269:     if (!$namespace) { 
1.620     albertel 6270:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6271:           return ''; 
                   6272:        } 
                   6273:     }
1.620     albertel 6274:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6275: 
                   6276:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6277:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6278: 
1.47      www      6279:     my $namevalue='';
1.800     albertel 6280:     foreach my $key (keys(%$storehash)) {
                   6281:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6282:     }
1.47      www      6283:     $namevalue=~s/\&$//;
1.187     www      6284:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6285:     return critical
1.1269    raeburn  6286:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6287: }
                   6288: 
1.9       www      6289: # --------------------------------------------------------------------- Restore
                   6290: 
                   6291: sub restore {
1.124     www      6292:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6293:     my $home='';
                   6294: 
1.168     albertel 6295:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6296: 
1.122     albertel 6297:     if (!$symb) {
1.1224    raeburn  6298:         return if ($namespace eq 'courserequests');
                   6299:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6300:     } else {
1.1224    raeburn  6301:         unless ($namespace eq 'courserequests') {
                   6302:             $symb=&escape(&symbclean($symb));
                   6303:         }
1.122     albertel 6304:     }
1.188     www      6305:     if (!$namespace) { 
1.620     albertel 6306:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6307:           return ''; 
                   6308:        } 
                   6309:     }
1.620     albertel 6310:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6311:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6312:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6313:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6314: 
1.12      www      6315:     my %returnhash=();
1.800     albertel 6316:     foreach my $line (split(/\&/,$answer)) {
                   6317: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6318:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6319:     }
1.75      www      6320:     my $version;
                   6321:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6322:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6323:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6324:        }
1.75      www      6325:     }
1.13      www      6326:     return %returnhash;
1.34      www      6327: }
                   6328: 
                   6329: # ---------------------------------------------------------- Course Description
1.1118    foxr     6330: #
                   6331: #  
1.34      www      6332: 
                   6333: sub coursedescription {
1.731     albertel 6334:     my ($courseid,$args)=@_;
1.34      www      6335:     $courseid=~s/^\///;
1.49      www      6336:     $courseid=~s/\_/\//g;
1.34      www      6337:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6338:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6339:     my $normalid=$cdomain.'_'.$cnum;
                   6340:     # need to always cache even if we get errors otherwise we keep 
                   6341:     # trying and trying and trying to get the course description.
                   6342:     my %envhash=();
                   6343:     my %returnhash=();
1.731     albertel 6344:     
                   6345:     my $expiretime=600;
                   6346:     if ($env{'request.course.id'} eq $normalid) {
                   6347: 	$expiretime=120;
                   6348:     }
                   6349: 
                   6350:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6351:     if (!$args->{'freshen_cache'}
                   6352: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6353: 	foreach my $key (keys(%env)) {
                   6354: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6355: 	    my ($setting) = $1;
                   6356: 	    $returnhash{$setting} = $env{$key};
                   6357: 	}
                   6358: 	return %returnhash;
                   6359:     }
                   6360: 
1.1118    foxr     6361:     # get the data again
                   6362: 
1.731     albertel 6363:     if (!$args->{'one_time'}) {
                   6364: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6365:     }
1.811     albertel 6366: 
1.34      www      6367:     if ($chome ne 'no_host') {
1.302     albertel 6368:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6369:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6370: 	   my $username = $env{'user.name'}; # Defult username
                   6371: 	   if(defined $args->{'user'}) {
                   6372: 	       $username = $args->{'user'};
                   6373: 	   }
1.129     albertel 6374:            $returnhash{'home'}= $chome;
                   6375: 	   $returnhash{'domain'} = $cdomain;
                   6376: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6377:            if (!defined($returnhash{'type'})) {
                   6378:                $returnhash{'type'} = 'Course';
                   6379:            }
1.130     albertel 6380:            while (my ($name,$value) = each %returnhash) {
1.53      www      6381:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6382:            }
1.270     www      6383:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6384:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6385: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6386:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6387:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6388:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6389:        }
                   6390:     }
1.731     albertel 6391:     if (!$args->{'one_time'}) {
1.949     raeburn  6392: 	&appenv(\%envhash);
1.731     albertel 6393:     }
1.302     albertel 6394:     return %returnhash;
1.461     www      6395: }
                   6396: 
1.1080    raeburn  6397: sub update_released_required {
                   6398:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6399:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6400:         $cid = $env{'request.course.id'};
                   6401:         $cdom = $env{'course.'.$cid.'.domain'};
                   6402:         $cnum = $env{'course.'.$cid.'.num'};
                   6403:         $chome = $env{'course.'.$cid.'.home'};
                   6404:     }
                   6405:     if ($needsrelease) {
                   6406:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6407:         my $needsupdate;
                   6408:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6409:             $needsupdate = 1;
                   6410:         } else {
                   6411:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6412:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6413:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6414:                 $needsupdate = 1;
                   6415:             }
                   6416:         }
                   6417:         if ($needsupdate) {
                   6418:             my %needshash = (
                   6419:                              'internal.releaserequired' => $needsrelease,
                   6420:                             );
                   6421:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6422:             if ($putresult eq 'ok') {
                   6423:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6424:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6425:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6426:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6427:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6428:                 }
                   6429:             }
                   6430:         }
                   6431:     }
                   6432:     return;
                   6433: }
                   6434: 
1.461     www      6435: # -------------------------------------------------See if a user is privileged
                   6436: 
                   6437: sub privileged {
1.1219    raeburn  6438:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6439:     my $now = time;
1.1219    raeburn  6440:     my $roles;
                   6441:     if (ref($possroles) eq 'ARRAY') {
                   6442:         $roles = $possroles; 
                   6443:     } else {
                   6444:         $roles = ['dc','su'];
                   6445:     }
                   6446:     if (ref($possdomains) eq 'ARRAY') {
                   6447:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6448:         foreach my $dom (@{$possdomains}) {
                   6449:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6450:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6451:                 foreach my $role (@{$roles}) {
                   6452:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6453:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6454:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6455:                             return 1 unless (($end && $end < $now) ||
                   6456:                                              ($start && $start > $now));
                   6457:                         }
                   6458:                     }
                   6459:                 }
                   6460:             }
                   6461:         }
                   6462:     } else {
                   6463:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6464:         my $now = time;
1.1170    droeschl 6465: 
1.1275    musolffc 6466:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6467:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6468:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6469:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6470:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6471:             }
1.1219    raeburn  6472:         }
                   6473:     }
                   6474:     return 0;
                   6475: }
1.1170    droeschl 6476: 
1.1219    raeburn  6477: sub privileged_by_domain {
                   6478:     my ($domains,$roles) = @_;
                   6479:     my %privileged = ();
                   6480:     my $cachetime = 60*60*24;
                   6481:     my $now = time;
                   6482:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6483:         return %privileged;
                   6484:     }
                   6485:     foreach my $dom (@{$domains}) {
                   6486:         next if (ref($privileged{$dom}) eq 'HASH');
                   6487:         my $needroles;
                   6488:         foreach my $role (@{$roles}) {
                   6489:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6490:             if (defined($cached)) {
                   6491:                 if (ref($result) eq 'HASH') {
                   6492:                     $privileged{$dom}{$role} = $result;
                   6493:                 }
                   6494:             } else {
                   6495:                 $needroles = 1;
                   6496:             }
                   6497:         }
                   6498:         if ($needroles) {
                   6499:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6500:             $privileged{$dom} = {};
                   6501:             foreach my $server (keys(%dompersonnel)) {
                   6502:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6503:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6504:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6505:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6506:                         next if ($end && $end < $now);
                   6507:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6508:                             $dompersonnel{$server}{$item};
                   6509:                     }
                   6510:                 }
                   6511:             }
                   6512:             if (ref($privileged{$dom}) eq 'HASH') {
                   6513:                 foreach my $role (@{$roles}) {
                   6514:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6515:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6516:                     } else {
                   6517:                         my %hash = ();
                   6518:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6519:                     }
                   6520:                 }
                   6521:             }
                   6522:         }
                   6523:     }
                   6524:     return %privileged;
1.9       www      6525: }
1.1       albertel 6526: 
1.103     harris41 6527: # -------------------------------------------------------- Get user privileges
1.11      www      6528: 
                   6529: sub rolesinit {
1.1169    droeschl 6530:     my ($domain, $username) = @_;
                   6531:     my %userroles = ('user.login.time' => time);
                   6532:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6533: 
                   6534:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6535:     # also, blocking can be triggered by an activating timer
                   6536:     # it's saved in the user's %env.
                   6537:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6538:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6539:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6540:         %timerintchk, %timerintenv);
                   6541: 
1.1162    raeburn  6542:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6543:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6544:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6545:     }
1.1169    droeschl 6546: 
1.1162    raeburn  6547:     foreach my $key (keys(%timerinterval)) {
                   6548:         my ($cid,$rest) = split(/\0/,$key);
                   6549:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6550:     }
1.1169    droeschl 6551: 
1.11      www      6552:     my %allroles=();
1.1162    raeburn  6553:     my %allgroups=();
1.11      www      6554: 
1.1274    raeburn  6555:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6556:         my $role = $rolesdump{$area};
                   6557:         $area =~ s/\_\w\w$//;
                   6558: 
                   6559:         my ($trole, $tend, $tstart, $group_privs);
                   6560: 
                   6561:         if ($role =~ /^cr/) {
                   6562:         # Custom role, defined by a user 
                   6563:         # e.g., user.role.cr/msu/smith/mynewrole
                   6564:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6565:                 $trole = $1;
                   6566:                 ($tend, $tstart) = split('_', $2);
                   6567:             } else {
                   6568:                 $trole = $role;
                   6569:             }
                   6570:         } elsif ($role =~ m|^gr/|) {
                   6571:         # Role of member in a group, defined within a course/community
                   6572:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6573:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6574:             next if $tstart eq '-1';
                   6575:             ($trole, $group_privs) = split(/\//, $trole);
                   6576:             $group_privs = &unescape($group_privs);
                   6577:         } else {
                   6578:         # Just a normal role, defined in roles.tab
                   6579:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6580:         }
                   6581: 
                   6582:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6583:                  $username);
                   6584:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6585: 
                   6586:         # role expired or not available yet?
                   6587:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6588:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6589: 
                   6590:         next if $area eq '' or $trole eq '';
                   6591: 
                   6592:         my $spec = "$trole.$area";
                   6593:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6594: 
                   6595:         if ($trole =~ /^cr\//) {
                   6596:         # Custom role, defined by a user
                   6597:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6598:         } elsif ($trole eq 'gr') {
                   6599:         # Role of a member in a group, defined within a course/community
                   6600:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6601:             next;
                   6602:         } else {
                   6603:         # Normal role, defined in roles.tab
                   6604:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6605:         }
                   6606: 
                   6607:         my $cid = $tdomain.'_'.$trest;
                   6608:         unless ($firstaccchk{$cid}) {
                   6609:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6610:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6611:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6612:                         $coursetimerstarts{$cid}{$item}; 
                   6613:                 }
                   6614:             }
                   6615:             $firstaccchk{$cid} = 1;
                   6616:         }
                   6617:         unless ($timerintchk{$cid}) {
                   6618:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6619:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6620:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6621:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6622:                 }
1.12      www      6623:             }
1.1169    droeschl 6624:             $timerintchk{$cid} = 1;
1.191     harris41 6625:         }
1.11      www      6626:     }
1.1169    droeschl 6627: 
1.1341    raeburn  6628:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6629:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6630:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6631:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6632: 
1.1162    raeburn  6633:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6634: }
                   6635: 
1.567     raeburn  6636: sub set_arearole {
1.1215    raeburn  6637:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6638:     unless ($nolog) {
1.567     raeburn  6639: # log the associated role with the area
1.1215    raeburn  6640:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6641:     }
1.743     albertel 6642:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6643: }
                   6644: 
                   6645: sub custom_roleprivs {
                   6646:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6647:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6648:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6649:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6650:         my ($rdummy,$roledef)=
                   6651:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6652:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6653:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6654:             if (defined($syspriv)) {
1.1043    raeburn  6655:                 if ($trest =~ /^$match_community$/) {
                   6656:                     $syspriv =~ s/bre\&S//; 
                   6657:                 }
1.567     raeburn  6658:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6659:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6660:             }
                   6661:             if ($tdomain ne '') {
                   6662:                 if (defined($dompriv)) {
                   6663:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6664:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6665:                 }
                   6666:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6667:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6668:                         my $rolename = $1;
                   6669:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6670:                     }
1.567     raeburn  6671:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6672:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6673:                 }
                   6674:             }
                   6675:         }
                   6676:     }
                   6677: }
                   6678: 
1.1332    raeburn  6679: sub course_adhocrole_privs {
                   6680:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6681:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6682:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6683:         my (%currprivs,%storeprivs);
                   6684:         foreach my $item (split(/:/,$coursepriv)) {
                   6685:             my ($priv,$restrict) = split(/\&/,$item);
                   6686:             $currprivs{$priv} = $restrict;
                   6687:         }
                   6688:         my (%possadd,%possremove,%full);
                   6689:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6690:             my ($priv,$restrict)=split(/\&/,$item);
                   6691:             $full{$priv} = $restrict;
                   6692:         }
                   6693:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6694:              next if ($item eq '');
                   6695:              my ($rule,$rest) = split(/=/,$item);
                   6696:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6697:              foreach my $priv (split(/:/,$rest)) {
                   6698:                  if ($priv ne '') {
                   6699:                      if ($rule eq 'off') {
                   6700:                          $possremove{$priv} = 1;
                   6701:                      } else {
                   6702:                          $possadd{$priv} = 1;
                   6703:                      }
                   6704:                  }
                   6705:              }
                   6706:          }
                   6707:          foreach my $priv (sort(keys(%full))) {
                   6708:              if (exists($currprivs{$priv})) {
                   6709:                  unless (exists($possremove{$priv})) {
                   6710:                      $storeprivs{$priv} = $currprivs{$priv};
                   6711:                  }
                   6712:              } elsif (exists($possadd{$priv})) {
                   6713:                  $storeprivs{$priv} = $full{$priv};
                   6714:              }
                   6715:          }
                   6716:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6717:      }
                   6718:      return $coursepriv;
                   6719: }
                   6720: 
1.678     raeburn  6721: sub group_roleprivs {
                   6722:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6723:     my $access = 1;
                   6724:     my $now = time;
                   6725:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6726:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6727:     if ($access) {
1.811     albertel 6728:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6729:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6730:     }
                   6731: }
1.567     raeburn  6732: 
                   6733: sub standard_roleprivs {
                   6734:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6735:     if (defined($pr{$trole.':s'})) {
                   6736:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6737:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6738:     }
                   6739:     if ($tdomain ne '') {
                   6740:         if (defined($pr{$trole.':d'})) {
                   6741:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6742:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6743:         }
                   6744:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6745:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6746:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6747:         }
                   6748:     }
                   6749: }
                   6750: 
                   6751: sub set_userprivs {
1.1064    raeburn  6752:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6753:     my $author=0;
                   6754:     my $adv=0;
1.1341    raeburn  6755:     my $rar=0;
1.678     raeburn  6756:     my %grouproles = ();
                   6757:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6758:         my @groupkeys; 
1.1000    raeburn  6759:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6760:             push(@groupkeys,$role);
                   6761:         }
                   6762:         if (ref($groups_roles) eq 'HASH') {
                   6763:             foreach my $key (keys(%{$groups_roles})) {
                   6764:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6765:                     push(@groupkeys,$key);
                   6766:                 }
                   6767:             }
                   6768:         }
                   6769:         if (@groupkeys > 0) {
                   6770:             foreach my $role (@groupkeys) {
                   6771:                 my ($trole,$area,$sec,$extendedarea);
                   6772:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6773:                     $trole = $1;
                   6774:                     $area = $2;
                   6775:                     $sec = $3;
                   6776:                     $extendedarea = $area.$sec;
                   6777:                     if (exists($$allgroups{$area})) {
                   6778:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6779:                             my $spec = $trole.'.'.$extendedarea;
                   6780:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6781:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6782:                         }
1.678     raeburn  6783:                     }
                   6784:                 }
                   6785:             }
                   6786:         }
                   6787:     }
1.800     albertel 6788:     foreach my $group (keys(%grouproles)) {
                   6789:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6790:     }
1.800     albertel 6791:     foreach my $role (keys(%{$allroles})) {
                   6792:         my %thesepriv;
1.941     raeburn  6793:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6794:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6795:             if ($item ne '') {
                   6796:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6797:                 if ($restrictions eq '') {
                   6798:                     $thesepriv{$privilege}='F';
                   6799:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6800:                     $thesepriv{$privilege}.=$restrictions;
                   6801:                 }
                   6802:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6803:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6804:             }
                   6805:         }
                   6806:         my $thesestr='';
1.1104    raeburn  6807:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6808: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6809: 	}
                   6810:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6811:     }
1.1341    raeburn  6812:     return ($author,$adv,$rar);
1.567     raeburn  6813: }
                   6814: 
1.994     raeburn  6815: sub role_status {
1.1104    raeburn  6816:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6817:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6818:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6819:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6820:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6821:             $$where = '/'.$two;
1.994     raeburn  6822:             $$trolecode=$$role.'.'.$$where;
                   6823:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6824:             $$tstatus='is';
1.1104    raeburn  6825:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6826:                 $$tstatus='future';
1.1034    raeburn  6827:                 if ($$tstart<$now) {
                   6828:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6829:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6830:                             my (%allroles,%allgroups,$group_privs,
                   6831:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6832:                             my %userroles = (
                   6833:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6834:                             );
1.1064    raeburn  6835:                             @rolecodes = ('cm'); 
1.1002    raeburn  6836:                             my $spec=$$role.'.'.$$where;
                   6837:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6838:                             if ($$role =~ /^cr\//) {
                   6839:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6840:                                 push(@rolecodes,'cr');
1.1002    raeburn  6841:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6842:                                 push(@rolecodes,$$role);
1.1002    raeburn  6843:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6844:                                                     $env{'user.name'});
1.1064    raeburn  6845:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6846:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6847:                                 $group_privs = &unescape($group_privs);
                   6848:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6849:                                 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  6850:                                 &get_groups_roles($tdomain,$trest,
                   6851:                                                   \%course_roles,\@rolecodes,
                   6852:                                                   \%groups_roles);
1.1002    raeburn  6853:                             } else {
1.1064    raeburn  6854:                                 push(@rolecodes,$$role);
1.1002    raeburn  6855:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6856:                             }
1.1341    raeburn  6857:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6858:                                                                    \%groups_roles);
1.1064    raeburn  6859:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6860:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6861:                         }
                   6862:                     }
1.1034    raeburn  6863:                     $$tstatus = 'is';
1.1002    raeburn  6864:                 }
1.994     raeburn  6865:             }
                   6866:             if ($$tend) {
1.1104    raeburn  6867:                 if ($$tend<$update) {
1.994     raeburn  6868:                     $$tstatus='expired';
                   6869:                 } elsif ($$tend<$now) {
                   6870:                     $$tstatus='will_not';
                   6871:                 }
                   6872:             }
                   6873:         }
                   6874:     }
                   6875: }
                   6876: 
1.1104    raeburn  6877: sub get_groups_roles {
                   6878:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6879:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6880:                   (ref($rolecodes) eq 'ARRAY') && 
                   6881:                   (ref($groups_roles) eq 'HASH')); 
                   6882:     if (keys(%{$cdom_courseroles}) > 0) {
                   6883:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6884:         if ($cdom ne '' && $cnum ne '') {
                   6885:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6886:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6887:                     my $crsrole = $1;
                   6888:                     my $crssec = $2;
                   6889:                     if ($crsrole =~ /^cr/) {
                   6890:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6891:                             push(@{$rolecodes},'cr');
                   6892:                         }
                   6893:                     } else {
                   6894:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6895:                             push(@{$rolecodes},$crsrole);
                   6896:                         }
                   6897:                     }
                   6898:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6899:                     if ($crssec ne '') {
                   6900:                         $rolekey .= "/$crssec";
                   6901:                     }
                   6902:                     $rolekey .= './';
                   6903:                     $groups_roles->{$rolekey} = $rolecodes;
                   6904:                 }
                   6905:             }
                   6906:         }
                   6907:     }
                   6908:     return;
                   6909: }
                   6910: 
                   6911: sub delete_env_groupprivs {
                   6912:     my ($where,$courseroles,$possroles) = @_;
                   6913:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6914:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6915:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6916:         %{$courseroles->{$udom}} =
                   6917:             &get_my_roles('','','userroles',['active'],
                   6918:                           $possroles,[$udom],1);
                   6919:     }
                   6920:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6921:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6922:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6923:             my $area = '/'.$cdom.'/'.$cnum;
                   6924:             my $privkey = "user.priv.$crsrole.$area";
                   6925:             if ($crssec ne '') {
                   6926:                 $privkey .= '/'.$crssec;
                   6927:             }
                   6928:             $privkey .= ".$area/$group";
                   6929:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6930:         }
                   6931:     }
                   6932:     return;
                   6933: }
                   6934: 
1.994     raeburn  6935: sub check_adhoc_privs {
1.1329    raeburn  6936:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6937:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6938:     if ($sec) {
                   6939:         $cckey .= '/'.$sec;
                   6940:     } 
1.1185    raeburn  6941:     my $setprivs;
1.994     raeburn  6942:     if ($env{$cckey}) {
                   6943:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6944:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6945:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6946:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6947:             $setprivs = 1;
1.994     raeburn  6948:         }
                   6949:     } else {
1.1330    raeburn  6950:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6951:         $setprivs = 1;
1.994     raeburn  6952:     }
1.1185    raeburn  6953:     return $setprivs;
1.994     raeburn  6954: }
                   6955: 
                   6956: sub set_adhoc_privileges {
1.1326    raeburn  6957: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6958:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6959:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6960:     if ($sec ne '') {
                   6961:         $area .= '/'.$sec;
                   6962:     }
1.994     raeburn  6963:     my $spec = $role.'.'.$area;
                   6964:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6965:                                   $env{'user.name'},1);
1.1326    raeburn  6966:     my %rolehash = ();
1.1332    raeburn  6967:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6968:         my $rolename = $1;
1.1326    raeburn  6969:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6970:         my %domdef = &get_domain_defaults($dcdom);
                   6971:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6972:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6973:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6974:             }
                   6975:         }
1.1326    raeburn  6976:     } else {
                   6977:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6978:     }
1.1341    raeburn  6979:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6980:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6981:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  6982:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6983:             ($caller eq 'tiny')) {
1.1088    raeburn  6984:         &appenv( {'request.role'        => $spec,
                   6985:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6986:                   'request.course.sec'  => $sec,
1.1088    raeburn  6987:                  }
                   6988:                );
                   6989:         my $tadv=0;
                   6990:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6991:         &appenv({'request.role.adv'    => $tadv});
                   6992:     }
1.994     raeburn  6993: }
                   6994: 
1.12      www      6995: # --------------------------------------------------------------- get interface
                   6996: 
                   6997: sub get {
1.131     albertel 6998:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6999:    my $items='';
1.800     albertel 7000:    foreach my $item (@$storearr) {
                   7001:        $items.=&escape($item).'&';
1.191     harris41 7002:    }
1.12      www      7003:    $items=~s/\&$//;
1.620     albertel 7004:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7005:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7006:    my $uhome=&homeserver($uname,$udomain);
                   7007: 
1.133     albertel 7008:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7009:    my @pairs=split(/\&/,$rep);
1.273     albertel 7010:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7011:      return @pairs;
                   7012:    }
1.15      www      7013:    my %returnhash=();
1.42      www      7014:    my $i=0;
1.800     albertel 7015:    foreach my $item (@$storearr) {
                   7016:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7017:       $i++;
1.191     harris41 7018:    }
1.15      www      7019:    return %returnhash;
1.27      www      7020: }
                   7021: 
                   7022: # --------------------------------------------------------------- del interface
                   7023: 
                   7024: sub del {
1.133     albertel 7025:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7026:    my $items='';
1.800     albertel 7027:    foreach my $item (@$storearr) {
                   7028:        $items.=&escape($item).'&';
1.191     harris41 7029:    }
1.984     neumanie 7030: 
1.27      www      7031:    $items=~s/\&$//;
1.620     albertel 7032:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7033:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7034:    my $uhome=&homeserver($uname,$udomain);
                   7035:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7036: }
                   7037: 
                   7038: # -------------------------------------------------------------- dump interface
                   7039: 
1.1180    droeschl 7040: sub unserialize {
                   7041:     my ($rep, $escapedkeys) = @_;
                   7042: 
                   7043:     return {} if $rep =~ /^error/;
                   7044: 
                   7045:     my %returnhash=();
1.1252    raeburn  7046: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7047: 	    my ($key, $value) = split(/=/, $item, 2);
                   7048: 	    $key = unescape($key) unless $escapedkeys;
                   7049: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7050: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7051: 	}
                   7052:     #return %returnhash;
                   7053:     return \%returnhash;
                   7054: }        
                   7055: 
                   7056: # see Lond::dump_with_regexp
                   7057: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7058: sub dump {
1.1180    droeschl 7059:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 7060:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7061:     if (!$uname) { $uname=$env{'user.name'}; }
                   7062:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7063: 
1.1266    raeburn  7064:     if ($regexp) {
                   7065:         $regexp=&escape($regexp);
                   7066:     } else {
                   7067:         $regexp='.';
                   7068:     }
1.1180    droeschl 7069:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7070:         # user is hosted on this machine
1.1266    raeburn  7071:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7072:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7073:         return %{unserialize($reply, $escapedkeys)};
                   7074:     }
1.1166    raeburn  7075:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 7076:     my @pairs=split(/\&/,$rep);
                   7077:     my %returnhash=();
1.1098    foxr     7078:     if (!($rep =~ /^error/ )) {
                   7079: 	foreach my $item (@pairs) {
                   7080: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7081:         $key = unescape($key) unless $escapedkeys;
                   7082:         #$key = &unescape($key);
1.1098    foxr     7083: 	    next if ($key =~ /^error: 2 /);
                   7084: 	    $returnhash{$key}=&thaw_unescape($value);
                   7085: 	}
1.755     albertel 7086:     }
                   7087:     return %returnhash;
1.407     www      7088: }
                   7089: 
1.1098    foxr     7090: 
1.717     albertel 7091: # --------------------------------------------------------- dumpstore interface
                   7092: 
                   7093: sub dumpstore {
                   7094:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7095:    # same as dump but keys must be escaped. They may contain colon separated
                   7096:    # lists of values that may themself contain colons (e.g. symbs).
                   7097:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7098: }
                   7099: 
1.407     www      7100: # -------------------------------------------------------------- keys interface
                   7101: 
                   7102: sub getkeys {
                   7103:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7104:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7105:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7106:    my $uhome=&homeserver($uname,$udomain);
                   7107:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7108:    my @keyarray=();
1.800     albertel 7109:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7110:       next if ($key =~ /^error: 2 /);
1.800     albertel 7111:       push(@keyarray,&unescape($key));
1.407     www      7112:    }
                   7113:    return @keyarray;
1.318     matthew  7114: }
                   7115: 
1.319     matthew  7116: # --------------------------------------------------------------- currentdump
                   7117: sub currentdump {
1.328     matthew  7118:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7119:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7120:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7121:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7122:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7123:    my $rep;
                   7124: 
                   7125:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7126:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7127:                    $courseid)));
                   7128:    } else {
                   7129:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7130:    }
                   7131: 
1.318     matthew  7132:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7133:    #
1.318     matthew  7134:    my %returnhash=();
1.319     matthew  7135:    #
1.1343    raeburn  7136:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7137:        # an old lond will not know currentdump
                   7138:        # Do a dump and make it look like a currentdump
1.822     albertel 7139:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7140:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7141:        my %hash = @tmp;
                   7142:        @tmp=();
1.424     matthew  7143:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7144:    } else {
                   7145:        my @pairs=split(/\&/,$rep);
1.800     albertel 7146:        foreach my $pair (@pairs) {
                   7147:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7148:            my ($symb,$param) = split(/:/,$key);
                   7149:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7150:                                                         &thaw_unescape($value);
1.319     matthew  7151:        }
1.191     harris41 7152:    }
1.12      www      7153:    return %returnhash;
1.424     matthew  7154: }
                   7155: 
                   7156: sub convert_dump_to_currentdump{
                   7157:     my %hash = %{shift()};
                   7158:     my %returnhash;
                   7159:     # Code ripped from lond, essentially.  The only difference
                   7160:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7161:     # we might run in to problems with parameter names =~ /^v\./
                   7162:     while (my ($key,$value) = each(%hash)) {
                   7163:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7164: 	$symb  = &unescape($symb);
                   7165: 	$param = &unescape($param);
1.424     matthew  7166:         next if ($v eq 'version' || $symb eq 'keys');
                   7167:         next if (exists($returnhash{$symb}) &&
                   7168:                  exists($returnhash{$symb}->{$param}) &&
                   7169:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7170:         $returnhash{$symb}->{$param}=$value;
                   7171:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7172:     }
                   7173:     #
                   7174:     # Remove all of the keys in the hashes which keep track of
                   7175:     # the version of the parameter.
                   7176:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7177:         # use a foreach because we are going to delete from the hash.
                   7178:         foreach my $key (keys(%$param_hash)) {
                   7179:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7180:         }
                   7181:     }
                   7182:     return \%returnhash;
1.12      www      7183: }
                   7184: 
1.627     albertel 7185: # ------------------------------------------------------ critical inc interface
                   7186: 
                   7187: sub cinc {
                   7188:     return &inc(@_,'critical');
                   7189: }
                   7190: 
1.449     matthew  7191: # --------------------------------------------------------------- inc interface
                   7192: 
                   7193: sub inc {
1.627     albertel 7194:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7195:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7196:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7197:     my $uhome=&homeserver($uname,$udomain);
                   7198:     my $items='';
                   7199:     if (! ref($store)) {
                   7200:         # got a single value, so use that instead
                   7201:         $items = &escape($store).'=&';
                   7202:     } elsif (ref($store) eq 'SCALAR') {
                   7203:         $items = &escape($$store).'=&';        
                   7204:     } elsif (ref($store) eq 'ARRAY') {
                   7205:         $items = join('=&',map {&escape($_);} @{$store});
                   7206:     } elsif (ref($store) eq 'HASH') {
                   7207:         while (my($key,$value) = each(%{$store})) {
                   7208:             $items.= &escape($key).'='.&escape($value).'&';
                   7209:         }
                   7210:     }
                   7211:     $items=~s/\&$//;
1.627     albertel 7212:     if ($critical) {
                   7213: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7214:     } else {
                   7215: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7216:     }
1.449     matthew  7217: }
                   7218: 
1.12      www      7219: # --------------------------------------------------------------- put interface
                   7220: 
                   7221: sub put {
1.134     albertel 7222:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7223:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7224:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7225:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7226:    my $items='';
1.800     albertel 7227:    foreach my $item (keys(%$storehash)) {
                   7228:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7229:    }
1.12      www      7230:    $items=~s/\&$//;
1.134     albertel 7231:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7232: }
                   7233: 
1.631     albertel 7234: # ------------------------------------------------------------ newput interface
                   7235: 
                   7236: sub newput {
                   7237:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7238:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7239:    if (!$uname) { $uname=$env{'user.name'}; }
                   7240:    my $uhome=&homeserver($uname,$udomain);
                   7241:    my $items='';
                   7242:    foreach my $key (keys(%$storehash)) {
                   7243:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7244:    }
                   7245:    $items=~s/\&$//;
                   7246:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7247: }
                   7248: 
                   7249: # ---------------------------------------------------------  putstore interface
                   7250: 
1.524     raeburn  7251: sub putstore {
1.1269    raeburn  7252:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7253:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7254:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7255:    my $uhome=&homeserver($uname,$udomain);
                   7256:    my $items='';
1.715     albertel 7257:    foreach my $key (keys(%$storehash)) {
                   7258:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7259:    }
1.715     albertel 7260:    $items=~s/\&$//;
1.716     albertel 7261:    my $esc_symb=&escape($symb);
                   7262:    my $esc_v=&escape($version);
1.715     albertel 7263:    my $reply =
1.716     albertel 7264:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7265: 	      $uhome);
1.1269    raeburn  7266:    if (($tolog) && ($reply eq 'ok')) {
                   7267:        my $namevalue='';
                   7268:        foreach my $key (keys(%{$storehash})) {
                   7269:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7270:        }
                   7271:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7272:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7273:                      '&version='.$esc_v.
                   7274:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7275:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7276:    }
1.715     albertel 7277:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7278:        # gfall back to way things use to be done
1.715     albertel 7279:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7280: 			    $uname);
1.524     raeburn  7281:    }
1.715     albertel 7282:    return $reply;
                   7283: }
                   7284: 
                   7285: sub old_putstore {
1.716     albertel 7286:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7287:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7288:     if (!$uname) { $uname=$env{'user.name'}; }
                   7289:     my $uhome=&homeserver($uname,$udomain);
                   7290:     my %newstorehash;
1.800     albertel 7291:     foreach my $item (keys(%$storehash)) {
                   7292: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7293: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7294:     }
                   7295:     my $items='';
                   7296:     my %allitems = ();
1.800     albertel 7297:     foreach my $item (keys(%newstorehash)) {
                   7298: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7299: 	    my $key = $1.':keys:'.$2;
                   7300: 	    $allitems{$key} .= $3.':';
                   7301: 	}
1.800     albertel 7302: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7303:     }
1.800     albertel 7304:     foreach my $item (keys(%allitems)) {
                   7305: 	$allitems{$item} =~ s/\:$//;
                   7306: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7307:     }
                   7308:     $items=~s/\&$//;
                   7309:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7310: }
                   7311: 
1.47      www      7312: # ------------------------------------------------------ critical put interface
                   7313: 
                   7314: sub cput {
1.134     albertel 7315:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7316:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7317:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7318:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7319:    my $items='';
1.800     albertel 7320:    foreach my $item (keys(%$storehash)) {
                   7321:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7322:    }
1.47      www      7323:    $items=~s/\&$//;
1.134     albertel 7324:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7325: }
                   7326: 
                   7327: # -------------------------------------------------------------- eget interface
                   7328: 
                   7329: sub eget {
1.133     albertel 7330:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7331:    my $items='';
1.800     albertel 7332:    foreach my $item (@$storearr) {
                   7333:        $items.=&escape($item).'&';
1.191     harris41 7334:    }
1.12      www      7335:    $items=~s/\&$//;
1.620     albertel 7336:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7337:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7338:    my $uhome=&homeserver($uname,$udomain);
                   7339:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7340:    my @pairs=split(/\&/,$rep);
                   7341:    my %returnhash=();
1.42      www      7342:    my $i=0;
1.800     albertel 7343:    foreach my $item (@$storearr) {
                   7344:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7345:       $i++;
1.191     harris41 7346:    }
1.12      www      7347:    return %returnhash;
                   7348: }
                   7349: 
1.667     albertel 7350: # ------------------------------------------------------------ tmpput interface
                   7351: sub tmpput {
1.802     raeburn  7352:     my ($storehash,$server,$context)=@_;
1.667     albertel 7353:     my $items='';
1.800     albertel 7354:     foreach my $item (keys(%$storehash)) {
                   7355: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7356:     }
                   7357:     $items=~s/\&$//;
1.802     raeburn  7358:     if (defined($context)) {
                   7359:         $items .= ':'.&escape($context);
                   7360:     }
1.667     albertel 7361:     return &reply("tmpput:$items",$server);
                   7362: }
                   7363: 
                   7364: # ------------------------------------------------------------ tmpget interface
                   7365: sub tmpget {
1.688     albertel 7366:     my ($token,$server)=@_;
                   7367:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7368:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7369:     my %returnhash;
1.1328    raeburn  7370:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7371:         return %returnhash;
                   7372:     }
1.667     albertel 7373:     foreach my $item (split(/\&/,$rep)) {
                   7374: 	my ($key,$value)=split(/=/,$item);
                   7375: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7376:     }
                   7377:     return %returnhash;
                   7378: }
                   7379: 
1.1113    raeburn  7380: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7381: sub tmpdel {
                   7382:     my ($token,$server)=@_;
                   7383:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7384:     return &reply("tmpdel:$token",$server);
                   7385: }
                   7386: 
1.1198    raeburn  7387: # ------------------------------------------------------------ get_timebased_id 
                   7388: 
                   7389: sub get_timebased_id {
                   7390:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7391:         $maxtries) = @_;
                   7392:     my ($newid,$error,$dellock);
                   7393:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7394:         return ('','ok','invalid call to get suffix');
                   7395:     }
                   7396: 
                   7397: # set defaults for any optional args for which values were not supplied
                   7398:     if ($who eq '') {
                   7399:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7400:     }
                   7401:     if (!$locktries) {
                   7402:         $locktries = 3;
                   7403:     }
                   7404:     if (!$maxtries) {
                   7405:         $maxtries = 10;
                   7406:     }
                   7407:     
                   7408:     if (($cdom eq '') || ($cnum eq '')) {
                   7409:         if ($env{'request.course.id'}) {
                   7410:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7411:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7412:         }
                   7413:         if (($cdom eq '') || ($cnum eq '')) {
                   7414:             return ('','ok','call to get suffix not in course context');
                   7415:         }
                   7416:     }
                   7417: 
                   7418: # construct locking item
                   7419:     my $lockhash = {
                   7420:                       $prefix."\0".'locked_'.$keyid => $who,
                   7421:                    };
                   7422:     my $tries = 0;
                   7423: 
                   7424: # attempt to get lock on nohist_$namespace file
                   7425:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7426:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7427:         $tries ++;
                   7428:         sleep 1;
                   7429:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7430:     }
                   7431: 
                   7432: # attempt to get unique identifier, based on current timestamp
                   7433:     if ($gotlock eq 'ok') {
                   7434:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7435:         my $id = time;
                   7436:         $newid = $id;
1.1268    raeburn  7437:         if ($idtype eq 'addcode') {
                   7438:             $newid .= &sixnum_code();
                   7439:         }
1.1198    raeburn  7440:         my $idtries = 0;
                   7441:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7442:             if ($idtype eq 'concat') {
                   7443:                 $newid = $id.$idtries;
1.1268    raeburn  7444:             } elsif ($idtype eq 'addcode') {
                   7445:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7446:             } else {
                   7447:                 $newid ++;
                   7448:             }
                   7449:             $idtries ++;
                   7450:         }
                   7451:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7452:             my %new_item =  (
                   7453:                               $prefix."\0".$newid => $who,
                   7454:                             );
                   7455:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7456:                                                  $cdom,$cnum);
                   7457:             if ($putresult ne 'ok') {
                   7458:                 undef($newid);
                   7459:                 $error = 'error saving new item: '.$putresult;
                   7460:             }
                   7461:         } else {
1.1268    raeburn  7462:              undef($newid);
1.1198    raeburn  7463:              $error = ('error: no unique suffix available for the new item ');
                   7464:         }
                   7465: #  remove lock
                   7466:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7467:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7468:     } else {
                   7469:         $error = "error: could not obtain lockfile\n";
                   7470:         $dellock = 'ok';
1.1276    raeburn  7471:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7472:             $dellock = 'nolock';
                   7473:         }
1.1198    raeburn  7474:     }
                   7475:     return ($newid,$dellock,$error);
                   7476: }
                   7477: 
1.1268    raeburn  7478: sub sixnum_code {
                   7479:     my $code;
                   7480:     for (0..6) {
                   7481:         $code .= int( rand(9) );
                   7482:     }
                   7483:     return $code;
                   7484: }
                   7485: 
1.765     albertel 7486: # -------------------------------------------------- portfolio access checking
                   7487: 
                   7488: sub portfolio_access {
1.1270    raeburn  7489:     my ($requrl,$clientip) = @_;
1.765     albertel 7490:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7491:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7492:     if ($result) {
                   7493:         my %setters;
                   7494:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7495:             my ($startblock,$endblock) =
                   7496:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7497:             if ($startblock && $endblock) {
                   7498:                 return 'B';
                   7499:             }
                   7500:         } else {
                   7501:             my ($startblock,$endblock) =
                   7502:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7503:             if ($startblock && $endblock) {
                   7504:                 return 'B';
                   7505:             }
                   7506:         }
                   7507:     }
1.765     albertel 7508:     if ($result eq 'ok') {
1.766     albertel 7509:        return 'F';
1.765     albertel 7510:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7511:        return 'A';
1.765     albertel 7512:     }
1.766     albertel 7513:     return '';
1.765     albertel 7514: }
                   7515: 
                   7516: sub get_portfolio_access {
1.1270    raeburn  7517:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7518: 
                   7519:     if (!ref($access_hash)) {
                   7520: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7521: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7522: 						   $file_name);
                   7523: 	$access_hash = $access_controls{$file_name};
                   7524:     }
                   7525: 
1.1270    raeburn  7526:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7527:     my $now = time;
                   7528:     if (ref($access_hash) eq 'HASH') {
                   7529:         foreach my $key (keys(%{$access_hash})) {
                   7530:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7531:             if ($start > $now) {
                   7532:                 next;
                   7533:             }
                   7534:             if ($end && $end<$now) {
                   7535:                 next;
                   7536:             }
                   7537:             if ($scope eq 'public') {
                   7538:                 $public = $key;
                   7539:                 last;
                   7540:             } elsif ($scope eq 'guest') {
                   7541:                 $guest = $key;
                   7542:             } elsif ($scope eq 'domains') {
                   7543:                 push(@domains,$key);
                   7544:             } elsif ($scope eq 'users') {
                   7545:                 push(@users,$key);
                   7546:             } elsif ($scope eq 'course') {
                   7547:                 push(@courses,$key);
                   7548:             } elsif ($scope eq 'group') {
                   7549:                 push(@groups,$key);
1.1270    raeburn  7550:             } elsif ($scope eq 'ip') {
                   7551:                 push(@ips,$key);
1.765     albertel 7552:             }
                   7553:         }
                   7554:         if ($public) {
                   7555:             return 'ok';
1.1270    raeburn  7556:         } elsif (@ips > 0) {
                   7557:             my $allowed;
                   7558:             foreach my $ipkey (@ips) {
                   7559:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7560:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7561:                         $allowed = 1;
                   7562:                         last; 
                   7563:                     }
                   7564:                 }
                   7565:             }
                   7566:             if ($allowed) {
                   7567:                 return 'ok';
                   7568:             }
1.765     albertel 7569:         }
                   7570:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7571:             if ($guest) {
                   7572:                 return $guest;
                   7573:             }
                   7574:         } else {
                   7575:             if (@domains > 0) {
                   7576:                 foreach my $domkey (@domains) {
                   7577:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7578:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7579:                             return 'ok';
                   7580:                         }
                   7581:                     }
                   7582:                 }
                   7583:             }
                   7584:             if (@users > 0) {
                   7585:                 foreach my $userkey (@users) {
1.865     raeburn  7586:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7587:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7588:                             if (ref($item) eq 'HASH') {
                   7589:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7590:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7591:                                     return 'ok';
                   7592:                                 }
                   7593:                             }
                   7594:                         }
                   7595:                     } 
1.765     albertel 7596:                 }
                   7597:             }
                   7598:             my %roleshash;
                   7599:             my @courses_and_groups = @courses;
                   7600:             push(@courses_and_groups,@groups); 
                   7601:             if (@courses_and_groups > 0) {
                   7602:                 my (%allgroups,%allroles); 
                   7603:                 my ($start,$end,$role,$sec,$group);
                   7604:                 foreach my $envkey (%env) {
1.1060    raeburn  7605:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7606:                         my $cid = $2.'_'.$3; 
                   7607:                         if ($1 eq 'gr') {
                   7608:                             $group = $4;
                   7609:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7610:                         } else {
                   7611:                             if ($4 eq '') {
                   7612:                                 $sec = 'none';
                   7613:                             } else {
                   7614:                                 $sec = $4;
                   7615:                             }
                   7616:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7617:                         }
1.811     albertel 7618:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7619:                         my $cid = $2.'_'.$3;
                   7620:                         if ($4 eq '') {
                   7621:                             $sec = 'none';
                   7622:                         } else {
                   7623:                             $sec = $4;
                   7624:                         }
                   7625:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7626:                     }
                   7627:                 }
                   7628:                 if (keys(%allroles) == 0) {
                   7629:                     return;
                   7630:                 }
                   7631:                 foreach my $key (@courses_and_groups) {
                   7632:                     my %content = %{$$access_hash{$key}};
                   7633:                     my $cnum = $content{'number'};
                   7634:                     my $cdom = $content{'domain'};
                   7635:                     my $cid = $cdom.'_'.$cnum;
                   7636:                     if (!exists($allroles{$cid})) {
                   7637:                         next;
                   7638:                     }    
                   7639:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7640:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7641:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7642:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7643:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7644:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7645:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7646:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7647:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7648:                                         if (grep/^all$/,@sections) {
                   7649:                                             return 'ok';
                   7650:                                         } else {
                   7651:                                             if (grep/^$sec$/,@sections) {
                   7652:                                                 return 'ok';
                   7653:                                             }
                   7654:                                         }
                   7655:                                     }
                   7656:                                 }
                   7657:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7658:                                     if (grep/^none$/,@groups) {
                   7659:                                         return 'ok';
                   7660:                                     }
                   7661:                                 } else {
                   7662:                                     if (grep/^all$/,@groups) {
                   7663:                                         return 'ok';
                   7664:                                     } 
                   7665:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7666:                                         if (grep/^$group$/,@groups) {
                   7667:                                             return 'ok';
                   7668:                                         }
                   7669:                                     }
                   7670:                                 } 
                   7671:                             }
                   7672:                         }
                   7673:                     }
                   7674:                 }
                   7675:             }
                   7676:             if ($guest) {
                   7677:                 return $guest;
                   7678:             }
                   7679:         }
                   7680:     }
                   7681:     return;
                   7682: }
                   7683: 
                   7684: sub course_group_datechecker {
                   7685:     my ($dates,$now,$status) = @_;
                   7686:     my ($start,$end) = split(/\./,$dates);
                   7687:     if (!$start && !$end) {
                   7688:         return 'ok';
                   7689:     }
                   7690:     if (grep/^active$/,@{$status}) {
                   7691:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7692:             return 'ok';
                   7693:         }
                   7694:     }
                   7695:     if (grep/^previous$/,@{$status}) {
                   7696:         if ($end > $now ) {
                   7697:             return 'ok';
                   7698:         }
                   7699:     }
                   7700:     if (grep/^future$/,@{$status}) {
                   7701:         if ($start > $now) {
                   7702:             return 'ok';
                   7703:         }
                   7704:     }
                   7705:     return; 
                   7706: }
                   7707: 
                   7708: sub parse_portfolio_url {
                   7709:     my ($url) = @_;
                   7710: 
                   7711:     my ($type,$udom,$unum,$group,$file_name);
                   7712:     
1.823     albertel 7713:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7714: 	$type = 1;
                   7715:         $udom = $1;
                   7716:         $unum = $2;
                   7717:         $file_name = $3;
1.823     albertel 7718:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7719: 	$type = 2;
                   7720:         $udom = $1;
                   7721:         $unum = $2;
                   7722:         $group = $3;
                   7723:         $file_name = $3.'/'.$4;
                   7724:     }
                   7725:     if (wantarray) {
                   7726: 	return ($type,$udom,$unum,$file_name,$group);
                   7727:     }
                   7728:     return $type;
                   7729: }
                   7730: 
                   7731: sub is_portfolio_url {
                   7732:     my ($url) = @_;
                   7733:     return scalar(&parse_portfolio_url($url));
                   7734: }
                   7735: 
1.798     raeburn  7736: sub is_portfolio_file {
                   7737:     my ($file) = @_;
1.820     raeburn  7738:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7739:         return 1;
                   7740:     }
                   7741:     return;
                   7742: }
                   7743: 
1.976     raeburn  7744: sub usertools_access {
1.1084    raeburn  7745:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7746:     my ($access,%tools);
                   7747:     if ($context eq '') {
                   7748:         $context = 'tools';
                   7749:     }
                   7750:     if ($context eq 'requestcourses') {
                   7751:         %tools = (
                   7752:                       official   => 1,
                   7753:                       unofficial => 1,
1.1006    raeburn  7754:                       community  => 1,
1.1246    raeburn  7755:                       textbook   => 1,
1.1305    raeburn  7756:                       placement  => 1,
1.1368    raeburn  7757:                       lti        => 1,
1.985     raeburn  7758:                  );
1.1183    raeburn  7759:     } elsif ($context eq 'requestauthor') {
                   7760:         %tools = (
                   7761:                       requestauthor => 1,
                   7762:                  );
1.985     raeburn  7763:     } else {
                   7764:         %tools = (
                   7765:                       aboutme   => 1,
                   7766:                       blog      => 1,
1.1177    raeburn  7767:                       webdav    => 1,
1.985     raeburn  7768:                       portfolio => 1,
                   7769:                  );
                   7770:     }
1.976     raeburn  7771:     return if (!defined($tools{$tool}));
                   7772: 
1.1242    raeburn  7773:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7774:         $udom = $env{'user.domain'};
                   7775:         $uname = $env{'user.name'};
                   7776:     }
                   7777: 
1.978     raeburn  7778:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7779:         if ($action ne 'reload') {
1.985     raeburn  7780:             if ($context eq 'requestcourses') {
                   7781:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7782:             } elsif ($context eq 'requestauthor') {
                   7783:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7784:             } else {
                   7785:                 return $env{'environment.availabletools.'.$tool};
                   7786:             }
                   7787:         }
1.976     raeburn  7788:     }
                   7789: 
1.1183    raeburn  7790:     my ($toolstatus,$inststatus,$envkey);
                   7791:     if ($context eq 'requestauthor') {
                   7792:         $envkey = $context; 
                   7793:     } else {
                   7794:         $envkey = $context.'.'.$tool;
                   7795:     }
1.976     raeburn  7796: 
1.985     raeburn  7797:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7798:          ($action ne 'reload')) {
1.1183    raeburn  7799:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7800:         $inststatus = $env{'environment.inststatus'};
                   7801:     } else {
1.1084    raeburn  7802:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7803:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7804:             $inststatus = $userenvref->{'inststatus'};
                   7805:         } else {
1.1183    raeburn  7806:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7807:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7808:             $inststatus = $userenv{'inststatus'};
                   7809:         }
1.976     raeburn  7810:     }
                   7811: 
                   7812:     if ($toolstatus ne '') {
                   7813:         if ($toolstatus) {
                   7814:             $access = 1;
                   7815:         } else {
                   7816:             $access = 0;
                   7817:         }
                   7818:         return $access;
                   7819:     }
                   7820: 
1.1084    raeburn  7821:     my ($is_adv,%domdef);
                   7822:     if (ref($is_advref) eq 'HASH') {
                   7823:         $is_adv = $is_advref->{'is_adv'};
                   7824:     } else {
                   7825:         $is_adv = &is_advanced_user($udom,$uname);
                   7826:     }
                   7827:     if (ref($domdefref) eq 'HASH') {
                   7828:         %domdef = %{$domdefref};
                   7829:     } else {
                   7830:         %domdef = &get_domain_defaults($udom);
                   7831:     }
1.976     raeburn  7832:     if (ref($domdef{$tool}) eq 'HASH') {
                   7833:         if ($is_adv) {
                   7834:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7835:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7836:                     $access = 1;
                   7837:                 } else {
                   7838:                     $access = 0;
                   7839:                 }
                   7840:                 return $access;
                   7841:             }
                   7842:         }
                   7843:         if ($inststatus ne '') {
                   7844:             my ($hasaccess,$hasnoaccess);
                   7845:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7846:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7847:                     if ($domdef{$tool}{$affiliation}) {
                   7848:                         $hasaccess = 1;
                   7849:                     } else {
                   7850:                         $hasnoaccess = 1;
                   7851:                     }
                   7852:                 }
                   7853:             }
                   7854:             if ($hasaccess || $hasnoaccess) {
                   7855:                 if ($hasaccess) {
                   7856:                     $access = 1;
                   7857:                 } elsif ($hasnoaccess) {
                   7858:                     $access = 0; 
                   7859:                 }
                   7860:                 return $access;
                   7861:             }
                   7862:         } else {
                   7863:             if ($domdef{$tool}{'default'} ne '') {
                   7864:                 if ($domdef{$tool}{'default'}) {
                   7865:                     $access = 1;
                   7866:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7867:                     $access = 0;
                   7868:                 }
                   7869:                 return $access;
                   7870:             }
                   7871:         }
                   7872:     } else {
1.1177    raeburn  7873:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7874:             $access = 1;
                   7875:         } else {
                   7876:             $access = 0;
                   7877:         }
1.976     raeburn  7878:         return $access;
                   7879:     }
                   7880: }
                   7881: 
1.1050    raeburn  7882: sub is_course_owner {
                   7883:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7884:     if (($udom eq '') || ($uname eq '')) {
                   7885:         $udom = $env{'user.domain'};
                   7886:         $uname = $env{'user.name'};
                   7887:     }
                   7888:     unless (($udom eq '') || ($uname eq '')) {
                   7889:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7890:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7891:                 return 1;
                   7892:             } else {
                   7893:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7894:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7895:                     return 1;
                   7896:                 }
                   7897:             }
                   7898:         }
                   7899:     }
                   7900:     return;
                   7901: }
                   7902: 
1.976     raeburn  7903: sub is_advanced_user {
                   7904:     my ($udom,$uname) = @_;
1.1085    raeburn  7905:     if ($udom ne '' && $uname ne '') {
                   7906:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7907:             if (wantarray) {
                   7908:                 return ($env{'user.adv'},$env{'user.author'});
                   7909:             } else {
                   7910:                 return $env{'user.adv'};
                   7911:             }
1.1085    raeburn  7912:         }
                   7913:     }
1.976     raeburn  7914:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7915:     my %allroles;
1.1128    raeburn  7916:     my ($is_adv,$is_author);
1.976     raeburn  7917:     foreach my $role (keys(%roleshash)) {
                   7918:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7919:         my $area = '/'.$tdomain.'/'.$trest;
                   7920:         if ($sec ne '') {
                   7921:             $area .= '/'.$sec;
                   7922:         }
                   7923:         if (($area ne '') && ($trole ne '')) {
                   7924:             my $spec=$trole.'.'.$area;
                   7925:             if ($trole =~ /^cr\//) {
                   7926:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7927:             } elsif ($trole ne 'gr') {
                   7928:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7929:             }
1.1128    raeburn  7930:             if ($trole eq 'au') {
                   7931:                 $is_author = 1;
                   7932:             }
1.976     raeburn  7933:         }
                   7934:     }
                   7935:     foreach my $role (keys(%allroles)) {
                   7936:         last if ($is_adv);
                   7937:         foreach my $item (split(/:/,$allroles{$role})) {
                   7938:             if ($item ne '') {
                   7939:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7940:                 if ($privilege eq 'adv') {
                   7941:                     $is_adv = 1;
                   7942:                     last;
                   7943:                 }
                   7944:             }
                   7945:         }
                   7946:     }
1.1128    raeburn  7947:     if (wantarray) {
                   7948:         return ($is_adv,$is_author);
                   7949:     }
1.976     raeburn  7950:     return $is_adv;
                   7951: }
1.798     raeburn  7952: 
1.1035    raeburn  7953: sub check_can_request {
1.1368    raeburn  7954:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7955:     my $canreq = 0;
1.1368    raeburn  7956:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7957:         $uname = $env{'user.name'};
                   7958:         $udom = $env{'user.domain'};
                   7959:     }
1.1035    raeburn  7960:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7961:     my @options = ('approval','validate','autolimit');
                   7962:     my $optregex = join('|',@options);
                   7963:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7964:         foreach my $type (@{$types}) {
1.1368    raeburn  7965:             if (&usertools_access($uname,$udom,$type,undef,
                   7966:                                   'requestcourses')) {
1.1035    raeburn  7967:                 $canreq ++;
1.1036    raeburn  7968:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7969:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7970:                 }
1.1368    raeburn  7971:                 if ($dom eq $udom) {
1.1035    raeburn  7972:                     $can_request->{$type} = 1;
                   7973:                 }
                   7974:             }
1.1368    raeburn  7975:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7976:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7977:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7978:                 if (@curr > 0) {
1.1036    raeburn  7979:                     foreach my $item (@curr) {
                   7980:                         if (ref($request_domains) eq 'HASH') {
                   7981:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7982:                             if ($otherdom ne '') {
                   7983:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7984:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7985:                                         push(@{$request_domains->{$type}},$otherdom);
                   7986:                                     }
                   7987:                                 } else {
                   7988:                                     push(@{$request_domains->{$type}},$otherdom);
                   7989:                                 }
                   7990:                             }
                   7991:                         }
                   7992:                     }
1.1368    raeburn  7993:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7994:                         $canreq ++;
1.1035    raeburn  7995:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7996:                             $can_request->{$type} = 1;
                   7997:                         }
                   7998:                     }
                   7999:                 }
                   8000:             }
                   8001:         }
                   8002:     }
                   8003:     return $canreq;
                   8004: }
                   8005: 
1.341     www      8006: # ---------------------------------------------- Custom access rule evaluation
                   8007: 
                   8008: sub customaccess {
                   8009:     my ($priv,$uri)=@_;
1.807     albertel 8010:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8011:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8012:     $udom = &LONCAPA::clean_domain($udom);
                   8013:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8014:     my $access=0;
1.800     albertel 8015:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8016: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8017: 	if ($type eq 'user') {
                   8018: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8019: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8020: 		if ($tdom) {
                   8021: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8022: 		}
1.896     albertel 8023: 		if ($tuname) {
                   8024: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8025: 		}
                   8026: 		$access=($effect eq 'allow');
                   8027: 		last;
                   8028: 	    }
                   8029: 	} else {
                   8030: 	    if ($role) {
                   8031: 		if ($role ne $urole) { next; }
                   8032: 	    }
                   8033: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8034: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8035: 		if ($tdom) {
                   8036: 		    if ($tdom ne $udom) { next; }
                   8037: 		}
                   8038: 		if ($tcrs) {
                   8039: 		    if ($tcrs ne $ucrs) { next; }
                   8040: 		}
                   8041: 		if ($tsec) {
                   8042: 		    if ($tsec ne $usec) { next; }
                   8043: 		}
                   8044: 		$access=($effect eq 'allow');
                   8045: 		last;
                   8046: 	    }
                   8047: 	    if ($realm eq '' && $role eq '') {
                   8048: 		$access=($effect eq 'allow');
                   8049: 	    }
1.402     bowersj2 8050: 	}
1.341     www      8051:     }
                   8052:     return $access;
                   8053: }
                   8054: 
1.103     harris41 8055: # ------------------------------------------------- Check for a user privilege
1.12      www      8056: 
                   8057: sub allowed {
1.1424    raeburn  8058:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 8059:     my $ver_orguri=$uri;
1.439     www      8060:     $uri=&deversion($uri);
1.152     www      8061:     my $orguri=$uri;
1.52      www      8062:     $uri=&declutter($uri);
1.809     raeburn  8063: 
1.810     raeburn  8064:     if ($priv eq 'evb') {
                   8065: # Evade communication block restrictions for specified role in a course
                   8066:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8067:             return $1;
                   8068:         } else {
                   8069:             return;
                   8070:         }
                   8071:     }
                   8072: 
1.620     albertel 8073:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8074: # Free bre access to adm and meta resources
1.1343    raeburn  8075:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 8076: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8077: 	&& ($priv eq 'bre')) {
1.14      www      8078: 	return 'F';
1.159     www      8079:     }
                   8080: 
1.545     banghart 8081: # Free bre access to user's own portfolio contents
1.714     raeburn  8082:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8083:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8084: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8085:         my %setters;
                   8086:         my ($startblock,$endblock) = 
                   8087:             &Apache::loncommon::blockcheck(\%setters,'port');
                   8088:         if ($startblock && $endblock) {
                   8089:             return 'B';
                   8090:         } else {
                   8091:             return 'F';
                   8092:         }
1.545     banghart 8093:     }
                   8094: 
1.762     raeburn  8095: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8096:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8097:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8098:         if (exists($env{'request.course.id'})) {
                   8099:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8100:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8101:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8102:                 my $courseprivid=$env{'request.course.id'};
                   8103:                 $courseprivid=~s/\_/\//;
                   8104:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8105:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8106:                     return $1; 
1.762     raeburn  8107:                 } else {
                   8108:                     if ($env{'request.course.sec'}) {
                   8109:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8110:                     }
                   8111:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8112:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8113:                         return $2;
                   8114:                     }
1.714     raeburn  8115:                 }
                   8116:             }
                   8117:         }
                   8118:     }
                   8119: 
1.159     www      8120: # Free bre to public access
                   8121: 
                   8122:     if ($priv eq 'bre') {
1.1362    raeburn  8123:         my $copyright;
                   8124:         unless ($uri =~ /ext\.tool/) {
                   8125:             $copyright=&metadata($uri,'copyright');
                   8126:         }
1.620     albertel 8127: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8128:            return 'F'; 
                   8129:         }
1.238     www      8130:         if ($copyright eq 'priv') {
                   8131:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8132: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8133: 		return '';
                   8134:             }
                   8135:         }
                   8136:         if ($copyright eq 'domain') {
                   8137:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8138: 	    unless (($env{'user.domain'} eq $1) ||
                   8139:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8140: 		return '';
                   8141:             }
1.262     matthew  8142:         }
1.620     albertel 8143:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8144:             # Library role, so allow browsing of resources in this domain.
                   8145:             return 'F';
1.238     www      8146:         }
1.341     www      8147:         if ($copyright eq 'custom') {
                   8148: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8149:         }
1.14      www      8150:     }
1.264     matthew  8151:     # Domain coordinator is trying to create a course
1.620     albertel 8152:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8153:         # uri is the requested domain in this case.
                   8154:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8155:         # a role of dc for the domain in question.
1.620     albertel 8156:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8157:     }
1.29      www      8158: 
1.52      www      8159:     my $thisallowed='';
                   8160:     my $statecond=0;
                   8161:     my $courseprivid='';
                   8162: 
1.1039    raeburn  8163:     my $ownaccess;
1.1043    raeburn  8164:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8165:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8166:         if ($uri eq '') {
                   8167:             $ownaccess = 1;
                   8168:         } else {
                   8169:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8170:                 my $udom = $env{'user.domain'};
                   8171:                 my $uname = $env{'user.name'};
                   8172:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8173:                     $ownaccess = 1;
1.1040    raeburn  8174:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8175:                     unless ($uri =~ m{\.\./}) {
                   8176:                         $ownaccess = 1;
                   8177:                     }
                   8178:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8179:                     my $now = time;
                   8180:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8181:                         my $adom = $1;
                   8182:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8183:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  8184:                                 my ($start,$end) = split('.',$env{$key});
                   8185:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8186:                                     $ownaccess = 1;
                   8187:                                     last;
                   8188:                                 }
                   8189:                             }
                   8190:                         }
                   8191:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8192:                         my $adom = $1;
                   8193:                         my $aname = $2;
1.1042    raeburn  8194:                         foreach my $role ('ca','aa') { 
                   8195:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8196:                                 my ($start,$end) =
                   8197:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   8198:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8199:                                     $ownaccess = 1;
                   8200:                                     last;
                   8201:                                 }
1.1039    raeburn  8202:                             }
                   8203:                         }
                   8204:                     }
                   8205:                 }
                   8206:             }
                   8207:         }
                   8208:     }
                   8209: 
1.52      www      8210: # Course
                   8211: 
1.620     albertel 8212:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8213:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8214:             $thisallowed.=$1;
                   8215:         }
1.52      www      8216:     }
1.29      www      8217: 
1.52      www      8218: # Domain
                   8219: 
1.620     albertel 8220:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8221:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8222:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8223:             $thisallowed.=$1;
                   8224:         }
1.12      www      8225:     }
1.52      www      8226: 
1.1141    raeburn  8227: # User who is not author or co-author might still be able to edit
                   8228: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8229:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8230:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8231:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8232:             $thisallowed.=$1;
                   8233:         }
                   8234:     }
                   8235: 
1.52      www      8236: # Course: uri itself is a course
1.66      www      8237:     my $courseuri=$uri;
                   8238:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8239:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8240: 
1.620     albertel 8241:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8242:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8243:         if ($priv eq 'mip') {
                   8244:             my $rem = $1;
                   8245:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8246:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8247:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8248:                 if ($cdom ne '') {
1.1410    raeburn  8249:                     my %passwdconf = &get_passwdconf($cdom);
                   8250:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8251:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8252:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8253:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8254:                                 unless (@inststatuses) {
                   8255:                                     @inststatuses = ('default');
                   8256:                                 }
                   8257:                                 foreach my $status (@inststatuses) {
                   8258:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8259:                                         $thisallowed.=$rem;
                   8260:                                     }
                   8261:                                 }
                   8262:                             }
                   8263:                         }
1.1409    raeburn  8264:                     }
                   8265:                 }
                   8266:             }
                   8267:         } else {
                   8268:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8269:                 $thisallowed.=$1;
                   8270:             }
1.1039    raeburn  8271:         }
1.12      www      8272:     }
1.29      www      8273: 
1.665     albertel 8274: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8275: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8276:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8277: 	$thisallowed='';
1.671     raeburn  8278:         my ($match)=&is_on_map($uri);
                   8279:         if ($match) {
                   8280:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8281:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8282:                 my $value = $1;
1.1402    raeburn  8283:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8284:                 if ($deeplinkblock) {
                   8285:                     $thisallowed='D';
                   8286:                 } elsif ($noblockcheck) {
1.1281    raeburn  8287:                     $thisallowed.=$value;
1.1162    raeburn  8288:                 } else {
1.1424    raeburn  8289:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8290:                     if (@blockers > 0) {
                   8291:                         $thisallowed = 'B';
                   8292:                     } else {
                   8293:                         $thisallowed.=$value;
                   8294:                     }
1.1162    raeburn  8295:                 }
1.671     raeburn  8296:             }
                   8297:         } else {
1.705     albertel 8298:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8299:             if ($refuri) {
                   8300:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8301:                     $thisallowed='F';
1.671     raeburn  8302:                 } else {
                   8303:                     $refuri=&declutter($refuri);
                   8304:                     my ($match) = &is_on_map($refuri);
                   8305:                     if ($match) {
1.1402    raeburn  8306:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8307:                         if ($deeplinkblock) {
                   8308:                             $thisallowed='D';
                   8309:                         } elsif ($noblockcheck) {
1.1281    raeburn  8310:                             $thisallowed='F';
1.1162    raeburn  8311:                         } else {
1.1426    raeburn  8312:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8313:                             if (@blockers > 0) {
                   8314:                                 $thisallowed = 'B';
                   8315:                             } else {
                   8316:                                 $thisallowed='F';
                   8317:                             }
1.1162    raeburn  8318:                         }
1.671     raeburn  8319:                     }
1.669     raeburn  8320:                 }
1.671     raeburn  8321:             }
                   8322:         }
1.314     www      8323:     }
1.492     albertel 8324: 
1.766     albertel 8325:     if ($priv eq 'bre'
                   8326: 	&& $thisallowed ne 'F' 
                   8327: 	&& $thisallowed ne '2'
                   8328: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8329: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8330:     }
1.1250    raeburn  8331: 
1.52      www      8332: # Full access at system, domain or course-wide level? Exit.
1.29      www      8333:     if ($thisallowed=~/F/) {
                   8334: 	return 'F';
                   8335:     }
                   8336: 
1.52      www      8337: # If this is generating or modifying users, exit with special codes
1.29      www      8338: 
1.643     www      8339:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8340: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8341: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8342: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8343: 	    unless ($auname) { return $thisallowed; }
                   8344: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8345: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8346: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8347: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8348: 	}
1.52      www      8349: 	return $thisallowed;
                   8350:     }
                   8351: #
1.103     harris41 8352: # Gathered so far: system, domain and course wide privileges
1.52      www      8353: #
                   8354: # Course: See if uri or referer is an individual resource that is part of 
                   8355: # the course
                   8356: 
1.620     albertel 8357:     if ($env{'request.course.id'}) {
1.232     www      8358: 
1.1409    raeburn  8359: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8360: 
                   8361:         if ($priv eq 'mip') {
                   8362:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8363:                 return $thisallowed;
                   8364:             } else {
                   8365:                 return '';
                   8366:             }
                   8367:         }
                   8368: 
1.620     albertel 8369:        $courseprivid=$env{'request.course.id'};
                   8370:        if ($env{'request.course.sec'}) {
                   8371:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8372:        }
                   8373:        $courseprivid=~s/\_/\//;
                   8374:        my $checkreferer=1;
1.232     www      8375:        my ($match,$cond)=&is_on_map($uri);
                   8376:        if ($match) {
                   8377:            $statecond=$cond;
1.620     albertel 8378:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8379:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8380:                my $value = $1;
                   8381:                if ($priv eq 'bre') {
1.1281    raeburn  8382:                    if ($noblockcheck) {
                   8383:                        $thisallowed.=$value;
1.1162    raeburn  8384:                    } else {
1.1424    raeburn  8385:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8386:                        if (@blockers > 0) {
                   8387:                            $thisallowed = 'B';
                   8388:                        } else {
                   8389:                            $thisallowed.=$value;
                   8390:                        }
1.1162    raeburn  8391:                    }
                   8392:                } else {
                   8393:                    $thisallowed.=$value;
                   8394:                }
1.52      www      8395:                $checkreferer=0;
                   8396:            }
1.29      www      8397:        }
1.1424    raeburn  8398: 
1.148     www      8399:        if ($checkreferer) {
1.620     albertel 8400: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8401:             unless ($refuri) {
1.800     albertel 8402:                 foreach my $key (keys(%env)) {
                   8403: 		    if ($key=~/^httpref\..*\*/) {
                   8404: 			my $pattern=$key;
1.156     www      8405:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8406:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8407:                         $pattern=~s/\//\\\//g;
1.152     www      8408:                         if ($orguri=~/$pattern/) {
1.800     albertel 8409: 			    $refuri=$env{$key};
1.148     www      8410:                         }
                   8411:                     }
1.191     harris41 8412:                 }
1.148     www      8413:             }
1.232     www      8414: 
1.148     www      8415:          if ($refuri) { 
1.152     www      8416: 	  $refuri=&declutter($refuri);
1.232     www      8417:           my ($match,$cond)=&is_on_map($refuri);
                   8418:             if ($match) {
                   8419:               my $refstatecond=$cond;
1.620     albertel 8420:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8421:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8422:                   my $value = $1;
                   8423:                   if ($priv eq 'bre') {
1.1402    raeburn  8424:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8425:                       if ($deeplinkblock) {
                   8426:                           $thisallowed = 'D';
                   8427:                       } elsif ($noblockcheck) {
1.1281    raeburn  8428:                           $thisallowed.=$value;
1.1162    raeburn  8429:                       } else {
1.1426    raeburn  8430:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8431:                           if (@blockers > 0) {
                   8432:                               $thisallowed = 'B';
                   8433:                           } else {
                   8434:                               $thisallowed.=$value;
                   8435:                           }
1.1162    raeburn  8436:                       }
                   8437:                   } else {
                   8438:                       $thisallowed.=$value;
                   8439:                   }
1.53      www      8440:                   $uri=$refuri;
                   8441:                   $statecond=$refstatecond;
1.52      www      8442:               }
                   8443:           }
1.148     www      8444:         }
1.29      www      8445:        }
1.52      www      8446:    }
1.29      www      8447: 
1.52      www      8448: #
1.103     harris41 8449: # Gathered now: all privileges that could apply, and condition number
1.52      www      8450: # 
                   8451: #
                   8452: # Full or no access?
                   8453: #
1.29      www      8454: 
1.52      www      8455:     if ($thisallowed=~/F/) {
                   8456: 	return 'F';
                   8457:     }
1.29      www      8458: 
1.52      www      8459:     unless ($thisallowed) {
                   8460:         return '';
                   8461:     }
1.29      www      8462: 
1.52      www      8463: # Restrictions exist, deal with them
                   8464: #
                   8465: #   C:according to course preferences
                   8466: #   R:according to resource settings
                   8467: #   L:unless locked
                   8468: #   X:according to user session state
                   8469: #
                   8470: 
                   8471: # Possibly locked functionality, check all courses
1.54      www      8472: # Locks might take effect only after 10 minutes cache expiration for other
                   8473: # courses, and 2 minutes for current course
1.52      www      8474: 
                   8475:     my $envkey;
                   8476:     if ($thisallowed=~/L/) {
1.1000    raeburn  8477:         foreach $envkey (keys(%env)) {
1.54      www      8478:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8479:                my $courseid=$2;
                   8480:                my $roleid=$1.'.'.$2;
1.92      www      8481:                $courseid=~s/^\///;
1.54      www      8482:                my $expiretime=600;
1.620     albertel 8483:                if ($env{'request.role'} eq $roleid) {
1.54      www      8484: 		  $expiretime=120;
                   8485:                }
                   8486: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8487:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8488:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8489: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8490:                }
1.620     albertel 8491:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8492:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8493: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8494:                        &log($env{'user.domain'},$env{'user.name'},
                   8495:                             $env{'user.home'},
1.57      www      8496:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8497:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8498:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8499: 		       return '';
                   8500:                    }
                   8501:                }
1.620     albertel 8502:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8503:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8504: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8505:                        &log($env{'user.domain'},$env{'user.name'},
                   8506:                             $env{'user.home'},
1.57      www      8507:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8508:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8509:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8510: 		       return '';
                   8511:                    }
                   8512:                }
                   8513: 	   }
1.29      www      8514:        }
1.52      www      8515:     }
1.1424    raeburn  8516: 
1.52      www      8517: #
                   8518: # Rest of the restrictions depend on selected course
                   8519: #
                   8520: 
1.620     albertel 8521:     unless ($env{'request.course.id'}) {
1.766     albertel 8522: 	if ($thisallowed eq 'A') {
                   8523: 	    return 'A';
1.814     raeburn  8524:         } elsif ($thisallowed eq 'B') {
                   8525:             return 'B';
1.766     albertel 8526: 	} else {
                   8527: 	    return '1';
                   8528: 	}
1.52      www      8529:     }
1.29      www      8530: 
1.52      www      8531: #
                   8532: # Now user is definitely in a course
                   8533: #
1.53      www      8534: 
                   8535: 
                   8536: # Course preferences
                   8537: 
                   8538:    if ($thisallowed=~/C/) {
1.620     albertel 8539:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8540:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8541:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8542: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8543: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8544: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8545: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8546: 			$env{'request.course.id'});
                   8547: 	   }
1.237     www      8548:            return '';
                   8549:        }
                   8550: 
1.620     albertel 8551:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8552: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8553: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8554: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8555: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8556: 			$env{'request.course.id'});
                   8557: 	   }
1.54      www      8558:            return '';
                   8559:        }
1.53      www      8560:    }
                   8561: 
                   8562: # Resource preferences
                   8563: 
                   8564:    if ($thisallowed=~/R/) {
1.620     albertel 8565:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8566:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8567: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8568: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8569: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8570: 	   }
                   8571: 	   return '';
1.54      www      8572:        }
1.53      www      8573:    }
1.30      www      8574: 
1.246     www      8575: # Restricted by state or randomout?
1.30      www      8576: 
1.52      www      8577:    if ($thisallowed=~/X/) {
1.620     albertel 8578:       if ($env{'acc.randomout'}) {
1.579     albertel 8579: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8580:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8581:             return ''; 
                   8582:          }
1.247     www      8583:       }
                   8584:       if (&condval($statecond)) {
1.52      www      8585: 	 return '2';
                   8586:       } else {
                   8587:          return '';
                   8588:       }
                   8589:    }
1.30      www      8590: 
1.766     albertel 8591:     if ($thisallowed eq 'A') {
                   8592: 	return 'A';
1.814     raeburn  8593:     } elsif ($thisallowed eq 'B') {
                   8594:         return 'B';
1.1402    raeburn  8595:     } elsif ($thisallowed eq 'D') {
                   8596:         return 'D';
1.766     albertel 8597:     }
1.52      www      8598:    return 'F';
1.232     www      8599: }
1.1162    raeburn  8600: 
1.1192    raeburn  8601: # ------------------------------------------- Check construction space access
                   8602: 
                   8603: sub constructaccess {
                   8604:     my ($url,$setpriv)=@_;
                   8605: 
                   8606: # We do not allow editing of previous versions of files
                   8607:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8608: 
                   8609: # Get username and domain from URL
                   8610:     my ($ownername,$ownerdomain,$ownerhome);
                   8611: 
                   8612:     ($ownerdomain,$ownername) =
1.1325    raeburn  8613:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8614: 
                   8615: # The URL does not really point to any authorspace, forget it
                   8616:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8617: 
                   8618: # Now we need to see if the user has access to the authorspace of
                   8619: # $ownername at $ownerdomain
                   8620: 
                   8621:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8622: # Real author for this?
                   8623:        $ownerhome = $env{'user.home'};
                   8624:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8625:           return ($ownername,$ownerdomain,$ownerhome);
                   8626:        }
                   8627:     } else {
                   8628: # Co-author for this?
                   8629:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8630:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8631:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8632:             return ($ownername,$ownerdomain,$ownerhome);
                   8633:         }
1.1312    raeburn  8634:         if ($env{'request.course.id'}) {
                   8635:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8636:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8637:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8638:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8639:                     return ($ownername,$ownerdomain,$ownerhome);
                   8640:                 }
                   8641:             }
                   8642:         }
1.1192    raeburn  8643:     }
                   8644: 
                   8645: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8646: # we might as well leave
                   8647:    unless ($setpriv) { return ''; }
                   8648: 
                   8649: # Backdoor access?
                   8650:     my $allowed=&allowed('eco',$ownerdomain);
                   8651: # Nope
                   8652:     unless ($allowed) { return ''; }
                   8653: # Looks like we may have access, but could be locked by the owner of the construction space
                   8654:     if ($allowed eq 'U') {
                   8655:         my %blocked=&get('environment',['domcoord.author'],
                   8656:                          $ownerdomain,$ownername);
                   8657: # Is blocked by owner
                   8658:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8659:     }
                   8660:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8661: # Grant temporary access
                   8662:         my $then=$env{'user.login.time'};
1.1209    raeburn  8663:         my $update=$env{'user.update.time'};
1.1192    raeburn  8664:         if (!$update) { $update = $then; }
                   8665:         my $refresh=$env{'user.refresh.time'};
                   8666:         if (!$refresh) { $refresh = $update; }
                   8667:         my $now = time;
                   8668:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8669:                            $now,'ca','constructaccess');
                   8670:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8671:         return($ownername,$ownerdomain,$ownerhome);
                   8672:     }
                   8673: # No business here
                   8674:     return '';
                   8675: }
                   8676: 
1.1282    raeburn  8677: # ----------------------------------------------------------- Content Blocking
                   8678: 
                   8679: {
                   8680: # Caches for faster Course Contents display where content blocking
                   8681: # is in operation (i.e., interval param set) for timed quiz.
                   8682: #
                   8683: # User for whom data are being temporarily cached.
                   8684: my $cacheduser='';
1.1424    raeburn  8685: # Course for which data are being temporarily cached.
                   8686: my $cachedcid='';
1.1282    raeburn  8687: # Cached blockers for this user (a hash of blocking items). 
                   8688: my %cachedblockers=();
                   8689: # When the data were last cached.
                   8690: my $cachedlast='';
                   8691: 
                   8692: sub load_all_blockers {
1.1427    raeburn  8693:     my ($uname,$udom)=@_;
1.1282    raeburn  8694:     if (($uname ne '') && ($udom ne '')) { 
                   8695:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  8696:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  8697:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  8698:             return;
                   8699:         }
                   8700:     }
                   8701:     $cachedlast=time;
                   8702:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  8703:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  8704:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  8705:     return;
1.1282    raeburn  8706: }
                   8707: 
1.1162    raeburn  8708: sub get_comm_blocks {
                   8709:     my ($cdom,$cnum) = @_;
                   8710:     if ($cdom eq '' || $cnum eq '') {
                   8711:         return unless ($env{'request.course.id'});
                   8712:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8713:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8714:     }
                   8715:     my %commblocks;
                   8716:     my $hashid=$cdom.'_'.$cnum;
                   8717:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8718:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8719:         %commblocks = %{$blocksref};
                   8720:     } else {
                   8721:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8722:         my $cachetime = 600;
                   8723:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8724:     }
                   8725:     return %commblocks;
                   8726: }
                   8727: 
1.1282    raeburn  8728: sub get_commblock_resources {
                   8729:     my ($blocks) = @_;
                   8730:     my %blockers = ();
                   8731:     return %blockers unless ($env{'request.course.id'});
                   8732:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8733:     my %commblocks;
                   8734:     if (ref($blocks) eq 'HASH') {
                   8735:         %commblocks = %{$blocks};
                   8736:     } else {
                   8737:         %commblocks = &get_comm_blocks();
                   8738:     }
1.1282    raeburn  8739:     return %blockers unless (keys(%commblocks) > 0); 
                   8740:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8741:     return %blockers unless (ref($navmap));
1.1162    raeburn  8742:     my $now = time;
                   8743:     foreach my $block (keys(%commblocks)) {
                   8744:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8745:             my ($start,$end) = ($1,$2);
                   8746:             if ($start <= $now && $end >= $now) {
                   8747:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8748:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8749:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8750:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8751:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8752:                             }
                   8753:                         }
                   8754:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8755:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8756:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8757:                             }
                   8758:                         }
                   8759:                     }
                   8760:                 }
                   8761:             }
                   8762:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8763:             my $item = $1;
1.1163    raeburn  8764:             my @to_test;
1.1162    raeburn  8765:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8766:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8767:                     my @interval;
                   8768:                     my $type = 'map';
                   8769:                     if ($item eq 'course') {
                   8770:                         $type = 'course';
                   8771:                         @interval=&EXT("resource.0.interval");
                   8772:                     } else {
                   8773:                         if ($item =~ /___\d+___/) {
                   8774:                             $type = 'resource';
                   8775:                             @interval=&EXT("resource.0.interval",$item);
                   8776:                             if (ref($navmap)) {                        
                   8777:                                 my $res = $navmap->getBySymb($item); 
                   8778:                                 push(@to_test,$res);
                   8779:                             }
1.1162    raeburn  8780:                         } else {
1.1282    raeburn  8781:                             my $mapsymb = &symbread($item,1);
                   8782:                             if ($mapsymb) {
                   8783:                                 if (ref($navmap)) {
                   8784:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1428    raeburn  8785:                                     if (ref($mapres)) {
                   8786:                                         my $first = $mapres->map_start();
                   8787:                                         my $finish = $mapres->map_finish();
                   8788:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
1.1429    raeburn  8789:                                         if (ref($it)) {
                   8790:                                             my $res;
                   8791:                                             while ($res = $it->next(undef,1)) {
                   8792:                                                 next unless (ref($res));
                   8793:                                                 my $symb = $res->symb();
                   8794:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8795:                                                 @interval=&EXT("resource.0.interval",$symb);
                   8796:                                                 if ($interval[1] eq 'map') {
                   8797:                                                     if ($res->answerable()) {
                   8798:                                                         push(@to_test,$res);
                   8799:                                                         last;
                   8800:                                                     }
1.1428    raeburn  8801:                                                 }
1.1162    raeburn  8802:                                             }
                   8803:                                         }
                   8804:                                     }
                   8805:                                 }
                   8806:                             }
                   8807:                         }
1.1282    raeburn  8808:                     }
1.1310    raeburn  8809:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8810:                         my $timelimit = $1; 
1.1282    raeburn  8811:                         my $first_access;
                   8812:                         if ($type eq 'resource') {
                   8813:                             $first_access=&get_first_access($interval[1],$item);
                   8814:                         } elsif ($type eq 'map') {
                   8815:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8816:                         } else {
                   8817:                             $first_access=&get_first_access($interval[1]);
                   8818:                         }
                   8819:                         if ($first_access) {
1.1292    raeburn  8820:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8821:                             if ($timesup > $now) {
                   8822:                                 my $activeblock;
                   8823:                                 foreach my $res (@to_test) {
1.1283    raeburn  8824:                                     if ($res->answerable()) {
1.1282    raeburn  8825:                                         $activeblock = 1;
                   8826:                                         last;
                   8827:                                     }
                   8828:                                 }
                   8829:                                 if ($activeblock) {
                   8830:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8831:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8832:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8833:                                          }
                   8834:                                     }
                   8835:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8836:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8837:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8838:                                         }
1.1162    raeburn  8839:                                     }
                   8840:                                 }
                   8841:                             }
                   8842:                         }
                   8843:                     }
                   8844:                 }
                   8845:             }
                   8846:         }
                   8847:     }
1.1282    raeburn  8848:     return %blockers;
1.1162    raeburn  8849: }
                   8850: 
1.1282    raeburn  8851: sub has_comm_blocking {
1.1427    raeburn  8852:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  8853:     my @blockers;
                   8854:     return unless ($env{'request.course.id'});
                   8855:     return unless ($priv eq 'bre');
                   8856:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8857:     return if ($env{'request.state'} eq 'construct');
1.1427    raeburn  8858:     my %blockinfo;
                   8859:     if (ref($blocks) eq 'HASH') {
                   8860:         %blockinfo = &get_commblock_resources($blocks);
                   8861:     } else {
                   8862:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8863:         %blockinfo = %cachedblockers;
                   8864:     }
                   8865:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  8866:     my (%possibles,@symbs);
                   8867:     if (!$symb) {
1.1427    raeburn  8868:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8869:     }
1.1282    raeburn  8870:     if ($symb) {
                   8871:         @symbs = ($symb);
                   8872:     } elsif (keys(%possibles)) { 
                   8873:         @symbs = keys(%possibles);
                   8874:     }
                   8875:     my $noblock;
                   8876:     foreach my $symb (@symbs) {
                   8877:         last if ($noblock);
                   8878:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  8879:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  8880:             if ($block =~ /^firstaccess____(.+)$/) {
                   8881:                 my $item = $1;
1.1424    raeburn  8882:                 unless ($blocked) {
                   8883:                     if (($item eq $map) || ($item eq $symb)) {
                   8884:                         $noblock = 1;
                   8885:                         last;
                   8886:                     }
1.1282    raeburn  8887:                 }
                   8888:             }
1.1427    raeburn  8889:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8890:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8891:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  8892:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8893:                             push(@blockers,$block);
                   8894:                         }
                   8895:                     }
                   8896:                 }
1.1427    raeburn  8897:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8898:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  8899:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8900:                             push(@blockers,$block);
                   8901:                         }
1.1282    raeburn  8902:                     }
                   8903:                 }
1.1162    raeburn  8904:             }
                   8905:         }
                   8906:     }
1.1424    raeburn  8907:     unless ($noblock) { 
                   8908:         return @blockers;
                   8909:     }
                   8910:     return;
1.1282    raeburn  8911: }
1.1162    raeburn  8912: }
                   8913: 
1.1402    raeburn  8914: sub deeplink_check {
                   8915:     my ($priv,$symb,$uri) = @_;
                   8916:     return unless ($env{'request.course.id'});
                   8917:     return unless ($priv eq 'bre');
                   8918:     return if ($env{'request.state'} eq 'construct');
                   8919:     return if ($env{'request.role.adv'});
                   8920:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8921:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8922:     my (%possibles,@symbs);
                   8923:     if (!$symb) {
                   8924:         $symb = &symbread($uri,1,1,1,\%possibles);
                   8925:     }
                   8926:     if ($symb) {
                   8927:         @symbs = ($symb);
                   8928:     } elsif (keys(%possibles)) {
                   8929:         @symbs = keys(%possibles);
                   8930:     }
                   8931: 
                   8932:     my ($login,$switchrole,$allow);
                   8933:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   8934:         my $key = $1;
                   8935:         my $tinyurl;
                   8936:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   8937:         if (defined($cached)) {
                   8938:              $tinyurl = $result;
                   8939:         } else {
                   8940:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   8941:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   8942:              if ($currtiny{$key} ne '') {
                   8943:                  $tinyurl = $currtiny{$key};
                   8944:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   8945:              }
                   8946:         }
                   8947:         if ($tinyurl ne '') {
                   8948:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
                   8949:             if ($cnumreq eq $cnum) {
                   8950:                 $login = $posslogin;
                   8951:             } else {
                   8952:                 $switchrole = 1;
                   8953:             }
                   8954:         }
                   8955:     }
                   8956:     foreach my $symb (@symbs) {
                   8957:         last if ($allow);
                   8958:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8959:         if ($deeplink eq '') {
                   8960:             $allow = 1;
                   8961:         } else {
                   8962:             my ($listed,$scope,$access) = split(/,/,$deeplink);
                   8963:             if ($access eq 'any') {
                   8964:                 $allow = 1;
                   8965:             } elsif ($login) {
                   8966:                 if ($access eq 'only') {
                   8967:                     if ($scope eq 'res') {
                   8968:                         if ($symb eq $login) {
                   8969:                             $allow = 1;
                   8970:                         }
                   8971:                     } elsif ($scope eq 'map') {
                   8972: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
                   8973:                     } elsif ($scope eq 'rec') {
                   8974: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
                   8975:                     }
                   8976:                 } else {
                   8977:                     my ($acctype,$item) = split(/:/,$access);
                   8978:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
                   8979:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
                   8980:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   8981:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
                   8982:                                 $allow = 1;
                   8983:                             }
                   8984:                         }
                   8985:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   8986:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   8987:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   8988:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
                   8989:                                 $allow = 1;
                   8990:                             }
                   8991:                         }
                   8992:                     }
                   8993:                 }
                   8994:             }
                   8995:         }
                   8996:     }
                   8997:     return if ($allow);
                   8998:     return 1;
                   8999: }
                   9000: 
1.1282    raeburn  9001: # -------------------------------- Deversion and split uri into path an filename   
                   9002: 
1.1133    foxr     9003: #
1.1282    raeburn  9004: #   Removes the version from a URI and
1.1133    foxr     9005: #   splits it in to its filename and path to the filename.
                   9006: #   Seems like File::Basename could have done this more clearly.
                   9007: #   Parameters:
                   9008: #      $uri   - input URI
                   9009: #   Returns:
                   9010: #     Two element list consisting of 
                   9011: #     $pathname  - the URI up to and excluding the trailing /
                   9012: #     $filename  - The part of the URI following the last /
                   9013: #  NOTE:
                   9014: #    Another realization of this is simply:
                   9015: #    use File::Basename;
                   9016: #    ...
                   9017: #    $uri = shift;
                   9018: #    $filename = basename($uri);
                   9019: #    $path     = dirname($uri);
                   9020: #    return ($filename, $path);
                   9021: #
                   9022: #     The implementation below is probably faster however.
                   9023: #
1.710     albertel 9024: sub split_uri_for_cond {
                   9025:     my $uri=&deversion(&declutter(shift));
                   9026:     my @uriparts=split(/\//,$uri);
                   9027:     my $filename=pop(@uriparts);
                   9028:     my $pathname=join('/',@uriparts);
                   9029:     return ($pathname,$filename);
                   9030: }
1.232     www      9031: # --------------------------------------------------- Is a resource on the map?
                   9032: 
                   9033: sub is_on_map {
1.710     albertel 9034:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9035:     #Trying to find the conditional for the file
1.620     albertel 9036:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9037: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9038:     if ($match) {
1.289     bowersj2 9039: 	return (1,$1);
                   9040:     } else {
1.434     www      9041: 	return (0,0);
1.289     bowersj2 9042:     }
1.12      www      9043: }
                   9044: 
1.427     www      9045: # --------------------------------------------------------- Get symb from alias
                   9046: 
                   9047: sub get_symb_from_alias {
                   9048:     my $symb=shift;
                   9049:     my ($map,$resid,$url)=&decode_symb($symb);
                   9050: # Already is a symb
                   9051:     if ($url) { return $symb; }
                   9052: # Must be an alias
                   9053:     my $aliassymb='';
                   9054:     my %bighash;
1.620     albertel 9055:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9056:                             &GDBM_READER(),0640)) {
                   9057:         my $rid=$bighash{'mapalias_'.$symb};
                   9058: 	if ($rid) {
                   9059: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9060: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9061: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9062: 	}
                   9063:         untie %bighash;
                   9064:     }
                   9065:     return $aliassymb;
                   9066: }
                   9067: 
1.12      www      9068: # ----------------------------------------------------------------- Define Role
                   9069: 
                   9070: sub definerole {
                   9071:   if (allowed('mcr','/')) {
1.1326    raeburn  9072:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9073:     foreach my $role (split(':',$sysrole)) {
                   9074: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9075:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9076:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9077: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9078:                return "refused:s:$crole&$cqual"; 
                   9079:             }
                   9080:         }
1.191     harris41 9081:     }
1.800     albertel 9082:     foreach my $role (split(':',$domrole)) {
                   9083: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9084:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9085:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9086: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9087:                return "refused:d:$crole&$cqual"; 
                   9088:             }
                   9089:         }
1.191     harris41 9090:     }
1.800     albertel 9091:     foreach my $role (split(':',$courole)) {
                   9092: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9093:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9094:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9095: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9096:                return "refused:c:$crole&$cqual"; 
                   9097:             }
                   9098:         }
1.191     harris41 9099:     }
1.1326    raeburn  9100:     my $uhome;
                   9101:     if (($uname ne '') && ($udom ne '')) {
                   9102:         $uhome = &homeserver($uname,$udom);
                   9103:         return $uhome if ($uhome eq 'no_host');
                   9104:     } else {
                   9105:         $uname = $env{'user.name'};
                   9106:         $udom = $env{'user.domain'};
                   9107:         $uhome = $env{'user.home'};
                   9108:     }
1.620     albertel 9109:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9110:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9111:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9112:     return reply($command,$uhome);
1.12      www      9113:   } else {
                   9114:     return 'refused';
                   9115:   }
1.105     harris41 9116: }
                   9117: 
                   9118: # ---------------- Make a metadata query against the network of library servers
                   9119: 
                   9120: sub metadata_query {
1.1237    raeburn  9121:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9122:     my %rhash;
1.845     albertel 9123:     my %libserv = &all_library();
1.244     matthew  9124:     my @server_list = (defined($server_array) ? @$server_array
                   9125:                                               : keys(%libserv) );
                   9126:     for my $server (@server_list) {
1.1237    raeburn  9127:         my $domains = ''; 
                   9128:         if (ref($domains_hash) eq 'HASH') {
                   9129:             $domains = $domains_hash->{$server}; 
                   9130:         }
1.118     harris41 9131: 	unless ($custom or $customshow) {
1.1237    raeburn  9132: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9133: 	    $rhash{$server}=$reply;
                   9134: 	}
                   9135: 	else {
                   9136: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9137: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9138: 			     $server);
                   9139: 	    $rhash{$server}=$reply;
                   9140: 	}
1.112     harris41 9141:     }
1.118     harris41 9142:     return \%rhash;
1.240     www      9143: }
                   9144: 
                   9145: # ----------------------------------------- Send log queries and wait for reply
                   9146: 
                   9147: sub log_query {
                   9148:     my ($uname,$udom,$query,%filters)=@_;
                   9149:     my $uhome=&homeserver($uname,$udom);
                   9150:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9151:     my $uhost=&hostname($uhome);
1.800     albertel 9152:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9153:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9154:                        $uhome);
1.479     albertel 9155:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9156:     return get_query_reply($queryid);
                   9157: }
                   9158: 
1.818     raeburn  9159: # -------------------------- Update MySQL table for portfolio file
                   9160: 
                   9161: sub update_portfolio_table {
1.821     raeburn  9162:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9163:     if ($group ne '') {
                   9164:         $file_name =~s /^\Q$group\E//;
                   9165:     }
1.818     raeburn  9166:     my $homeserver = &homeserver($uname,$udom);
                   9167:     my $queryid=
1.821     raeburn  9168:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9169:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9170:     my $reply = &get_query_reply($queryid);
                   9171:     return $reply;
                   9172: }
                   9173: 
1.899     raeburn  9174: # -------------------------- Update MySQL allusers table
                   9175: 
                   9176: sub update_allusers_table {
                   9177:     my ($uname,$udom,$names) = @_;
                   9178:     my $homeserver = &homeserver($uname,$udom);
                   9179:     my $queryid=
                   9180:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9181:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9182:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9183:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9184:                'generation='.&escape($names->{'generation'}).'%%'.
                   9185:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9186:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9187:     return;
1.899     raeburn  9188: }
                   9189: 
1.508     raeburn  9190: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9191: 
                   9192: sub fetch_enrollment_query {
1.511     raeburn  9193:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9194:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9195:     my $maxtries = 1;
1.508     raeburn  9196:     if ($context eq 'automated') {
                   9197:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9198:         $sleep = 2;
                   9199:         $loopmax = 100;
1.547     raeburn  9200:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9201:     } else {
                   9202:         $homeserver = &homeserver($cnum,$dom);
                   9203:     }
1.838     albertel 9204:     my $host=&hostname($homeserver);
1.506     raeburn  9205:     my $cmd = '';
1.1000    raeburn  9206:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9207:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9208:     }
                   9209:     $cmd =~ s/%%$//;
                   9210:     $cmd = &escape($cmd);
                   9211:     my $query = 'fetchenrollment';
1.620     albertel 9212:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9213:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9214:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9215:         return 'error: '.$queryid;
                   9216:     }
1.1317    raeburn  9217:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9218:     my $tries = 1;
                   9219:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9220:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9221:         $tries ++;
                   9222:     }
1.526     raeburn  9223:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9224:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9225:     } else {
1.901     albertel 9226:         my @responses = split(/:/,$reply);
1.1322    raeburn  9227:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9228:             foreach my $line (@responses) {
                   9229:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9230:                 $$replyref{$key} = $value;
                   9231:             }
                   9232:         } else {
1.1117    foxr     9233:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9234:             foreach my $line (@responses) {
                   9235:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9236:                 $$replyref{$key} = $value;
                   9237:                 if ($value > 0) {
1.800     albertel 9238:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9239:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9240:                         my $destname = $pathname.'/'.$filename;
                   9241:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9242:                         if ($xml_classlist =~ /^error/) {
                   9243:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9244:                         } else {
1.1359    raeburn  9245:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9246:                                 print FILE &unescape($xml_classlist);
                   9247:                                 close(FILE);
1.526     raeburn  9248:                             } else {
                   9249:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9250:                             }
                   9251:                         }
                   9252:                     }
                   9253:                 }
                   9254:             }
                   9255:         }
                   9256:         return 'ok';
                   9257:     }
                   9258:     return 'error';
                   9259: }
                   9260: 
1.242     www      9261: sub get_query_reply {
1.1317    raeburn  9262:     my ($queryid,$sleep,$loopmax) = @_;;
                   9263:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9264:         $sleep = 0.2;
                   9265:     }
                   9266:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9267:         $loopmax = 100;
                   9268:     }
1.1117    foxr     9269:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9270:     my $reply='';
1.1317    raeburn  9271:     for (1..$loopmax) {
                   9272: 	sleep($sleep);
1.240     www      9273:         if (-e $replyfile.'.end') {
1.1359    raeburn  9274: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9275: 		$reply = join('',<$fh>);
                   9276: 		close($fh);
1.240     www      9277: 	   } else { return 'error: reply_file_error'; }
1.242     www      9278:            return &unescape($reply);
                   9279: 	}
1.240     www      9280:     }
1.242     www      9281:     return 'timeout:'.$queryid;
1.240     www      9282: }
                   9283: 
                   9284: sub courselog_query {
1.241     www      9285: #
                   9286: # possible filters:
                   9287: # url: url or symb
                   9288: # username
                   9289: # domain
                   9290: # action: view, submit, grade
                   9291: # start: timestamp
                   9292: # end: timestamp
                   9293: #
1.240     www      9294:     my (%filters)=@_;
1.620     albertel 9295:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9296:     if ($filters{'url'}) {
                   9297: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9298:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9299:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9300:     }
1.620     albertel 9301:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9302:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9303:     return &log_query($cname,$cdom,'courselog',%filters);
                   9304: }
                   9305: 
                   9306: sub userlog_query {
1.858     raeburn  9307: #
                   9308: # possible filters:
                   9309: # action: log check role
                   9310: # start: timestamp
                   9311: # end: timestamp
                   9312: #
1.240     www      9313:     my ($uname,$udom,%filters)=@_;
                   9314:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9315: }
                   9316: 
1.506     raeburn  9317: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9318: 
                   9319: sub auto_run {
1.508     raeburn  9320:     my ($cnum,$cdom) = @_;
1.876     raeburn  9321:     my $response = 0;
                   9322:     my $settings;
                   9323:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9324:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9325:         $settings = $domconfig{'autoenroll'};
                   9326:         if ($settings->{'run'} eq '1') {
                   9327:             $response = 1;
                   9328:         }
                   9329:     } else {
1.934     raeburn  9330:         my $homeserver;
                   9331:         if (&is_course($cdom,$cnum)) {
                   9332:             $homeserver = &homeserver($cnum,$cdom);
                   9333:         } else {
                   9334:             $homeserver = &domain($cdom,'primary');
                   9335:         }
                   9336:         if ($homeserver ne 'no_host') {
                   9337:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9338:         }
1.876     raeburn  9339:     }
1.506     raeburn  9340:     return $response;
                   9341: }
1.776     albertel 9342: 
1.506     raeburn  9343: sub auto_get_sections {
1.508     raeburn  9344:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9345:     my $homeserver;
                   9346:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9347:         $homeserver = &homeserver($cnum,$cdom);
                   9348:     }
                   9349:     if (!defined($homeserver)) { 
                   9350:         if ($cdom =~ /^$match_domain$/) {
                   9351:             $homeserver = &domain($cdom,'primary');
                   9352:         }
                   9353:     }
                   9354:     my @secs;
                   9355:     if (defined($homeserver)) {
                   9356:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9357:         unless ($response eq 'refused') {
                   9358:             @secs = split(/:/,$response);
                   9359:         }
1.506     raeburn  9360:     }
                   9361:     return @secs;
                   9362: }
1.776     albertel 9363: 
1.506     raeburn  9364: sub auto_new_course {
1.1099    raeburn  9365:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9366:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9367:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9368:     return $response;
                   9369: }
1.776     albertel 9370: 
1.506     raeburn  9371: sub auto_validate_courseID {
1.508     raeburn  9372:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9373:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9374:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9375:     return $response;
                   9376: }
1.776     albertel 9377: 
1.1007    raeburn  9378: sub auto_validate_instcode {
1.1020    raeburn  9379:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9380:     my ($homeserver,$response);
                   9381:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9382:         $homeserver = &homeserver($cnum,$cdom);
                   9383:     }
                   9384:     if (!defined($homeserver)) {
                   9385:         if ($cdom =~ /^$match_domain$/) {
                   9386:             $homeserver = &domain($cdom,'primary');
                   9387:         }
                   9388:     }
1.1065    raeburn  9389:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9390:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9391:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9392:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9393: }
                   9394: 
1.506     raeburn  9395: sub auto_create_password {
1.873     raeburn  9396:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9397:     my ($homeserver,$response);
1.506     raeburn  9398:     my $create_passwd = 0;
                   9399:     my $authchk = '';
1.873     raeburn  9400:     if ($udom =~ /^$match_domain$/) {
                   9401:         $homeserver = &domain($udom,'primary');
                   9402:     }
                   9403:     if ($homeserver eq '') {
                   9404:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9405:             $homeserver = &homeserver($cnum,$cdom);
                   9406:         }
                   9407:     }
                   9408:     if ($homeserver eq '') {
                   9409:         $authchk = 'nodomain';
1.506     raeburn  9410:     } else {
1.873     raeburn  9411:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9412:         if ($response eq 'refused') {
                   9413:             $authchk = 'refused';
                   9414:         } else {
1.901     albertel 9415:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9416:         }
1.506     raeburn  9417:     }
                   9418:     return ($authparam,$create_passwd,$authchk);
                   9419: }
                   9420: 
1.706     raeburn  9421: sub auto_photo_permission {
                   9422:     my ($cnum,$cdom,$students) = @_;
                   9423:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9424:     my ($outcome,$perm_reqd,$conditions) = 
                   9425: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9426:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9427: 	return (undef,undef);
                   9428:     }
1.706     raeburn  9429:     return ($outcome,$perm_reqd,$conditions);
                   9430: }
                   9431: 
                   9432: sub auto_checkphotos {
                   9433:     my ($uname,$udom,$pid) = @_;
                   9434:     my $homeserver = &homeserver($uname,$udom);
                   9435:     my ($result,$resulttype);
                   9436:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9437: 				   &escape($uname).':'.&escape($pid),
                   9438: 				   $homeserver));
1.709     albertel 9439:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9440: 	return (undef,undef);
                   9441:     }
1.706     raeburn  9442:     if ($outcome) {
                   9443:         ($result,$resulttype) = split(/:/,$outcome);
                   9444:     } 
                   9445:     return ($result,$resulttype);
                   9446: }
                   9447: 
                   9448: sub auto_photochoice {
                   9449:     my ($cnum,$cdom) = @_;
                   9450:     my $homeserver = &homeserver($cnum,$cdom);
                   9451:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9452: 						       &escape($cdom),
                   9453: 						       $homeserver)));
1.709     albertel 9454:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9455: 	return (undef,undef);
                   9456:     }
1.706     raeburn  9457:     return ($update,$comment);
                   9458: }
                   9459: 
                   9460: sub auto_photoupdate {
                   9461:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9462:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9463:     my $host=&hostname($homeserver);
1.706     raeburn  9464:     my $cmd = '';
                   9465:     my $maxtries = 1;
1.800     albertel 9466:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9467:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9468:     }
                   9469:     $cmd =~ s/%%$//;
                   9470:     $cmd = &escape($cmd);
                   9471:     my $query = 'institutionalphotos';
                   9472:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9473:     unless ($queryid=~/^\Q$host\E\_/) {
                   9474:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9475:         return 'error: '.$queryid;
                   9476:     }
                   9477:     my $reply = &get_query_reply($queryid);
                   9478:     my $tries = 1;
                   9479:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9480:         $reply = &get_query_reply($queryid);
                   9481:         $tries ++;
                   9482:     }
                   9483:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9484:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9485:     } else {
                   9486:         my @responses = split(/:/,$reply);
                   9487:         my $outcome = shift(@responses); 
                   9488:         foreach my $item (@responses) {
                   9489:             my ($key,$value) = split(/=/,$item);
                   9490:             $$photo{$key} = $value;
                   9491:         }
                   9492:         return $outcome;
                   9493:     }
                   9494:     return 'error';
                   9495: }
                   9496: 
1.521     raeburn  9497: sub auto_instcode_format {
1.793     albertel 9498:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9499: 	$cat_order) = @_;
1.521     raeburn  9500:     my $courses = '';
1.772     raeburn  9501:     my @homeservers;
1.521     raeburn  9502:     if ($caller eq 'global') {
1.841     albertel 9503: 	my %servers = &get_servers($codedom,'library');
                   9504: 	foreach my $tryserver (keys(%servers)) {
                   9505: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9506: 		push(@homeservers,$tryserver);
                   9507: 	    }
1.584     raeburn  9508:         }
1.1022    raeburn  9509:     } elsif ($caller eq 'requests') {
                   9510:         if ($codedom =~ /^$match_domain$/) {
                   9511:             my $chome = &domain($codedom,'primary');
                   9512:             unless ($chome eq 'no_host') {
                   9513:                 push(@homeservers,$chome);
                   9514:             }
                   9515:         }
1.521     raeburn  9516:     } else {
1.772     raeburn  9517:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9518:     }
1.793     albertel 9519:     foreach my $code (keys(%{$instcodes})) {
                   9520:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9521:     }
                   9522:     chop($courses);
1.772     raeburn  9523:     my $ok_response = 0;
                   9524:     my $response;
                   9525:     while (@homeservers > 0 && $ok_response == 0) {
                   9526:         my $server = shift(@homeservers); 
                   9527:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9528:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9529:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9530: 		split(/:/,$response);
1.772     raeburn  9531:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9532:             push(@{$codetitles},&str2array($codetitles_str));
                   9533:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9534:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9535:             $ok_response = 1;
                   9536:         }
                   9537:     }
                   9538:     if ($ok_response) {
1.521     raeburn  9539:         return 'ok';
1.772     raeburn  9540:     } else {
                   9541:         return $response;
1.521     raeburn  9542:     }
                   9543: }
                   9544: 
1.792     raeburn  9545: sub auto_instcode_defaults {
                   9546:     my ($domain,$returnhash,$code_order) = @_;
                   9547:     my @homeservers;
1.841     albertel 9548: 
                   9549:     my %servers = &get_servers($domain,'library');
                   9550:     foreach my $tryserver (keys(%servers)) {
                   9551: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9552: 	    push(@homeservers,$tryserver);
                   9553: 	}
1.792     raeburn  9554:     }
1.841     albertel 9555: 
1.792     raeburn  9556:     my $response;
1.841     albertel 9557:     foreach my $server (@homeservers) {
1.792     raeburn  9558:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9559:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9560: 	
                   9561: 	foreach my $pair (split(/\&/,$response)) {
                   9562: 	    my ($name,$value)=split(/\=/,$pair);
                   9563: 	    if ($name eq 'code_order') {
                   9564: 		@{$code_order} = split(/\&/,&unescape($value));
                   9565: 	    } else {
                   9566: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9567: 	    }
                   9568: 	}
                   9569: 	return 'ok';
1.792     raeburn  9570:     }
1.841     albertel 9571: 
                   9572:     return $response;
1.1003    raeburn  9573: }
                   9574: 
                   9575: sub auto_possible_instcodes {
1.1007    raeburn  9576:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9577:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9578:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9579:         return;
                   9580:     }
1.1003    raeburn  9581:     my (@homeservers,$uhome);
                   9582:     if (defined(&domain($domain,'primary'))) {
                   9583:         $uhome=&domain($domain,'primary');
                   9584:         push(@homeservers,&domain($domain,'primary'));
                   9585:     } else {
                   9586:         my %servers = &get_servers($domain,'library');
                   9587:         foreach my $tryserver (keys(%servers)) {
                   9588:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9589:                 push(@homeservers,$tryserver);
                   9590:             }
                   9591:         }
                   9592:     }
                   9593:     my $response;
                   9594:     foreach my $server (@homeservers) {
                   9595:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9596:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9597:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9598:             split(':',$response);
                   9599:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9600:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9601:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9602:             my ($name,$value)=split('=',$item);
                   9603:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9604:         }
                   9605:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9606:             my ($name,$value)=split('=',$item);
                   9607:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9608:         }
                   9609:         return 'ok';
                   9610:     }
                   9611:     return $response;
                   9612: }
1.792     raeburn  9613: 
1.1010    raeburn  9614: sub auto_courserequest_checks {
                   9615:     my ($dom) = @_;
1.1020    raeburn  9616:     my ($homeserver,%validations);
                   9617:     if ($dom =~ /^$match_domain$/) {
                   9618:         $homeserver = &domain($dom,'primary');
                   9619:     }
                   9620:     unless ($homeserver eq 'no_host') {
                   9621:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9622:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9623:             my @items = split(/&/,$response);
                   9624:             foreach my $item (@items) {
                   9625:                 my ($key,$value) = split('=',$item);
                   9626:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9627:             }
                   9628:         }
                   9629:     }
1.1010    raeburn  9630:     return %validations; 
                   9631: }
                   9632: 
1.1020    raeburn  9633: sub auto_courserequest_validation {
1.1255    raeburn  9634:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9635:     my ($homeserver,$response);
                   9636:     if ($dom =~ /^$match_domain$/) {
                   9637:         $homeserver = &domain($dom,'primary');
                   9638:     }
1.1255    raeburn  9639:     unless ($homeserver eq 'no_host') {
                   9640:         my $customdata;
                   9641:         if (ref($custominfo) eq 'HASH') {
                   9642:             $customdata = &freeze_escape($custominfo);
                   9643:         }
1.1020    raeburn  9644:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9645:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9646:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9647:                                     $customdata,$homeserver));
1.1020    raeburn  9648:     }
                   9649:     return $response;
                   9650: }
                   9651: 
1.777     albertel 9652: sub auto_validate_class_sec {
1.918     raeburn  9653:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9654:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9655:     my $ownerlist;
                   9656:     if (ref($owners) eq 'ARRAY') {
                   9657:         $ownerlist = join(',',@{$owners});
                   9658:     } else {
                   9659:         $ownerlist = $owners;
                   9660:     }
1.773     raeburn  9661:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9662:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9663:     return $response;
                   9664: }
                   9665: 
1.1367    raeburn  9666: sub auto_validate_instclasses {
                   9667:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9668:     my ($homeserver,%validations);
                   9669:     $homeserver = &homeserver($cnum,$cdom);
                   9670:     unless ($homeserver eq 'no_host') {
                   9671:         my $ownerlist;
                   9672:         if (ref($owners) eq 'ARRAY') {
                   9673:             $ownerlist = join(',',@{$owners});
                   9674:         } else {
                   9675:             $ownerlist = $owners;
                   9676:         }
                   9677:         if (ref($classesref) eq 'HASH') {
                   9678:             my $classes = &freeze_escape($classesref);
                   9679:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9680:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9681:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9682:                 my @items = split(/&/,$response);
                   9683:                 foreach my $item (@items) {
                   9684:                     my ($key,$value) = split('=',$item);
                   9685:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9686:                 }
                   9687:             }
                   9688:         }
                   9689:     }
                   9690:     return %validations;
                   9691: }
                   9692: 
1.1248    raeburn  9693: sub auto_crsreq_update {
                   9694:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9695:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9696:     my ($homeserver,%crsreqresponse);
                   9697:     if ($cdom =~ /^$match_domain$/) {
                   9698:         $homeserver = &domain($cdom,'primary');
                   9699:     }
                   9700:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9701:         my $info;
                   9702:         if (ref($inbound) eq 'HASH') {
                   9703:             $info = &freeze_escape($inbound);
                   9704:         }
                   9705:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9706:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9707:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9708:                             &escape($title).':'.&escape($code).':'.
                   9709:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9710:                             $homeserver);
1.1248    raeburn  9711:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9712:             my @items = split(/&/,$response);
                   9713:             foreach my $item (@items) {
                   9714:                 my ($key,$value) = split('=',$item);
                   9715:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9716:             }
                   9717:         }
                   9718:     }
                   9719:     return \%crsreqresponse;
                   9720: }
                   9721: 
1.1305    raeburn  9722: sub auto_export_grades {
1.1309    raeburn  9723:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9724:     my ($homeserver,%exportresponse);
                   9725:     if ($cdom =~ /^$match_domain$/) {
                   9726:         $homeserver = &domain($cdom,'primary');
                   9727:     }
                   9728:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9729:         my $info;
                   9730:         if (ref($inforef) eq 'HASH') {
                   9731:             $info = &freeze_escape($inforef);
                   9732:         }
                   9733:         if (ref($gradesref) eq 'HASH') {
                   9734:             my $grades = &freeze_escape($gradesref);
                   9735:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9736:                                 $info.':'.$grades,$homeserver);
                   9737:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9738:                 my @items = split(/&/,$response);
                   9739:                 foreach my $item (@items) {
                   9740:                     my ($key,$value) = split('=',$item);
                   9741:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9742:                 }
                   9743:             }
                   9744:         }
                   9745:     }
                   9746:     return \%exportresponse;
1.1305    raeburn  9747: }
                   9748: 
1.1287    raeburn  9749: sub check_instcode_cloning {
                   9750:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9751:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9752:         return;
                   9753:     }
                   9754:     my $canclone;
                   9755:     if (@{$code_order} > 0) {
                   9756:         my $instcoderegexp ='^';
                   9757:         my @clonecodes = split(/\&/,$cloner);
                   9758:         foreach my $item (@{$code_order}) {
                   9759:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9760:                 foreach my $pair (@clonecodes) {
                   9761:                     my ($key,$val) = split(/\=/,$pair,2);
                   9762:                     $val = &unescape($val);
                   9763:                     if ($key eq $item) {
                   9764:                         $instcoderegexp .= '('.$val.')';
                   9765:                         last;
                   9766:                     }
                   9767:                 }
                   9768:             } else {
                   9769:                 $instcoderegexp .= $codedefaults->{$item};
                   9770:             }
                   9771:         }
                   9772:         $instcoderegexp .= '$';
                   9773:         my (@from,@to);
                   9774:         eval {
                   9775:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9776:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9777:         };
                   9778:         if ((@from > 0) && (@to > 0)) {
                   9779:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9780:             if (!@diffs) {
                   9781:                 $canclone = 1;
                   9782:             }
                   9783:         }
                   9784:     }
                   9785:     return $canclone;
                   9786: }
                   9787: 
                   9788: sub default_instcode_cloning {
                   9789:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9790:     my (%codedefaults,@code_order,$canclone);
                   9791:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9792:         %codedefaults = %{$codedefaultsref};
                   9793:         @code_order = @{$codeorderref};
                   9794:     } elsif ($clonedom) {
                   9795:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9796:     }
                   9797:     if (($domdefclone) && (@code_order)) {
                   9798:         my @clonecodes = split(/\+/,$domdefclone);
                   9799:         my $instcoderegexp ='^';
                   9800:         foreach my $item (@code_order) {
                   9801:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9802:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9803:             } else {
                   9804:                 $instcoderegexp .= $codedefaults{$item};
                   9805:             }
                   9806:         }
                   9807:         $instcoderegexp .= '$';
                   9808:         my (@from,@to);
                   9809:         eval {
                   9810:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9811:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9812:         };
                   9813:         if ((@from > 0) && (@to > 0)) {
                   9814:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9815:             if (!@diffs) {
                   9816:                 $canclone = 1;
                   9817:             }
                   9818:         }
                   9819:     }
                   9820:     return $canclone;
                   9821: }
                   9822: 
1.679     raeburn  9823: # ------------------------------------------------------- Course Group routines
                   9824: 
                   9825: sub get_coursegroups {
1.809     raeburn  9826:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9827:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9828: }
                   9829: 
1.679     raeburn  9830: sub modify_coursegroup {
                   9831:     my ($cdom,$cnum,$groupsettings) = @_;
                   9832:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9833: }
                   9834: 
1.809     raeburn  9835: sub toggle_coursegroup_status {
                   9836:     my ($cdom,$cnum,$group,$action) = @_;
                   9837:     my ($from_namespace,$to_namespace);
                   9838:     if ($action eq 'delete') {
                   9839:         $from_namespace = 'coursegroups';
                   9840:         $to_namespace = 'deleted_groups';
                   9841:     } else {
                   9842:         $from_namespace = 'deleted_groups';
                   9843:         $to_namespace = 'coursegroups';
                   9844:     }
                   9845:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9846:     if (my $tmp = &error(%curr_group)) {
                   9847:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9848:         return ('read error',$tmp);
                   9849:     } else {
                   9850:         my %savedsettings = %curr_group; 
1.809     raeburn  9851:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9852:         my $deloutcome;
                   9853:         if ($result eq 'ok') {
1.809     raeburn  9854:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9855:         } else {
                   9856:             return ('write error',$result);
                   9857:         }
                   9858:         if ($deloutcome eq 'ok') {
                   9859:             return 'ok';
                   9860:         } else {
                   9861:             return ('delete error',$deloutcome);
                   9862:         }
                   9863:     }
                   9864: }
                   9865: 
1.679     raeburn  9866: sub modify_group_roles {
1.957     raeburn  9867:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9868:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9869:     my $role = 'gr/'.&escape($userprivs);
                   9870:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9871:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9872:     if ($result eq 'ok') {
                   9873:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9874:     }
1.679     raeburn  9875:     return $result;
                   9876: }
                   9877: 
                   9878: sub modify_coursegroup_membership {
                   9879:     my ($cdom,$cnum,$membership) = @_;
                   9880:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9881:     return $result;
                   9882: }
                   9883: 
1.682     raeburn  9884: sub get_active_groups {
                   9885:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9886:     my $now = time;
                   9887:     my %groups = ();
                   9888:     foreach my $key (keys(%env)) {
1.811     albertel 9889:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9890:             my ($start,$end) = split(/\./,$env{$key});
                   9891:             if (($end!=0) && ($end<$now)) { next; }
                   9892:             if (($start!=0) && ($start>$now)) { next; }
                   9893:             if ($1 eq $cdom && $2 eq $cnum) {
                   9894:                 $groups{$3} = $env{$key} ;
                   9895:             }
                   9896:         }
                   9897:     }
                   9898:     return %groups;
                   9899: }
                   9900: 
1.683     raeburn  9901: sub get_group_membership {
                   9902:     my ($cdom,$cnum,$group) = @_;
                   9903:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9904: }
                   9905: 
                   9906: sub get_users_groups {
                   9907:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9908:     my @usersgroups;
1.683     raeburn  9909:     my $cachetime=1800;
                   9910: 
                   9911:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9912:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9913:     if (defined($cached)) {
1.734     albertel 9914:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9915:     } else {  
                   9916:         $grouplist = '';
1.816     raeburn  9917:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9918:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9919:         my $access_end = $env{'course.'.$courseid.
                   9920:                               '.default_enrollment_end_date'};
                   9921:         my $now = time;
                   9922:         foreach my $key (keys(%roleshash)) {
                   9923:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9924:                 my $group = $1;
                   9925:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9926:                     my $start = $2;
                   9927:                     my $end = $1;
                   9928:                     if ($start == -1) { next; } # deleted from group
                   9929:                     if (($start!=0) && ($start>$now)) { next; }
                   9930:                     if (($end!=0) && ($end<$now)) {
                   9931:                         if ($access_end && $access_end < $now) {
                   9932:                             if ($access_end - $end < 86400) {
                   9933:                                 push(@usersgroups,$group);
1.733     raeburn  9934:                             }
                   9935:                         }
1.817     raeburn  9936:                         next;
1.733     raeburn  9937:                     }
1.817     raeburn  9938:                     push(@usersgroups,$group);
1.683     raeburn  9939:                 }
                   9940:             }
                   9941:         }
1.817     raeburn  9942:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9943:         $grouplist = join(':',@usersgroups);
                   9944:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9945:     }
1.733     raeburn  9946:     return @usersgroups;
1.683     raeburn  9947: }
                   9948: 
                   9949: sub devalidate_getgroups_cache {
                   9950:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9951:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9952: 
1.683     raeburn  9953:     my $hashid="$udom:$uname:$courseid";
                   9954:     &devalidate_cache_new('getgroups',$hashid);
                   9955: }
                   9956: 
1.12      www      9957: # ------------------------------------------------------------------ Plain Text
                   9958: 
                   9959: sub plaintext {
1.988     raeburn  9960:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9961:     if ($short =~ m{^cr/}) {
1.758     albertel 9962: 	return (split('/',$short))[-1];
                   9963:     }
1.742     raeburn  9964:     if (!defined($cid)) {
                   9965:         $cid = $env{'request.course.id'};
                   9966:     }
                   9967:     my %rolenames = (
1.1008    raeburn  9968:                       Course    => 'std',
                   9969:                       Community => 'alt1',
1.1305    raeburn  9970:                       Placement => 'std',
1.742     raeburn  9971:                     );
1.1037    raeburn  9972:     if ($cid ne '') {
                   9973:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9974:             unless ($forcedefault) {
                   9975:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9976:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9977:                 return &Apache::lonlocal::mt($roletext);
                   9978:             }
                   9979:         }
                   9980:     }
                   9981:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9982:         (defined($rolenames{$type})) && 
                   9983:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9984:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9985:     } elsif ($cid ne '') {
                   9986:         my $crstype = $env{'course.'.$cid.'.type'};
                   9987:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9988:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9989:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9990:         }
1.742     raeburn  9991:     }
1.1037    raeburn  9992:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9993: }
                   9994: 
                   9995: # ----------------------------------------------------------------- Assign Role
                   9996: 
                   9997: sub assignrole {
1.957     raeburn  9998:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9999:         $context)=@_;
1.21      www      10000:     my $mrole;
                   10001:     if ($role =~ /^cr\//) {
1.393     www      10002:         my $cwosec=$url;
1.811     albertel 10003:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10004: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10005:            my $refused = 1;
                   10006:            if ($context eq 'requestcourses') {
                   10007:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10008:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10009:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10010:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10011:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10012:                            if ($crsenv{'internal.courseowner'} eq
                   10013:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10014:                                $refused = '';
                   10015:                            }
                   10016:                        }
                   10017:                    }
                   10018:                }
                   10019:            }
                   10020:            if ($refused) {
                   10021:                &logthis('Refused custom assignrole: '.
                   10022:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10023:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10024:                return 'refused';
                   10025:            }
1.104     www      10026:         }
1.21      www      10027:         $mrole='cr';
1.678     raeburn  10028:     } elsif ($role =~ /^gr\//) {
                   10029:         my $cwogrp=$url;
1.811     albertel 10030:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10031:         unless (&allowed('mdg',$cwogrp)) {
                   10032:             &logthis('Refused group assignrole: '.
                   10033:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10034:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10035:             return 'refused';
                   10036:         }
                   10037:         $mrole='gr';
1.21      www      10038:     } else {
1.82      www      10039:         my $cwosec=$url;
1.811     albertel 10040:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10041:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10042:             my $refused;
                   10043:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10044:                 if (!(&allowed('c'.$role,$url))) {
                   10045:                     $refused = 1;
                   10046:                 }
                   10047:             } else {
                   10048:                 $refused = 1;
                   10049:             }
1.947     raeburn  10050:             if ($refused) {
1.1045    raeburn  10051:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  10052:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10053:                     my %crsenv;
                   10054:                     if ($role eq 'cc' || $role eq 'co') {
                   10055:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10056:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10057:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10058:                                 if ($crsenv{'internal.courseowner'} eq 
                   10059:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10060:                                     $refused = '';
                   10061:                                 }
                   10062:                             }
                   10063:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10064:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10065:                                 if ($crsenv{'internal.courseowner'} eq 
                   10066:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10067:                                     $refused = '';
                   10068:                                 }
                   10069:                             }
                   10070:                         }
                   10071:                     }
1.1368    raeburn  10072:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10073:                     if ($role eq 'st') {
                   10074:                         $refused = '';
1.1377    raeburn  10075:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10076:                         $refused = '';
                   10077:                     }
1.1017    raeburn  10078:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10079:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10080:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10081:                         my $wrongcc;
                   10082:                         if ($cnum =~ /^$match_community$/) {
                   10083:                             $wrongcc = 1 if ($role eq 'cc');
                   10084:                         } else {
                   10085:                             $wrongcc = 1 if ($role eq 'co');
                   10086:                         }
                   10087:                         unless ($wrongcc) {
                   10088:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10089:                             if ($crsenv{'internal.courseowner'} eq 
                   10090:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10091:                                 $refused = '';
                   10092:                             }
1.1017    raeburn  10093:                         }
                   10094:                     }
1.1183    raeburn  10095:                 } elsif ($context eq 'requestauthor') {
                   10096:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10097:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10098:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10099:                             $refused = '';
                   10100:                         } else {
                   10101:                             my %domdefaults = &get_domain_defaults($udom);
                   10102:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10103:                                 my $checkbystatus;
                   10104:                                 if ($env{'user.adv'}) { 
                   10105:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10106:                                     if ($disposition eq 'automatic') {
                   10107:                                         $refused = '';
                   10108:                                     } elsif ($disposition eq '') {
                   10109:                                         $checkbystatus = 1;
                   10110:                                     } 
                   10111:                                 } else {
                   10112:                                     $checkbystatus = 1;
                   10113:                                 }
                   10114:                                 if ($checkbystatus) {
                   10115:                                     if ($env{'environment.inststatus'}) {
                   10116:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10117:                                         foreach my $type (@inststatuses) {
                   10118:                                             if (($type ne '') &&
                   10119:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10120:                                                 $refused = '';
                   10121:                                             }
                   10122:                                         }
                   10123:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10124:                                         $refused = '';
                   10125:                                     }
                   10126:                                 }
                   10127:                             }
                   10128:                         }
                   10129:                     }
1.1017    raeburn  10130:                 }
                   10131:                 if ($refused) {
1.947     raeburn  10132:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10133:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10134: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10135:                     return 'refused';
                   10136:                 }
1.932     raeburn  10137:             }
1.1131    raeburn  10138:         } elsif ($role eq 'au') {
                   10139:             if ($url ne '/'.$udom.'/') {
                   10140:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10141:                          ' to assign author role for '.$uname.':'.$udom.
                   10142:                          ' in domain: '.$url.' refused (wrong domain).');
                   10143:                 return 'refused';
                   10144:             }
1.104     www      10145:         }
1.21      www      10146:         $mrole=$role;
                   10147:     }
1.620     albertel 10148:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10149:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10150:     if ($end) { $command.='_'.$end; }
1.21      www      10151:     if ($start) {
                   10152: 	if ($end) { 
1.81      www      10153:            $command.='_'.$start; 
1.21      www      10154:         } else {
1.81      www      10155:            $command.='_0_'.$start;
1.21      www      10156:         }
                   10157:     }
1.739     raeburn  10158:     my $origstart = $start;
                   10159:     my $origend = $end;
1.957     raeburn  10160:     my $delflag;
1.357     www      10161: # actually delete
                   10162:     if ($deleteflag) {
1.373     www      10163: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10164: # modify command to delete the role
1.620     albertel 10165:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10166:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10167: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10168: # set start and finish to negative values for userrolelog
                   10169:            $start=-1;
                   10170:            $end=-1;
1.957     raeburn  10171:            $delflag = 1;
1.357     www      10172:         }
                   10173:     }
                   10174: # send command
1.349     www      10175:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10176: # log new user role if status is ok
1.349     www      10177:     if ($answer eq 'ok') {
1.663     raeburn  10178: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10179:         if (($role eq 'cc') || ($role eq 'in') ||
                   10180:             ($role eq 'ep') || ($role eq 'ad') ||
                   10181:             ($role eq 'ta') || ($role eq 'st') ||
                   10182:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10183:             ($role eq 'co')) {
1.1200    raeburn  10184: # for course roles, perform group memberships changes triggered by role change.
                   10185:             unless ($role =~ /^gr/) {
                   10186:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10187:                                                  $origstart,$selfenroll,$context);
                   10188:             }
1.1184    raeburn  10189:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10190:                            $selfenroll,$context);
                   10191:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10192:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10193:                  ($role eq 'da')) {
1.1184    raeburn  10194:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10195:                            $context);
                   10196:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10197:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10198:                              $context); 
                   10199:         }
1.1053    raeburn  10200:         if ($role eq 'cc') {
                   10201:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10202:         }
1.349     www      10203:     }
                   10204:     return $answer;
1.169     harris41 10205: }
                   10206: 
1.1053    raeburn  10207: sub autoupdate_coowners {
                   10208:     my ($url,$end,$start,$uname,$udom) = @_;
                   10209:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10210:     if (($cdom ne '') && ($cnum ne '')) {
                   10211:         my $now = time;
                   10212:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10213:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10214:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10215:             my $instcode = $coursehash{'internal.coursecode'};
                   10216:             if ($instcode ne '') {
1.1056    raeburn  10217:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10218:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10219:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10220:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   10221:                         if ($result eq 'valid') {
                   10222:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10223:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10224:                                     push(@newcoowners,$coowner);
                   10225:                                 }
                   10226:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10227:                                     push(@newcoowners,$uname.':'.$udom);
                   10228:                                 }
                   10229:                                 @newcoowners = sort(@newcoowners);
                   10230:                             } else {
                   10231:                                 push(@newcoowners,$uname.':'.$udom);
                   10232:                             }
                   10233:                         } else {
                   10234:                             if ($coursehash{'internal.co-owners'}) {
                   10235:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10236:                                     unless ($coowner eq $uname.':'.$udom) {
                   10237:                                         push(@newcoowners,$coowner);
                   10238:                                     }
                   10239:                                 }
                   10240:                                 unless (@newcoowners > 0) {
                   10241:                                     $delcoowners = 1;
                   10242:                                     $coowners = '';
                   10243:                                 }
                   10244:                             }
                   10245:                         }
                   10246:                         if (@newcoowners || $delcoowners) {
                   10247:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10248:                                             $delcoowners,@newcoowners);
                   10249:                         }
                   10250:                     }
                   10251:                 }
                   10252:             }
                   10253:         }
                   10254:     }
                   10255: }
                   10256: 
                   10257: sub store_coowners {
                   10258:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10259:     my $cid = $cdom.'_'.$cnum;
                   10260:     my ($coowners,$delresult,$putresult);
                   10261:     if (@newcoowners) {
                   10262:         $coowners = join(',',@newcoowners);
                   10263:         my %coownershash = (
                   10264:                             'internal.co-owners' => $coowners,
                   10265:                            );
                   10266:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10267:         if ($putresult eq 'ok') {
                   10268:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10269:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10270:             }
                   10271:         }
                   10272:     }
                   10273:     if ($delcoowners) {
                   10274:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10275:         if ($delresult eq 'ok') {
                   10276:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10277:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10278:             }
                   10279:         }
                   10280:     }
                   10281:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10282:         my %crsinfo =
                   10283:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10284:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10285:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10286:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10287:         }
                   10288:     }
                   10289: }
                   10290: 
1.169     harris41 10291: # -------------------------------------------------- Modify user authentication
1.197     www      10292: # Overrides without validation
                   10293: 
1.169     harris41 10294: sub modifyuserauth {
                   10295:     my ($udom,$uname,$umode,$upass)=@_;
                   10296:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  10297:     my $allowed;
                   10298:     if (&allowed('mau',$udom)) {
                   10299:         $allowed = 1;
                   10300:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10301:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10302:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10303:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10304:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10305:         if (($cdom ne '') && ($cnum ne '')) {
                   10306:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10307:             if ($is_owner) {
                   10308:                 $allowed = 1;
                   10309:             }
                   10310:         }
                   10311:     }
                   10312:     unless ($allowed) { return 'refused'; }
1.197     www      10313:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10314:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10315:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10316:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10317: 		     &escape($upass),$uhome);
1.620     albertel 10318:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10319:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   10320:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   10321:     &log($udom,,$uname,$uhome,
1.620     albertel 10322:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10323:                                      $env{'user.name'}.', '.$umode.
1.197     www      10324:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 10325:     unless ($reply eq 'ok') {
1.197     www      10326:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10327: 	return 'error: '.$reply;
                   10328:     }   
1.170     harris41 10329:     return 'ok';
1.80      www      10330: }
                   10331: 
1.81      www      10332: # --------------------------------------------------------------- Modify a user
1.80      www      10333: 
1.81      www      10334: sub modifyuser {
1.206     matthew  10335:     my ($udom,    $uname, $uid,
                   10336:         $umode,   $upass, $first,
                   10337:         $middle,  $last,  $gene,
1.1058    raeburn  10338:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10339:     $udom= &LONCAPA::clean_domain($udom);
                   10340:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10341:     my $showcandelete = 'none';
                   10342:     if (ref($candelete) eq 'ARRAY') {
                   10343:         if (@{$candelete} > 0) {
                   10344:             $showcandelete = join(', ',@{$candelete});
                   10345:         }
                   10346:     }
1.81      www      10347:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10348:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10349: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10350:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10351:                                      ' desiredhome not specified'). 
1.620     albertel 10352:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10353:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10354:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10355:     my $newuser;
                   10356:     if ($uhome eq 'no_host') {
                   10357:         $newuser = 1;
1.1368    raeburn  10358:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10359:                 ($umode eq 'lti')) {
                   10360:             return 'error: more information needed to create new user';
                   10361:         }
1.1075    raeburn  10362:     }
1.80      www      10363: # ----------------------------------------------------------------- Create User
1.406     albertel 10364:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10365: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10366:         my $unhome='';
1.844     albertel 10367:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10368:             $unhome = $desiredhome;
1.620     albertel 10369: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10370: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10371:         } else { # load balancing routine for determining $unhome
1.81      www      10372:             my $loadm=10000000;
1.841     albertel 10373: 	    my %servers = &get_servers($udom,'library');
                   10374: 	    foreach my $tryserver (keys(%servers)) {
                   10375: 		my $answer=reply('load',$tryserver);
                   10376: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10377: 		    $loadm=$answer;
                   10378: 		    $unhome=$tryserver;
                   10379: 		}
1.80      www      10380: 	    }
                   10381:         }
                   10382:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10383: 	    return 'error: unable to find a home server for '.$uname.
                   10384:                    ' in domain '.$udom;
1.80      www      10385:         }
                   10386:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10387:                          &escape($upass),$unhome);
                   10388: 	unless ($reply eq 'ok') {
                   10389:             return 'error: '.$reply;
                   10390:         }   
1.230     stredwic 10391:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10392:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10393: 	    return 'error: unable verify users home machine.';
1.80      www      10394:         }
1.209     matthew  10395:     }   # End of creation of new user
1.80      www      10396: # ---------------------------------------------------------------------- Add ID
                   10397:     if ($uid) {
                   10398:        $uid=~tr/A-Z/a-z/;
                   10399:        my %uidhash=&idrget($udom,$uname);
1.196     www      10400:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10401:          && (!$forceid)) {
1.80      www      10402: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10403: 	      return 'error: user id "'.$uid.'" does not match '.
                   10404:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10405:           }
                   10406:        } else {
1.1300    raeburn  10407: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10408:        }
                   10409:     }
                   10410: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10411:     my @tmp=&get('environment',
1.899     raeburn  10412: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10413:                     'permanentemail','inststatus'],
1.134     albertel 10414: 		   $udom,$uname);
1.1075    raeburn  10415:     my (%names,%oldnames);
1.313     matthew  10416:     if ($tmp[0] =~ m/^error:.*/) { 
                   10417:         %names=(); 
                   10418:     } else {
                   10419:         %names = @tmp;
1.1075    raeburn  10420:         %oldnames = %names;
1.313     matthew  10421:     }
1.388     www      10422: #
1.1058    raeburn  10423: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10424: # of users did not contain them), do not overwrite existing values
                   10425: # unless field is in $candelete array ref.  
                   10426: #
                   10427: 
                   10428:     my @fields = ('firstname','middlename','lastname','generation',
                   10429:                   'permanentemail','id');
                   10430:     my %newvalues;
                   10431:     if (ref($candelete) eq 'ARRAY') {
                   10432:         foreach my $field (@fields) {
                   10433:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10434:                 if ($field eq 'firstname') {
                   10435:                     $names{$field} = $first;
                   10436:                 } elsif ($field eq 'middlename') {
                   10437:                     $names{$field} = $middle;
                   10438:                 } elsif ($field eq 'lastname') {
                   10439:                     $names{$field} = $last;
                   10440:                 } elsif ($field eq 'generation') { 
                   10441:                     $names{$field} = $gene;
                   10442:                 } elsif ($field eq 'permanentemail') {
                   10443:                     $names{$field} = $email;
                   10444:                 } elsif ($field eq 'id') {
                   10445:                     $names{$field}  = $uid;
                   10446:                 }
                   10447:             }
                   10448:         }
                   10449:     }
1.388     www      10450:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10451:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10452:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10453:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10454:     if ($email) {
                   10455:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10456:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10457:     }
1.899     raeburn  10458:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10459:     if (defined($inststatus)) {
                   10460:         $names{'inststatus'} = '';
                   10461:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10462:         if (ref($usertypes) eq 'HASH') {
                   10463:             my @okstatuses; 
                   10464:             foreach my $item (split(/:/,$inststatus)) {
                   10465:                 if (defined($usertypes->{$item})) {
                   10466:                     push(@okstatuses,$item);  
                   10467:                 }
                   10468:             }
                   10469:             if (@okstatuses) {
                   10470:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10471:             }
                   10472:         }
                   10473:     }
1.1075    raeburn  10474:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10475:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10476:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10477:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10478:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10479:     } else {
                   10480:         $logmsg .= ' during self creation';
                   10481:     }
1.1075    raeburn  10482:     my $changed;
                   10483:     if ($newuser) {
                   10484:         $changed = 1;
                   10485:     } else {
                   10486:         foreach my $field (@fields) {
                   10487:             if ($names{$field} ne $oldnames{$field}) {
                   10488:                 $changed = 1;
                   10489:                 last;
                   10490:             }
                   10491:         }
                   10492:     }
                   10493:     unless ($changed) {
                   10494:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10495:         &logthis($logmsg);
                   10496:         return 'ok';
                   10497:     }
                   10498:     my $reply = &put('environment', \%names, $udom,$uname);
                   10499:     if ($reply ne 'ok') { 
                   10500:         return 'error: '.$reply;
                   10501:     }
1.1087    raeburn  10502:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10503:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10504:     }
1.1075    raeburn  10505:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10506:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10507:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10508:     &logthis($logmsg);
1.134     albertel 10509:     return 'ok';
1.80      www      10510: }
                   10511: 
1.81      www      10512: # -------------------------------------------------------------- Modify student
1.80      www      10513: 
1.81      www      10514: sub modifystudent {
                   10515:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10516:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10517:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10518:     if (!$cid) {
1.620     albertel 10519: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10520: 	    return 'not_in_class';
                   10521: 	}
1.80      www      10522:     }
                   10523: # --------------------------------------------------------------- Make the user
1.81      www      10524:     my $reply=&modifyuser
1.209     matthew  10525: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10526:          $desiredhome,$email,$inststatus);
1.80      www      10527:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10528:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10529:     # student's environment
1.297     matthew  10530:     $uid = undef if (!$forceid);
1.455     albertel 10531:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10532:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10533:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10534:     return $reply;
                   10535: }
                   10536: 
                   10537: sub modify_student_enrollment {
1.1216    raeburn  10538:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10539:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10540:     my ($cdom,$cnum,$chome);
                   10541:     if (!$cid) {
1.620     albertel 10542: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10543: 	    return 'not_in_class';
                   10544: 	}
1.620     albertel 10545: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10546: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10547:     } else {
                   10548: 	($cdom,$cnum)=split(/_/,$cid);
                   10549:     }
1.620     albertel 10550:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10551:     if (!$chome) {
1.457     raeburn  10552: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10553:     }
1.455     albertel 10554:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10555:     # Make sure the user exists
1.81      www      10556:     my $uhome=&homeserver($uname,$udom);
                   10557:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10558: 	return 'error: no such user';
                   10559:     }
1.297     matthew  10560:     # Get student data if we were not given enough information
                   10561:     if (!defined($first)  || $first  eq '' || 
                   10562:         !defined($last)   || $last   eq '' || 
                   10563:         !defined($uid)    || $uid    eq '' || 
                   10564:         !defined($middle) || $middle eq '' || 
                   10565:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10566:         # They did not supply us with enough data to enroll the student, so
                   10567:         # we need to pick up more information.
1.297     matthew  10568:         my %tmp = &get('environment',
1.294     matthew  10569:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10570:                        ,$udom,$uname);
                   10571: 
1.800     albertel 10572:         #foreach my $key (keys(%tmp)) {
                   10573:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10574:         #}
1.294     matthew  10575:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10576:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10577:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10578:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10579:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10580:     }
1.556     albertel 10581:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10582:     my $user = "$uname:$udom";
                   10583:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10584:     my $reply=cput('classlist',
1.1148    raeburn  10585: 		   {$user => 
1.1314    raeburn  10586: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10587: 		   $cdom,$cnum);
1.1148    raeburn  10588:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10589:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10590:     } else { 
1.81      www      10591: 	return 'error: '.$reply;
                   10592:     }
1.297     matthew  10593:     # Add student role to user
1.83      www      10594:     my $uurl='/'.$cid;
1.81      www      10595:     $uurl=~s/\_/\//g;
                   10596:     if ($usec) {
                   10597: 	$uurl.='/'.$usec;
                   10598:     }
1.1148    raeburn  10599:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10600:                              $selfenroll,$context);
                   10601:     if ($result ne 'ok') {
                   10602:         if ($old_entry{$user} ne '') {
                   10603:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10604:         } else {
                   10605:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10606:         }
                   10607:     }
                   10608:     return $result; 
1.21      www      10609: }
                   10610: 
1.556     albertel 10611: sub format_name {
                   10612:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10613:     my $name;
                   10614:     if ($first ne 'lastname') {
                   10615: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10616:     } else {
                   10617: 	if ($lastname=~/\S/) {
                   10618: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10619: 	    $name=~s/\s+,/,/;
                   10620: 	} else {
                   10621: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10622: 	}
                   10623:     }
                   10624:     $name=~s/^\s+//;
                   10625:     $name=~s/\s+$//;
                   10626:     $name=~s/\s+/ /g;
                   10627:     return $name;
                   10628: }
                   10629: 
1.84      www      10630: # ------------------------------------------------- Write to course preferences
                   10631: 
                   10632: sub writecoursepref {
                   10633:     my ($courseid,%prefs)=@_;
                   10634:     $courseid=~s/^\///;
                   10635:     $courseid=~s/\_/\//g;
                   10636:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10637:     my $chome=homeserver($cnum,$cdomain);
                   10638:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10639: 	return 'error: no such course';
                   10640:     }
                   10641:     my $cstring='';
1.800     albertel 10642:     foreach my $pref (keys(%prefs)) {
                   10643: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10644:     }
1.84      www      10645:     $cstring=~s/\&$//;
                   10646:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10647: }
                   10648: 
                   10649: # ---------------------------------------------------------- Make/modify course
                   10650: 
                   10651: sub createcourse {
1.741     raeburn  10652:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  10653:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10654:     $url=&declutter($url);
                   10655:     my $cid='';
1.1028    raeburn  10656:     if ($context eq 'requestcourses') {
                   10657:         my $can_create = 0;
                   10658:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10659:         if ($udom eq $ownerdom) {
1.1423    raeburn  10660:             my $reload;
                   10661:             if (($callercontext eq 'auto') &&
                   10662:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10663:                 $reload = 'reload';
                   10664:             }
                   10665:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10666:                                   $context)) {
                   10667:                 $can_create = 1;
                   10668:             }
                   10669:         } else {
                   10670:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10671:                                            $category);
                   10672:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10673:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10674:                 if (@curr > 0) {
                   10675:                     my @options = qw(approval validate autolimit);
                   10676:                     my $optregex = join('|',@options);
                   10677:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10678:                         $can_create = 1;
                   10679:                     }
                   10680:                 }
                   10681:             }
                   10682:         }
                   10683:         if ($can_create) {
                   10684:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10685:                 unless (&allowed('ccc',$udom)) {
                   10686:                     return 'refused'; 
                   10687:                 }
1.1017    raeburn  10688:             }
                   10689:         } else {
                   10690:             return 'refused';
                   10691:         }
1.1028    raeburn  10692:     } elsif (!&allowed('ccc',$udom)) {
                   10693:         return 'refused';
1.84      www      10694:     }
1.1011    raeburn  10695: # --------------------------------------------------------------- Get Unique ID
                   10696:     my $uname;
                   10697:     if ($cnum =~ /^$match_courseid$/) {
                   10698:         my $chome=&homeserver($cnum,$udom,'true');
                   10699:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10700:             $uname = $cnum;
                   10701:         } else {
1.1038    raeburn  10702:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10703:         }
                   10704:     } else {
1.1038    raeburn  10705:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10706:     }
                   10707:     return $uname if ($uname =~ /^error/);
                   10708: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10709:     if (!defined($course_server)) {
                   10710:         if (defined(&domain($udom,'primary'))) {
                   10711:             $course_server = &domain($udom,'primary');
                   10712:         } else {
                   10713:             $course_server = $env{'user.home'}; 
                   10714:         }
                   10715:     }
                   10716:     my %host_servers =
                   10717:         &Apache::lonnet::get_servers($udom,'library');
                   10718:     unless ($host_servers{$course_server}) {
                   10719:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10720:     }
1.84      www      10721: # ------------------------------------------------------------- Make the course
                   10722:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10723:                       $course_server);
1.84      www      10724:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10725:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10726:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10727: 	return 'error: no such course';
                   10728:     }
1.271     www      10729: # ----------------------------------------------------------------- Course made
1.516     raeburn  10730: # log existence
1.1029    raeburn  10731:     my $now = time;
1.918     raeburn  10732:     my $newcourse = {
                   10733:                     $udom.'_'.$uname => {
1.921     raeburn  10734:                                      description => $description,
                   10735:                                      inst_code   => $inst_code,
                   10736:                                      owner       => $course_owner,
                   10737:                                      type        => $crstype,
1.1029    raeburn  10738:                                      creator     => $env{'user.name'}.':'.
                   10739:                                                     $env{'user.domain'},
                   10740:                                      created     => $now,
                   10741:                                      context     => $context,
1.918     raeburn  10742:                                                 },
                   10743:                     };
1.921     raeburn  10744:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10745: # set toplevel url
1.271     www      10746:     my $topurl=$url;
                   10747:     unless ($nonstandard) {
                   10748: # ------------------------------------------ For standard courses, make top url
                   10749:         my $mapurl=&clutter($url);
1.278     www      10750:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10751:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10752: <map>
                   10753: <resource id="1" type="start"></resource>
                   10754: <resource id="2" src="$mapurl"></resource>
                   10755: <resource id="3" type="finish"></resource>
                   10756: <link index="1" from="1" to="2"></link>
                   10757: <link index="2" from="2" to="3"></link>
                   10758: </map>
                   10759: ENDINITMAP
                   10760:         $topurl=&declutter(
1.638     albertel 10761:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10762:                           );
                   10763:     }
                   10764: # ----------------------------------------------------------- Write preferences
1.84      www      10765:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10766:                      ('description'              => $description,
                   10767:                       'url'                      => $topurl,
                   10768:                       'internal.creator'         => $env{'user.name'}.':'.
                   10769:                                                     $env{'user.domain'},
                   10770:                       'internal.created'         => $now,
                   10771:                       'internal.creationcontext' => $context)
                   10772:                     );
1.84      www      10773:     return '/'.$udom.'/'.$uname;
                   10774: }
                   10775: 
1.1011    raeburn  10776: # ------------------------------------------------------------------- Create ID
                   10777: sub generate_coursenum {
1.1038    raeburn  10778:     my ($udom,$crstype) = @_;
1.1011    raeburn  10779:     my $domdesc = &domain($udom);
                   10780:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10781:     my $first;
                   10782:     if ($crstype eq 'Community') {
                   10783:         $first = '0';
                   10784:     } else {
                   10785:         $first = int(1+rand(9)); 
                   10786:     } 
                   10787:     my $uname=$first.
1.1011    raeburn  10788:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10789:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10790:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10791: # ----------------------------------------------- Make sure that does not exist
                   10792:     my $uhome=&homeserver($uname,$udom,'true');
                   10793:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10794:         if ($crstype eq 'Community') {
                   10795:             $first = '0';
                   10796:         } else {
                   10797:             $first = int(1+rand(9));
                   10798:         }
                   10799:         $uname=$first.
1.1011    raeburn  10800:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10801:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10802:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10803:         $uhome=&homeserver($uname,$udom,'true');
                   10804:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10805:             return 'error: unable to generate unique course-ID';
                   10806:         }
                   10807:     }
                   10808:     return $uname;
                   10809: }
                   10810: 
1.813     albertel 10811: sub is_course {
1.1167    droeschl 10812:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10813:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10814: 
1.1381    raeburn  10815:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10816:     my $uhome=&homeserver($cnum,$cdom);
                   10817:     my $iscourse;
                   10818:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10819:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10820:     } else {
                   10821:         my $hashid = $cdom.':'.$cnum;
                   10822:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10823:         unless (defined($cached)) {
                   10824:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10825:                                         $cnum,undef,undef,'.');
                   10826:             $iscourse = 0;
                   10827:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10828:                 $iscourse = 1;
                   10829:             }
                   10830:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10831:         }
                   10832:     }
                   10833:     return unless ($iscourse);
1.1167    droeschl 10834:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10835: }
                   10836: 
1.1015    raeburn  10837: sub store_userdata {
                   10838:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10839:     my $result;
1.1016    raeburn  10840:     if ($datakey ne '') {
1.1013    raeburn  10841:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10842:             if ($udom eq '' || $uname eq '') {
                   10843:                 $udom = $env{'user.domain'};
                   10844:                 $uname = $env{'user.name'};
                   10845:             }
                   10846:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10847:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10848:                 $result = 'error: no_host';
                   10849:             } else {
                   10850:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10851:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10852: 
                   10853:                 my $namevalue='';
                   10854:                 foreach my $key (keys(%{$storehash})) {
                   10855:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10856:                 }
                   10857:                 $namevalue=~s/\&$//;
1.1224    raeburn  10858:                 unless ($namespace eq 'courserequests') {
                   10859:                     $datakey = &escape($datakey);
                   10860:                 }
1.1105    raeburn  10861:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10862:                                   $namevalue,$uhome);
1.1013    raeburn  10863:             }
                   10864:         } else {
                   10865:             $result = 'error: data to store was not a hash reference'; 
                   10866:         }
                   10867:     } else {
                   10868:         $result= 'error: invalid requestkey'; 
                   10869:     }
                   10870:     return $result;
                   10871: }
                   10872: 
1.21      www      10873: # ---------------------------------------------------------- Assign Custom Role
                   10874: 
                   10875: sub assigncustomrole {
1.957     raeburn  10876:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10877:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10878:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10879: }
                   10880: 
                   10881: # ----------------------------------------------------------------- Revoke Role
                   10882: 
                   10883: sub revokerole {
1.957     raeburn  10884:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10885:     my $now=time;
1.965     raeburn  10886:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10887: }
                   10888: 
                   10889: # ---------------------------------------------------------- Revoke Custom Role
                   10890: 
                   10891: sub revokecustomrole {
1.957     raeburn  10892:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10893:     my $now=time;
1.357     www      10894:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10895:            $deleteflag,$selfenroll,$context);
1.17      www      10896: }
                   10897: 
1.533     banghart 10898: # ------------------------------------------------------------ Disk usage
1.535     albertel 10899: sub diskusage {
1.955     raeburn  10900:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10901:     $directorypath =~ s/\/$//;
                   10902:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10903:                        .&escape($getpropath).':'.&escape($uname).':'
                   10904:                        .&escape($udom),homeserver($uname,$udom));
                   10905:     if ($listing eq 'unknown_cmd') {
                   10906:         if ($getpropath) {
                   10907:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10908:         }
                   10909:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10910:     }
1.514     albertel 10911:     return $listing;
1.512     banghart 10912: }
                   10913: 
1.566     banghart 10914: sub is_locked {
1.1096    raeburn  10915:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10916:     my @check;
                   10917:     my $is_locked;
1.1093    raeburn  10918:     push (@check,$file_name);
1.613     albertel 10919:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10920: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10921:     my ($tmp)=keys(%locked);
                   10922:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10923:     
1.566     banghart 10924:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10925:         $is_locked = 'false';
                   10926:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10927:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10928:                $is_locked = 'true';
1.1096    raeburn  10929:                if (ref($which) eq 'ARRAY') {
                   10930:                    push(@{$which},$entry);
                   10931:                } else {
                   10932:                    last;
                   10933:                }
1.745     raeburn  10934:            }
                   10935:        }
1.566     banghart 10936:     } else {
                   10937:         $is_locked = 'false';
                   10938:     }
1.1093    raeburn  10939:     return $is_locked;
1.566     banghart 10940: }
                   10941: 
1.759     albertel 10942: sub declutter_portfile {
                   10943:     my ($file) = @_;
1.833     albertel 10944:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10945:     return $file;
                   10946: }
                   10947: 
1.559     banghart 10948: # ------------------------------------------------------------- Mark as Read Only
                   10949: 
                   10950: sub mark_as_readonly {
                   10951:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10952:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10953:     my ($tmp)=keys(%current_permissions);
                   10954:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10955:     foreach my $file (@{$files}) {
1.759     albertel 10956: 	$file = &declutter_portfile($file);
1.561     banghart 10957:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10958:     }
1.613     albertel 10959:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10960:     return;
                   10961: }
                   10962: 
1.572     banghart 10963: # ------------------------------------------------------------Save Selected Files
                   10964: 
                   10965: sub save_selected_files {
                   10966:     my ($user, $path, @files) = @_;
                   10967:     my $filename = $user."savedfiles";
1.573     banghart 10968:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10969:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10970:     foreach my $file (@files) {
1.620     albertel 10971:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10972:     }
                   10973:     foreach my $file (@other_files) {
1.574     banghart 10974:         print (OUT $file."\n");
1.572     banghart 10975:     }
1.574     banghart 10976:     close (OUT);
1.572     banghart 10977:     return 'ok';
                   10978: }
                   10979: 
1.574     banghart 10980: sub clear_selected_files {
                   10981:     my ($user) = @_;
                   10982:     my $filename = $user."savedfiles";
1.1359    raeburn  10983:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10984:     print (OUT undef);
                   10985:     close (OUT);
                   10986:     return ("ok");    
                   10987: }
                   10988: 
1.572     banghart 10989: sub files_in_path {
                   10990:     my ($user, $path) = @_;
                   10991:     my $filename = $user."savedfiles";
                   10992:     my %return_files;
1.1359    raeburn  10993:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10994:     while (my $line_in = <IN>) {
1.574     banghart 10995:         chomp ($line_in);
                   10996:         my @paths_and_file = split (m!/!, $line_in);
                   10997:         my $file_part = pop (@paths_and_file);
                   10998:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10999:         $path_part.='/';
                   11000:         my $path_and_file = $path_part.$file_part;
                   11001:         if ($path_part eq $path) {
                   11002:             $return_files{$file_part}= 'selected';
                   11003:         }
                   11004:     }
1.574     banghart 11005:     close (IN);
                   11006:     return (\%return_files);
1.572     banghart 11007: }
                   11008: 
                   11009: # called in portfolio select mode, to show files selected NOT in current directory
                   11010: sub files_not_in_path {
                   11011:     my ($user, $path) = @_;
                   11012:     my $filename = $user."savedfiles";
                   11013:     my @return_files;
                   11014:     my $path_part;
1.1359    raeburn  11015:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11016:     while (my $line = <IN>) {
1.572     banghart 11017:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11018:         my @paths_and_file = split(m|/|, $line);
                   11019:         my $file_part = pop(@paths_and_file);
                   11020:         chomp($file_part);
                   11021:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11022:         $path_part .= '/';
                   11023:         my $path_and_file = $path_part.$file_part;
                   11024:         if ($path_part ne $path) {
1.800     albertel 11025:             push(@return_files, ($path_and_file));
1.572     banghart 11026:         }
                   11027:     }
1.800     albertel 11028:     close(OUT);
1.574     banghart 11029:     return (@return_files);
1.572     banghart 11030: }
                   11031: 
1.1273    raeburn  11032: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11033:  
                   11034: sub portfiles_versioning {
                   11035:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11036:     my $portfolio_root = '/userfiles/portfolio';
                   11037:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11038:     foreach my $file (@{$portfiles}) {
                   11039:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11040:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11041:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11042:         my $getpropath = 1;
                   11043:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11044:                                              $stu_name,$getpropath);
                   11045:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11046:         my $new_answer = 
                   11047:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11048:         if ($new_answer ne 'problem getting file') {
                   11049:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11050:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11051:                               [$symb,$env{'request.course.id'},'graded']);
                   11052:         }
                   11053:     }
                   11054: }
                   11055: 
                   11056: sub get_next_version {
                   11057:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11058:     my $version;
                   11059:     if (ref($dir_list) eq 'ARRAY') {
                   11060:         foreach my $row (@{$dir_list}) {
                   11061:             my ($file) = split(/\&/,$row,2);
                   11062:             my ($file_name,$file_version,$file_ext) =
                   11063:                 &file_name_version_ext($file);
                   11064:             if (($file_name eq $answer_name) &&
                   11065:                 ($file_ext eq $answer_ext)) {
                   11066:                      # gets here if filename and extension match,
                   11067:                      # regardless of version
                   11068:                 if ($file_version ne '') {
                   11069:                     # a versioned file is found  so save it for later
                   11070:                     if ($file_version > $version) {
                   11071:                         $version = $file_version;
                   11072:                     }
                   11073:                 }
                   11074:             }
                   11075:         }
                   11076:     }
                   11077:     $version ++;
                   11078:     return($version);
                   11079: }
                   11080: 
                   11081: sub version_selected_portfile {
                   11082:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11083:     my ($answer_name,$answer_ver,$answer_ext) =
                   11084:         &file_name_version_ext($file_name);
                   11085:     my $new_answer;
                   11086:     $env{'form.copy'} =
                   11087:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11088:     if($env{'form.copy'} eq '-1') {
                   11089:         $new_answer = 'problem getting file';
                   11090:     } else {
                   11091:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11092:         my $copy_result = 
                   11093:             &finishuserfileupload($stu_name,$domain,'copy',
                   11094:                                   '/portfolio'.$directory.$new_answer);
                   11095:     }
                   11096:     undef($env{'form.copy'});
                   11097:     return ($new_answer);
                   11098: }
                   11099: 
                   11100: sub file_name_version_ext {
                   11101:     my ($file)=@_;
                   11102:     my @file_parts = split(/\./, $file);
                   11103:     my ($name,$version,$ext);
                   11104:     if (@file_parts > 1) {
                   11105:         $ext=pop(@file_parts);
                   11106:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11107:             $version=pop(@file_parts);
                   11108:         }
                   11109:         $name=join('.',@file_parts);
                   11110:     } else {
                   11111:         $name=join('.',@file_parts);
                   11112:     }
                   11113:     return($name,$version,$ext);
                   11114: }
                   11115: 
1.745     raeburn  11116: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11117: 
1.745     raeburn  11118: sub get_portfile_permissions {
                   11119:     my ($domain,$user) = @_;
1.613     albertel 11120:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11121:     my ($tmp)=keys(%current_permissions);
                   11122:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11123:     return \%current_permissions;
                   11124: }
                   11125: 
                   11126: #---------------------------------------------Get portfolio file access controls
                   11127: 
1.749     raeburn  11128: sub get_access_controls {
1.745     raeburn  11129:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11130:     my %access;
                   11131:     my $real_file = $file;
                   11132:     $file =~ s/\.meta$//;
1.745     raeburn  11133:     if (defined($file)) {
1.749     raeburn  11134:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11135:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11136:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11137:             }
                   11138:         }
1.745     raeburn  11139:     } else {
1.749     raeburn  11140:         foreach my $key (keys(%{$current_permissions})) {
                   11141:             if ($key =~ /\0accesscontrol$/) {
                   11142:                 if (defined($group)) {
                   11143:                     if ($key !~ m-^\Q$group\E/-) {
                   11144:                         next;
                   11145:                     }
                   11146:                 }
                   11147:                 my ($fullpath) = split(/\0/,$key);
                   11148:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11149:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11150:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11151:                     }
                   11152:                 }
                   11153:             }
                   11154:         }
                   11155:     }
                   11156:     return %access;
                   11157: }
                   11158: 
                   11159: sub modify_access_controls {
                   11160:     my ($file_name,$changes,$domain,$user)=@_;
                   11161:     my ($outcome,$deloutcome);
                   11162:     my %store_permissions;
                   11163:     my %new_values;
                   11164:     my %new_control;
                   11165:     my %translation;
                   11166:     my @deletions = ();
                   11167:     my $now = time;
                   11168:     if (exists($$changes{'activate'})) {
                   11169:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11170:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11171:             my $numnew = scalar(@newitems);
                   11172:             for (my $i=0; $i<$numnew; $i++) {
                   11173:                 my $newkey = $newitems[$i];
                   11174:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11175:                 if ($newkey =~ /^\d+:/) { 
                   11176:                     $newkey =~ s/^(\d+)/$newid/;
                   11177:                     $translation{$1} = $newid;
                   11178:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11179:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11180:                     $translation{$1} = $newid;
                   11181:                 }
1.749     raeburn  11182:                 $new_values{$file_name."\0".$newkey} = 
                   11183:                                           $$changes{'activate'}{$newitems[$i]};
                   11184:                 $new_control{$newkey} = $now;
                   11185:             }
                   11186:         }
                   11187:     }
                   11188:     my %todelete;
                   11189:     my %changed_items;
                   11190:     foreach my $action ('delete','update') {
                   11191:         if (exists($$changes{$action})) {
                   11192:             if (ref($$changes{$action}) eq 'HASH') {
                   11193:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11194:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11195:                     if ($action eq 'delete') { 
                   11196:                         $todelete{$itemnum} = 1;
                   11197:                     } else {
                   11198:                         $changed_items{$itemnum} = $key;
                   11199:                     }
                   11200:                 }
1.745     raeburn  11201:             }
                   11202:         }
1.749     raeburn  11203:     }
                   11204:     # get lock on access controls for file.
                   11205:     my $lockhash = {
                   11206:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11207:                                                        ':'.$env{'user.domain'},
                   11208:                    }; 
                   11209:     my $tries = 0;
                   11210:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11211:    
1.1288    damieng  11212:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11213:         $tries ++;
1.1289    damieng  11214:         sleep(0.1);
1.749     raeburn  11215:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11216:     }
                   11217:     if ($gotlock eq 'ok') {
                   11218:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11219:         my ($tmp)=keys(%curr_permissions);
                   11220:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11221:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11222:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11223:             if (ref($curr_controls) eq 'HASH') {
                   11224:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11225:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11226:                     if (defined($todelete{$itemnum})) {
                   11227:                         push(@deletions,$file_name."\0".$control_item);
                   11228:                     } else {
                   11229:                         if (defined($changed_items{$itemnum})) {
                   11230:                             $new_control{$changed_items{$itemnum}} = $now;
                   11231:                             push(@deletions,$file_name."\0".$control_item);
                   11232:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11233:                         } else {
                   11234:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11235:                         }
                   11236:                     }
1.745     raeburn  11237:                 }
                   11238:             }
                   11239:         }
1.970     raeburn  11240:         my ($group);
                   11241:         if (&is_course($domain,$user)) {
                   11242:             ($group,my $file) = split(/\//,$file_name,2);
                   11243:         }
1.749     raeburn  11244:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11245:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11246:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11247:         #  remove lock
                   11248:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11249:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11250:         my $sqlresult =
1.970     raeburn  11251:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11252:                                     $group);
1.749     raeburn  11253:     } else {
                   11254:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11255:     }
1.749     raeburn  11256:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11257: }
                   11258: 
1.827     raeburn  11259: sub make_public_indefinitely {
1.1271    raeburn  11260:     my (@requrl) = @_;
                   11261:     return &automated_portfile_access('public',\@requrl);
                   11262: }
                   11263: 
                   11264: sub automated_portfile_access {
                   11265:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11266:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11267:         return 'invalid';
                   11268:     }
1.1271    raeburn  11269:     my %urls;
                   11270:     if (ref($addsref) eq 'ARRAY') {
                   11271:         foreach my $requrl (@{$addsref}) {
                   11272:             if (&is_portfolio_url($requrl)) {
                   11273:                 unless (exists($urls{$requrl})) {
                   11274:                     $urls{$requrl} = 'add';
                   11275:                 }
                   11276:             }
                   11277:         }
                   11278:     }
                   11279:     if (ref($delsref) eq 'ARRAY') {
                   11280:         foreach my $requrl (@{$delsref}) { 
                   11281:             if (&is_portfolio_url($requrl)) {
                   11282:                 unless (exists($urls{$requrl})) {
                   11283:                     $urls{$requrl} = 'delete'; 
                   11284:                 }
                   11285:             }
                   11286:         }
                   11287:     }
                   11288:     unless (keys(%urls)) {
                   11289:         return 'invalid';
                   11290:     }
                   11291:     my $ip;
                   11292:     if ($accesstype eq 'ip') {
                   11293:         if (ref($info) eq 'HASH') {
                   11294:             if ($info->{'ip'} ne '') {
                   11295:                 $ip = $info->{'ip'};
                   11296:             }
                   11297:         }
                   11298:         if ($ip eq '') {
                   11299:             return 'invalid';
                   11300:         }
                   11301:     }
                   11302:     my $errors;
1.827     raeburn  11303:     my $now = time;
1.1271    raeburn  11304:     my %current_perms;
                   11305:     foreach my $requrl (sort(keys(%urls))) {
                   11306:         my $action;
                   11307:         if ($urls{$requrl} eq 'add') {
                   11308:             $action = 'activate';
                   11309:         } else {
                   11310:             $action = 'none';
                   11311:         }
                   11312:         my $aclnum = 0;
1.827     raeburn  11313:         my (undef,$udom,$unum,$file_name,$group) =
                   11314:             &parse_portfolio_url($requrl);
1.1271    raeburn  11315:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11316:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11317:         }
                   11318:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11319:                                                    $group,$file_name);
                   11320:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11321:             my ($num,$scope,$end,$start) = 
                   11322:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11323:             if ($scope eq $accesstype) {
                   11324:                 if (($start <= $now) && ($end == 0)) {
                   11325:                     if ($accesstype eq 'ip') {
                   11326:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11327:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11328:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11329:                                     if ($urls{$requrl} eq 'add') {
                   11330:                                         $action = 'none';
                   11331:                                         last;
                   11332:                                     } else {
                   11333:                                         $action = 'delete';
                   11334:                                         $aclnum = $num;
                   11335:                                         last;
                   11336:                                     }
                   11337:                                 }
                   11338:                             }
                   11339:                         }
                   11340:                     } elsif ($accesstype eq 'public') {
                   11341:                         if ($urls{$requrl} eq 'add') {
                   11342:                             $action = 'none';
                   11343:                             last;
                   11344:                         } else {
                   11345:                             $action = 'delete';
                   11346:                             $aclnum = $num;
                   11347:                             last;
                   11348:                         }
                   11349:                     }
                   11350:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11351:                     $action = 'update';
                   11352:                     $aclnum = $num;
1.1271    raeburn  11353:                     last;
1.827     raeburn  11354:                 }
                   11355:             }
                   11356:         }
                   11357:         if ($action eq 'none') {
1.1271    raeburn  11358:             next;
1.827     raeburn  11359:         } else {
                   11360:             my %changes;
                   11361:             my $newend = 0;
                   11362:             my $newstart = $now;
1.1271    raeburn  11363:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11364:             $changes{$action}{$newkey} = {
1.1271    raeburn  11365:                 type => $accesstype,
1.827     raeburn  11366:                 time => {
                   11367:                     start => $newstart,
                   11368:                     end   => $newend,
                   11369:                 },
                   11370:             };
1.1271    raeburn  11371:             if ($accesstype eq 'ip') {
                   11372:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11373:             }
1.827     raeburn  11374:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11375:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11376:             unless ($outcome eq 'ok') {
                   11377:                 $errors .= $outcome.' ';
                   11378:             }
1.827     raeburn  11379:         }
1.1271    raeburn  11380:     }
                   11381:     if ($errors) {
                   11382:         $errors =~ s/\s$//;
                   11383:         return $errors;
1.827     raeburn  11384:     } else {
1.1271    raeburn  11385:         return 'ok';
1.827     raeburn  11386:     }
                   11387: }
                   11388: 
1.745     raeburn  11389: #------------------------------------------------------Get Marked as Read Only
                   11390: 
                   11391: sub get_marked_as_readonly {
                   11392:     my ($domain,$user,$what,$group) = @_;
                   11393:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11394:     my @readonly_files;
1.629     banghart 11395:     my $cmp1=$what;
                   11396:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11397:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11398:         if (defined($group)) {
                   11399:             if ($file_name !~ m-^\Q$group\E/-) {
                   11400:                 next;
                   11401:             }
                   11402:         }
1.561     banghart 11403:         if (ref($value) eq "ARRAY"){
                   11404:             foreach my $stored_what (@{$value}) {
1.629     banghart 11405:                 my $cmp2=$stored_what;
1.759     albertel 11406:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11407:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11408:                 }
1.629     banghart 11409:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11410:                     push(@readonly_files, $file_name);
1.745     raeburn  11411:                     last;
1.563     banghart 11412:                 } elsif (!defined($what)) {
                   11413:                     push(@readonly_files, $file_name);
1.745     raeburn  11414:                     last;
1.561     banghart 11415:                 }
                   11416:             }
1.745     raeburn  11417:         }
1.561     banghart 11418:     }
                   11419:     return @readonly_files;
                   11420: }
1.577     banghart 11421: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11422: 
1.577     banghart 11423: sub get_marked_as_readonly_hash {
1.745     raeburn  11424:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11425:     my %readonly_files;
1.745     raeburn  11426:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11427:         if (defined($group)) {
                   11428:             if ($file_name !~ m-^\Q$group\E/-) {
                   11429:                 next;
                   11430:             }
                   11431:         }
1.577     banghart 11432:         if (ref($value) eq "ARRAY"){
                   11433:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11434:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11435:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11436:                         if ($lock_descriptor eq 'graded') {
                   11437:                             $readonly_files{$file_name} = 'graded';
                   11438:                         } elsif ($lock_descriptor eq 'handback') {
                   11439:                             $readonly_files{$file_name} = 'handback';
                   11440:                         } else {
                   11441:                             if (!exists($readonly_files{$file_name})) {
                   11442:                                 $readonly_files{$file_name} = 'locked';
                   11443:                             }
                   11444:                         }
1.745     raeburn  11445:                     }
1.750     banghart 11446:                 } 
1.577     banghart 11447:             }
                   11448:         } 
                   11449:     }
                   11450:     return %readonly_files;
                   11451: }
1.559     banghart 11452: # ------------------------------------------------------------ Unmark as Read Only
                   11453: 
                   11454: sub unmark_as_readonly {
1.629     banghart 11455:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11456:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11457:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11458:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11459:     my $symb_crs = $what;
                   11460:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11461:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11462:     my ($tmp)=keys(%current_permissions);
                   11463:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11464:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11465:     foreach my $file (@readonly_files) {
1.759     albertel 11466: 	my $clean_file = &declutter_portfile($file);
                   11467: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11468: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11469:         my @new_locks;
                   11470:         my @del_keys;
                   11471:         if (ref($current_locks) eq "ARRAY"){
                   11472:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11473:                 my $compare=$locker;
1.749     raeburn  11474:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11475:                     $compare=join('',@{$locker});
1.746     raeburn  11476:                     if ($compare ne $symb_crs) {
                   11477:                         push(@new_locks, $locker);
                   11478:                     }
1.563     banghart 11479:                 }
                   11480:             }
1.650     albertel 11481:             if (scalar(@new_locks) > 0) {
1.563     banghart 11482:                 $current_permissions{$file} = \@new_locks;
                   11483:             } else {
                   11484:                 push(@del_keys, $file);
1.613     albertel 11485:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11486:                 delete($current_permissions{$file});
1.563     banghart 11487:             }
                   11488:         }
1.561     banghart 11489:     }
1.613     albertel 11490:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11491:     return;
                   11492: }
1.512     banghart 11493: 
1.17      www      11494: # ------------------------------------------------------------ Directory lister
                   11495: 
                   11496: sub dirlist {
1.955     raeburn  11497:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11498:     $uri=~s/^\///;
                   11499:     $uri=~s/\/$//;
1.253     stredwic 11500:     my ($udom, $uname);
1.955     raeburn  11501:     if ($getuserdir) {
1.253     stredwic 11502:         $udom = $userdomain;
                   11503:         $uname = $username;
1.955     raeburn  11504:     } else {
                   11505:         (undef,$udom,$uname)=split(/\//,$uri);
                   11506:         if(defined($userdomain)) {
                   11507:             $udom = $userdomain;
                   11508:         }
                   11509:         if(defined($username)) {
                   11510:             $uname = $username;
                   11511:         }
1.253     stredwic 11512:     }
1.955     raeburn  11513:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11514: 
1.955     raeburn  11515:     $dirRoot = $perlvar{'lonDocRoot'};
                   11516:     if (defined($getpropath)) {
                   11517:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11518:         $dirRoot =~ s/\/$//;
1.955     raeburn  11519:     } elsif (defined($getuserdir)) {
                   11520:         my $subdir=$uname.'__';
                   11521:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11522:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11523:                    ."/$udom/$subdir/$uname";
                   11524:     } elsif (defined($alternateRoot)) {
                   11525:         $dirRoot = $alternateRoot;
1.751     banghart 11526:     }
1.253     stredwic 11527: 
                   11528:     if($udom) {
                   11529:         if($uname) {
1.1135    raeburn  11530:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11531:             if ($uhome eq 'no_host') {
                   11532:                 return ([],'no_host');
                   11533:             }
1.955     raeburn  11534:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11535:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11536:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11537:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11538:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11539:             } else {
                   11540:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11541:             }
1.605     matthew  11542:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11543:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11544:                 @listing_results = split(/:/,$listing);
                   11545:             } else {
                   11546:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11547:             }
1.1135    raeburn  11548:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11549:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11550:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11551:                 return ([],$listing);
                   11552:             } else {
                   11553:                 return (\@listing_results);
1.1135    raeburn  11554:             }
1.955     raeburn  11555:         } elsif(!$alternateRoot) {
1.1136    raeburn  11556:             my (%allusers,%listerror);
1.841     albertel 11557: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11558:  	    foreach my $tryserver (keys(%servers)) {
                   11559:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11560:                                   &escape($udom),$tryserver);
                   11561:                 if ($listing eq 'unknown_cmd') {
                   11562: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11563: 				      $udom, $tryserver);
                   11564:                 } else {
                   11565:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11566:                 }
1.841     albertel 11567: 		if ($listing eq 'unknown_cmd') {
                   11568: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11569: 				      $udom, $tryserver);
                   11570: 		    @listing_results = split(/:/,$listing);
                   11571: 		} else {
                   11572: 		    @listing_results =
                   11573: 			map { &unescape($_); } split(/:/,$listing);
                   11574: 		}
1.1136    raeburn  11575:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11576:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11577:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11578:                     $listerror{$tryserver} = $listing;
                   11579:                 } else {
1.841     albertel 11580: 		    foreach my $line (@listing_results) {
                   11581: 			my ($entry) = split(/&/,$line,2);
                   11582: 			$allusers{$entry} = 1;
                   11583: 		    }
                   11584: 		}
1.253     stredwic 11585:             }
1.1136    raeburn  11586:             my @alluserslist=();
1.800     albertel 11587:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11588:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11589:             }
1.1318    droeschl 11590: 
                   11591:             if (!%listerror) {
                   11592:                 # no errors
                   11593:                 return (\@alluserslist);
                   11594:             } elsif (scalar(keys(%servers)) == 1) {
                   11595:                 # one library server, one error 
                   11596:                 my ($key) = keys(%listerror);
                   11597:                 return (\@alluserslist, $listerror{$key});
                   11598:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11599:                 # con_lost indicates that we might miss data from at least one
                   11600:                 # library server
                   11601:                 return (\@alluserslist, 'con_lost');
                   11602:             } else {
                   11603:                 # multiple library servers and no con_lost -> data should be
                   11604:                 # complete. 
                   11605:                 return (\@alluserslist);
                   11606:             }
                   11607: 
1.253     stredwic 11608:         } else {
1.1136    raeburn  11609:             return ([],'missing username');
1.253     stredwic 11610:         }
1.955     raeburn  11611:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11612:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11613:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11614:         return (\@all_domains);
1.955     raeburn  11615:     } else {
1.1136    raeburn  11616:         return ([],'missing domain');
1.275     stredwic 11617:     }
                   11618: }
                   11619: 
                   11620: # --------------------------------------------- GetFileTimestamp
                   11621: # This function utilizes dirlist and returns the date stamp for
                   11622: # when it was last modified.  It will also return an error of -1
                   11623: # if an error occurs
                   11624: 
                   11625: sub GetFileTimestamp {
1.955     raeburn  11626:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11627:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11628:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11629:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11630:                                     undef,$getuserdir);
                   11631:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11632:         return -1;
                   11633:     }
                   11634:     if (ref($fileref) eq 'ARRAY') {
                   11635:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11636:         # @stats contains first the filename, then the stat output
                   11637:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11638:     } else {
                   11639:         return -1;
1.253     stredwic 11640:     }
1.26      www      11641: }
                   11642: 
1.712     albertel 11643: sub stat_file {
                   11644:     my ($uri) = @_;
1.787     albertel 11645:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11646: 
1.955     raeburn  11647:     my ($udom,$uname,$file);
1.712     albertel 11648:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11649: 	($udom,$uname,$file) =
1.811     albertel 11650: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11651: 	$file = 'userfiles/'.$file;
                   11652:     }
                   11653:     if ($uri =~ m-^/res/-) {
                   11654: 	($udom,$uname) = 
1.807     albertel 11655: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11656: 	$file = $uri;
                   11657:     }
                   11658: 
                   11659:     if (!$udom || !$uname || !$file) {
                   11660: 	# unable to handle the uri
                   11661: 	return ();
                   11662:     }
1.956     raeburn  11663:     my $getpropath;
                   11664:     if ($file =~ /^userfiles\//) {
                   11665:         $getpropath = 1;
                   11666:     }
1.1136    raeburn  11667:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11668:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11669:         return ();
                   11670:     } else {
                   11671:         if (ref($listref) eq 'ARRAY') {
                   11672:             my @stats = split('&',$listref->[0]);
                   11673: 	    shift(@stats); #filename is first
                   11674: 	    return @stats;
                   11675:         }
1.712     albertel 11676:     }
                   11677:     return ();
                   11678: }
                   11679: 
1.1313    raeburn  11680: # --------------------------------------------------------- recursedirs
                   11681: # Recursive function to traverse either a specific user's Authoring Space
                   11682: # or corresponding Published Resource Space, and populate the hash ref:
                   11683: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11684: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11685: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11686: # files in Authoring Space.
                   11687: #
                   11688: # Inputs:
                   11689: #
                   11690: # $is_home - true if current server is home server for user's space
                   11691: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11692: # $docroot - Document root (i.e., /home/httpd/html
                   11693: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11694: # $relpath - Current path (relative to top level).
                   11695: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11696: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11697: #
                   11698: # Returns: nothing
                   11699: #
                   11700: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11701: #
                   11702: # Currently used by interface/londocs.pm to create linked select boxes for
                   11703: # directory and filename to import a Course "Author" resource into a course, and
                   11704: # also to create linked select boxes for Authoring Space and Directory to choose
                   11705: # save location for creation of a new "standard" problem from the Course Editor.
                   11706: #
                   11707: 
                   11708: sub recursedirs {
                   11709:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11710:     return unless (ref($dirhashref) eq 'HASH');
                   11711:     my $currpath = $docroot.$toppath;
                   11712:     if ($relpath) {
                   11713:         $currpath .= "/$relpath";
                   11714:     }
                   11715:     my $savefile;
                   11716:     if (ref($filehashref)) {
                   11717:         $savefile = 1;
                   11718:     }
                   11719:     if ($is_home) {
                   11720:         if (opendir(my $dirh,$currpath)) {
                   11721:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11722:                 next if ($item eq '');
                   11723:                 if (-d "$currpath/$item") {
                   11724:                     my $newpath;
                   11725:                     if ($relpath) {
                   11726:                         $newpath = "$relpath/$item";
                   11727:                     } else {
                   11728:                         $newpath = $item;
                   11729:                     }
                   11730:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11731:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11732:                 } elsif ($savefile) {
                   11733:                     if ($context eq 'priv') {
                   11734:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11735:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11736:                         }
                   11737:                     } else {
                   11738:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11739:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11740:                         }
                   11741:                     }
                   11742:                 }
                   11743:             }
                   11744:             closedir($dirh);
                   11745:         }
                   11746:     } else {
                   11747:         my ($dirlistref,$listerror) =
                   11748:             &dirlist($toppath.$relpath);
                   11749:         my @dir_lines;
                   11750:         my $dirptr=16384;
                   11751:         if (ref($dirlistref) eq 'ARRAY') {
                   11752:             foreach my $dir_line (sort
                   11753:                               {
                   11754:                                   my ($afile)=split('&',$a,2);
                   11755:                                   my ($bfile)=split('&',$b,2);
                   11756:                                   return (lc($afile) cmp lc($bfile));
                   11757:                               } (@{$dirlistref})) {
                   11758:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11759:                     split(/\&/,$dir_line,16);
                   11760:                 $item =~ s/\s+$//;
                   11761:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11762:                 if ($dirptr&$testdir) {
                   11763:                     my $newpath;
                   11764:                     if ($relpath) {
                   11765:                         $newpath = "$relpath/$item";
                   11766:                     } else {
                   11767:                         $relpath = '/';
                   11768:                         $newpath = $item;
                   11769:                     }
                   11770:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11771:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11772:                 } elsif ($savefile) {
                   11773:                     if ($context eq 'priv') {
                   11774:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11775:                             $filehashref->{$relpath}{$item} = 1;
                   11776:                         }
                   11777:                     } else {
                   11778:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11779:                             $filehashref->{$relpath}{$item} = 1;
                   11780:                         }
                   11781:                     }
                   11782:                 }
                   11783:             }
                   11784:         }
                   11785:     }
                   11786:     return;
                   11787: }
                   11788: 
1.26      www      11789: # -------------------------------------------------------- Value of a Condition
                   11790: 
1.713     albertel 11791: # gets the value of a specific preevaluated condition
                   11792: #    stored in the string  $env{user.state.<cid>}
                   11793: # or looks up a condition reference in the bighash and if if hasn't
                   11794: # already been evaluated recurses into docondval to get the value of
                   11795: # the condition, then memoizing it to 
                   11796: #   $env{user.state.<cid>.<condition>}
1.40      www      11797: sub directcondval {
                   11798:     my $number=shift;
1.620     albertel 11799:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11800: 	&Apache::lonuserstate::evalstate();
                   11801:     }
1.713     albertel 11802:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11803: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11804:     } elsif ($number =~ /^_/) {
                   11805: 	my $sub_condition;
                   11806: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11807: 		&GDBM_READER(),0640)) {
                   11808: 	    $sub_condition=$bighash{'conditions'.$number};
                   11809: 	    untie(%bighash);
                   11810: 	}
                   11811: 	my $value = &docondval($sub_condition);
1.949     raeburn  11812: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11813: 	return $value;
                   11814:     }
1.620     albertel 11815:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11816:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11817:     } else {
                   11818:        return 2;
                   11819:     }
                   11820: }
                   11821: 
1.713     albertel 11822: # get the collection of conditions for this resource
1.26      www      11823: sub condval {
                   11824:     my $condidx=shift;
1.54      www      11825:     my $allpathcond='';
1.713     albertel 11826:     foreach my $cond (split(/\|/,$condidx)) {
                   11827: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11828: 	    $allpathcond.=
                   11829: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11830: 	}
1.191     harris41 11831:     }
1.54      www      11832:     $allpathcond=~s/\|$//;
1.713     albertel 11833:     return &docondval($allpathcond);
                   11834: }
                   11835: 
                   11836: #evaluates an expression of conditions
                   11837: sub docondval {
                   11838:     my ($allpathcond) = @_;
                   11839:     my $result=0;
                   11840:     if ($env{'request.course.id'}
                   11841: 	&& defined($allpathcond)) {
                   11842: 	my $operand='|';
                   11843: 	my @stack;
                   11844: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11845: 	    if ($chunk eq '(') {
                   11846: 		push @stack,($operand,$result);
                   11847: 	    } elsif ($chunk eq ')') {
                   11848: 		my $before=pop @stack;
                   11849: 		if (pop @stack eq '&') {
                   11850: 		    $result=$result>$before?$before:$result;
                   11851: 		} else {
                   11852: 		    $result=$result>$before?$result:$before;
                   11853: 		}
                   11854: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11855: 		$operand=$chunk;
                   11856: 	    } else {
                   11857: 		my $new=directcondval($chunk);
                   11858: 		if ($operand eq '&') {
                   11859: 		    $result=$result>$new?$new:$result;
                   11860: 		} else {
                   11861: 		    $result=$result>$new?$result:$new;
                   11862: 		}
                   11863: 	    }
                   11864: 	}
1.26      www      11865:     }
                   11866:     return $result;
1.421     albertel 11867: }
                   11868: 
                   11869: # ---------------------------------------------------- Devalidate courseresdata
                   11870: 
                   11871: sub devalidatecourseresdata {
                   11872:     my ($coursenum,$coursedomain)=@_;
                   11873:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11874:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11875: }
                   11876: 
1.763     www      11877: 
1.200     www      11878: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11879: #
                   11880: #  Parameters:
                   11881: #      $coursenum    - Number of the course.
                   11882: #      $coursedomain - Domain at which the course was created.
                   11883: #  Returns:
                   11884: #     A hash of the course parameters along (I think) with timestamps
                   11885: #     and version info.
1.877     foxr     11886: 
1.624     albertel 11887: sub get_courseresdata {
                   11888:     my ($coursenum,$coursedomain)=@_;
1.200     www      11889:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11890:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11891:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11892:     my %dumpreply;
1.417     albertel 11893:     unless (defined($cached)) {
1.624     albertel 11894: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11895: 	$result=\%dumpreply;
1.251     albertel 11896: 	my ($tmp) = keys(%dumpreply);
                   11897: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11898: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11899: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11900: 	    return $tmp;
1.416     albertel 11901: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11902: 	    $result=undef;
1.599     albertel 11903: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11904: 	}
                   11905:     }
1.624     albertel 11906:     return $result;
                   11907: }
                   11908: 
1.633     albertel 11909: sub devalidateuserresdata {
                   11910:     my ($uname,$udom)=@_;
                   11911:     my $hashid="$udom:$uname";
                   11912:     &devalidate_cache_new('userres',$hashid);
                   11913: }
                   11914: 
1.624     albertel 11915: sub get_userresdata {
                   11916:     my ($uname,$udom)=@_;
                   11917:     #most student don\'t have any data set, check if there is some data
                   11918:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11919: 
                   11920:     my $hashid="$udom:$uname";
                   11921:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11922:     if (!defined($cached)) {
                   11923: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11924: 	$result=\%resourcedata;
                   11925: 	&do_cache_new('userres',$hashid,$result,600);
                   11926:     }
                   11927:     my ($tmp)=keys(%$result);
                   11928:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11929: 	return $result;
                   11930:     }
                   11931:     #error 2 occurs when the .db doesn't exist
                   11932:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11933:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11934: 	    &logthis("<font color=\"blue\">WARNING:".
                   11935: 		     " Trying to get resource data for ".
                   11936: 		     $uname." at ".$udom.": ".
                   11937: 		     $tmp."</font>");
                   11938:         }
1.624     albertel 11939:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11940: 	#&EXT_cache_set($udom,$uname);
                   11941: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11942: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11943:     }
                   11944:     return $tmp;
                   11945: }
1.879     foxr     11946: #----------------------------------------------- resdata - return resource data
                   11947: #  Purpose:
                   11948: #    Return resource data for either users or for a course.
                   11949: #  Parameters:
                   11950: #     $name      - Course/user name.
                   11951: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11952: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11953: #     $mapp      - decluttered URL of enclosing map  
                   11954: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11955: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11956: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11957: #     $courseid  - CourseID (first part of param identifier).
                   11958: #     $modifier  - Middle part of param identifier.
                   11959: #     $what      - Last part of param identifier.
1.879     foxr     11960: #     @which     - Array of names of resources desired.
                   11961: #  Returns:
                   11962: #     The value of the first reasource in @which that is found in the
                   11963: #     resource hash.
                   11964: #  Exceptional Conditions:
                   11965: #     If the $type passed in is not valid (not the string 'course' or 
                   11966: #     'user', an undefined  reference is returned.
                   11967: #     If none of the resources are found, an undef is returned
1.624     albertel 11968: sub resdata {
1.1301    raeburn  11969:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11970:         $modifier,$what,@which)=@_;
1.624     albertel 11971:     my $result;
                   11972:     if ($type eq 'course') {
                   11973: 	$result=&get_courseresdata($name,$domain);
                   11974:     } elsif ($type eq 'user') {
                   11975: 	$result=&get_userresdata($name,$domain);
                   11976:     }
                   11977:     if (!ref($result)) { return $result; }    
1.251     albertel 11978:     foreach my $item (@which) {
1.1301    raeburn  11979:         if ($item->[1] eq 'course') {
                   11980:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11981:                 unless ($$recursed) {
1.1302    raeburn  11982:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11983:                     $$recursed = 1;
                   11984:                 }
                   11985:                 foreach my $item (@${recurseup}) {
                   11986:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11987:                     last if (defined($result->{$norecursechk}));
                   11988:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11989:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11990:                 }
                   11991:             }
                   11992:         }
                   11993:         if (defined($result->{$item->[0]})) {
1.927     albertel 11994: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11995: 	}
1.250     albertel 11996:     }
1.291     albertel 11997:     return undef;
1.200     www      11998: }
                   11999: 
1.1360    raeburn  12000: sub get_domain_lti {
                   12001:     my ($cdom,$context) = @_;
                   12002:     my ($name,%lti);
                   12003:     if ($context eq 'consumer') {
                   12004:         $name = 'ltitools';
                   12005:     } elsif ($context eq 'provider') {
                   12006:         $name = 'lti';
                   12007:     } else {
                   12008:         return %lti;
                   12009:     }
                   12010:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  12011:     if (defined($cached)) {
                   12012:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12013:             %lti = %{$result};
1.1298    raeburn  12014:         }
                   12015:     } else {
1.1360    raeburn  12016:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12017:         if (ref($domconfig{$name}) eq 'HASH') {
                   12018:             %lti = %{$domconfig{$name}};
                   12019:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   12020:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   12021:                 foreach my $id (keys(%lti)) {
                   12022:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  12023:                         foreach my $item ('key','secret') {
1.1360    raeburn  12024:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  12025:                         }
                   12026:                     }
                   12027:                 }
                   12028:             }
1.1298    raeburn  12029:         }
                   12030:         my $cachetime = 24*60*60;
1.1360    raeburn  12031:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  12032:     }
1.1360    raeburn  12033:     return %lti;
1.1298    raeburn  12034: }
                   12035: 
1.1236    raeburn  12036: sub get_numsuppfiles {
                   12037:     my ($cnum,$cdom,$ignorecache)=@_;
                   12038:     my $hashid=$cnum.':'.$cdom;
                   12039:     my ($suppcount,$cached);
                   12040:     unless ($ignorecache) {
                   12041:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   12042:     }
                   12043:     unless (defined($cached)) {
                   12044:         my $chome=&homeserver($cnum,$cdom);
                   12045:         unless ($chome eq 'no_host') {
1.1366    raeburn  12046:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  12047:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  12048:             ($suppcount,$supptools,$errors) =
                   12049:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   12050:                                                          $supptools,$errors);
1.1236    raeburn  12051:         }
                   12052:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   12053:     }
                   12054:     return $suppcount;
                   12055: }
                   12056: 
1.379     matthew  12057: #
                   12058: # EXT resource caching routines
                   12059: #
                   12060: 
1.1302    raeburn  12061: {
                   12062: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12063: #
                   12064: # The course for which we cache
                   12065: my $cachedmapkey='';
                   12066: # The cached recursive maps for this course
                   12067: my %cachedmaps=();
                   12068: # When this was last done
                   12069: my $cachedmaptime='';
                   12070: 
1.379     matthew  12071: sub clear_EXT_cache_status {
1.383     albertel 12072:     &delenv('cache.EXT.');
1.379     matthew  12073: }
                   12074: 
                   12075: sub EXT_cache_status {
                   12076:     my ($target_domain,$target_user) = @_;
1.383     albertel 12077:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12078:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12079:         # We know already the user has no data
                   12080:         return 1;
                   12081:     } else {
                   12082:         return 0;
                   12083:     }
                   12084: }
                   12085: 
                   12086: sub EXT_cache_set {
                   12087:     my ($target_domain,$target_user) = @_;
1.383     albertel 12088:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12089:     #&appenv({$cachename => time});
1.379     matthew  12090: }
                   12091: 
1.28      www      12092: # --------------------------------------------------------- Value of a Variable
1.58      www      12093: sub EXT {
1.715     albertel 12094: 
1.1228    raeburn  12095:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12096:     unless ($varname) { return ''; }
1.218     albertel 12097:     #get real user name/domain, courseid and symb
                   12098:     my $courseid;
1.359     albertel 12099:     my $publicuser;
1.427     www      12100:     if ($symbparm) {
                   12101: 	$symbparm=&get_symb_from_alias($symbparm);
                   12102:     }
1.218     albertel 12103:     if (!($uname && $udom)) {
1.790     albertel 12104:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12105:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12106:     } else {
1.620     albertel 12107: 	$courseid=$env{'request.course.id'};
1.218     albertel 12108:     }
1.48      www      12109:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12110:     my $rest;
1.320     albertel 12111:     if (defined($therest[0])) {
1.48      www      12112:        $rest=join('.',@therest);
                   12113:     } else {
                   12114:        $rest='';
                   12115:     }
1.320     albertel 12116: 
1.57      www      12117:     my $qualifierrest=$qualifier;
                   12118:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12119:     my $spacequalifierrest=$space;
                   12120:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12121:     if ($realm eq 'user') {
1.48      www      12122: # --------------------------------------------------------------- user.resource
                   12123: 	if ($space eq 'resource') {
1.651     albertel 12124: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12125: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12126: 		 &&
1.744     albertel 12127: 		 ($symbparm eq &symbread()) ) {	
                   12128: 		# if we are in the middle of processing the resource the
                   12129: 		# get the value we are planning on committing
                   12130:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12131:                     return $Apache::lonhomework::results{$qualifierrest};
                   12132:                 } else {
                   12133:                     return $Apache::lonhomework::history{$qualifierrest};
                   12134:                 }
1.335     albertel 12135: 	    } else {
1.359     albertel 12136: 		my %restored;
1.620     albertel 12137: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12138: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12139: 		} else {
                   12140: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12141: 		}
1.335     albertel 12142: 		return $restored{$qualifierrest};
                   12143: 	    }
1.48      www      12144: # ----------------------------------------------------------------- user.access
                   12145:         } elsif ($space eq 'access') {
1.218     albertel 12146: 	    # FIXME - not supporting calls for a specific user
1.48      www      12147:             return &allowed($qualifier,$rest);
                   12148: # ------------------------------------------ user.preferences, user.environment
                   12149:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12150: 	    if (($uname eq $env{'user.name'}) &&
                   12151: 		($udom eq $env{'user.domain'})) {
                   12152: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12153: 	    } else {
1.359     albertel 12154: 		my %returnhash;
                   12155: 		if (!$publicuser) {
                   12156: 		    %returnhash=&userenvironment($udom,$uname,
                   12157: 						 $qualifierrest);
                   12158: 		}
1.218     albertel 12159: 		return $returnhash{$qualifierrest};
                   12160: 	    }
1.48      www      12161: # ----------------------------------------------------------------- user.course
                   12162:         } elsif ($space eq 'course') {
1.218     albertel 12163: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12164:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12165: # ------------------------------------------------------------------- user.role
                   12166:         } elsif ($space eq 'role') {
1.218     albertel 12167: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12168:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12169:             if ($qualifier eq 'value') {
                   12170: 		return $role;
                   12171:             } elsif ($qualifier eq 'extent') {
                   12172:                 return $where;
                   12173:             }
                   12174: # ----------------------------------------------------------------- user.domain
                   12175:         } elsif ($space eq 'domain') {
1.218     albertel 12176:             return $udom;
1.48      www      12177: # ------------------------------------------------------------------- user.name
                   12178:         } elsif ($space eq 'name') {
1.218     albertel 12179:             return $uname;
1.48      www      12180: # ---------------------------------------------------- Any other user namespace
1.29      www      12181:         } else {
1.359     albertel 12182: 	    my %reply;
                   12183: 	    if (!$publicuser) {
                   12184: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12185: 	    }
                   12186: 	    return $reply{$qualifierrest};
1.48      www      12187:         }
1.236     www      12188:     } elsif ($realm eq 'query') {
                   12189: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12190:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12191: 						[$spacequalifierrest]);
1.620     albertel 12192: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12193:    } elsif ($realm eq 'request') {
1.48      www      12194: # ------------------------------------------------------------- request.browser
                   12195:         if ($space eq 'browser') {
1.1145    bisitz   12196:             return $env{'browser.'.$qualifier};
1.57      www      12197: # ------------------------------------------------------------ request.filename
                   12198:         } else {
1.620     albertel 12199:             return $env{'request.'.$spacequalifierrest};
1.29      www      12200:         }
1.28      www      12201:     } elsif ($realm eq 'course') {
1.48      www      12202: # ---------------------------------------------------------- course.description
1.620     albertel 12203:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12204:     } elsif ($realm eq 'resource') {
1.165     www      12205: 
1.620     albertel 12206: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12207: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12208: 	}
1.693     albertel 12209: 
1.1232    raeburn  12210:         if ($qualifier eq '') {
                   12211: 	    if ($space eq 'title') {
                   12212: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12213: 	        return &gettitle($symbparm);
                   12214: 	    }
1.693     albertel 12215: 	
1.1232    raeburn  12216: 	    if ($space eq 'map') {
                   12217: 	        my ($map) = &decode_symb($symbparm);
                   12218: 	        return &symbread($map);
                   12219: 	    }
                   12220:             if ($space eq 'maptitle') {
                   12221:                 my ($map) = &decode_symb($symbparm);
                   12222:                 return &gettitle($map);
                   12223:             }
                   12224: 	    if ($space eq 'filename') {
                   12225: 	        if ($symbparm) {
                   12226: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12227: 	        }
                   12228: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12229: 	    }
1.1232    raeburn  12230: 
1.1233    raeburn  12231:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12232:                 if ($space eq 'visibleparts') {
                   12233:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12234:                     my $item;
                   12235:                     if (ref($navmap)) {
                   12236:                         my $res = $navmap->getBySymb($symbparm);
                   12237:                         my $parts = $res->parts();
                   12238:                         if (ref($parts) eq 'ARRAY') {
                   12239:                             $item = join(',',@{$parts});
                   12240:                         }
                   12241:                         undef($navmap);
1.1232    raeburn  12242:                     }
1.1233    raeburn  12243:                     return $item;
1.1232    raeburn  12244:                 }
                   12245:             }
                   12246:         }
1.693     albertel 12247: 
1.1301    raeburn  12248: 	my ($section, $group, @groups, @recurseup, $recursed);
                   12249: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  12250:         if (($courseid eq '') && ($cid)) {
                   12251:             $courseid = $cid;
                   12252:         }
                   12253: 	if (($symbparm && $courseid) && 
                   12254: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      12255: 
1.218     albertel 12256: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12257: 
1.60      www      12258: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12259: 	    my $symbp=$symbparm;
1.1301    raeburn  12260: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12261: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  12262:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12263: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12264: 	    if (($env{'user.name'} eq $uname) &&
                   12265: 		($env{'user.domain'} eq $udom)) {
                   12266: 		$section=$env{'request.course.sec'};
1.733     raeburn  12267:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12268:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12269: 	    } else {
1.539     albertel 12270: 		if (! defined($usection)) {
1.551     albertel 12271: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12272: 		} else {
                   12273: 		    $section = $usection;
                   12274: 		}
1.733     raeburn  12275:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12276: 	    }
                   12277: 
                   12278: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12279: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12280:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12281: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12282: 
1.593     albertel 12283: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12284: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12285:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12286: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12287: 
1.60      www      12288: # ----------------------------------------------------------- first, check user
1.624     albertel 12289: 
1.1301    raeburn  12290: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12291:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12292: 				       ([$courselevelr,'resource'],
                   12293: 					[$courselevelm,'map'     ],
1.1301    raeburn  12294:                                         [$courseleveli,'map'     ],
1.927     albertel 12295: 					[$courselevel, 'course'  ]));
1.931     albertel 12296: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12297: 
1.594     albertel 12298: # ------------------------------------------------ second, check some of course
1.684     raeburn  12299:             my $coursereply;
1.691     raeburn  12300:             if (@groups > 0) {
                   12301:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12302:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12303:                                        $mapp,\$recursed,\@recurseup);
                   12304:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12305:             }
1.96      www      12306: 
1.684     raeburn  12307: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12308: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12309: 				  'course',$mapp,\$recursed,\@recurseup,
                   12310:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12311: 				  ([$seclevelr,   'resource'],
                   12312: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12313:                                    [$secleveli,   'map'     ],
1.927     albertel 12314: 				   [$seclevel,    'course'  ],
                   12315: 				   [$courselevelr,'resource']));
                   12316: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12317: 
1.60      www      12318: # ------------------------------------------------------ third, check map parms
1.218     albertel 12319: 	    my %parmhash=();
                   12320: 	    my $thisparm='';
                   12321: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12322: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12323: 		    &GDBM_READER(),0640)) {
1.218     albertel 12324: 		$thisparm=$parmhash{$symbparm};
                   12325: 		untie(%parmhash);
                   12326: 	    }
1.927     albertel 12327: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12328: 	}
1.594     albertel 12329: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12330:  
                   12331:         my $what = $spacequalifierrest;
                   12332: 	$what=~s/\./\_/;
1.282     albertel 12333: 	my $filename;
                   12334: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12335: 	if ($symbparm) {
1.409     www      12336: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12337: 	} else {
1.620     albertel 12338: 	    $filename=$env{'request.filename'};
1.282     albertel 12339: 	}
1.1362    raeburn  12340:         my $toolsymb;
                   12341:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12342:             $toolsymb = $symbparm;
                   12343:         }
                   12344: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12345: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12346: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12347: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12348: 
1.1301    raeburn  12349: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12350: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12351: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12352: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12353: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12354: 				     'course',$mapp,\$recursed,\@recurseup,
                   12355:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12356: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12357:                                       [$courseleveli,'map'   ],
1.927     albertel 12358: 				      [$courselevel, 'course']));
                   12359: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12360: 	}
1.145     www      12361: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12362: 	unless ($space eq '0') {
1.336     albertel 12363: 	    my @parts=split(/_/,$space);
                   12364: 	    my $id=pop(@parts);
                   12365: 	    my $part=join('_',@parts);
                   12366: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12367: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12368: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12369: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12370: 	}
1.395     albertel 12371: 	if ($recurse) { return undef; }
1.1362    raeburn  12372: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12373: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12374: # ---------------------------------------------------- Any other user namespace
                   12375:     } elsif ($realm eq 'environment') {
                   12376: # ----------------------------------------------------------------- environment
1.620     albertel 12377: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12378: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12379: 	} else {
1.770     albertel 12380: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12381: 		return '';
                   12382: 	    }
1.219     albertel 12383: 	    my %returnhash=&userenvironment($udom,$uname,
                   12384: 					    $spacequalifierrest);
                   12385: 	    return $returnhash{$spacequalifierrest};
                   12386: 	}
1.28      www      12387:     } elsif ($realm eq 'system') {
1.48      www      12388: # ----------------------------------------------------------------- system.time
                   12389: 	if ($space eq 'time') {
                   12390: 	    return time;
                   12391:         }
1.696     albertel 12392:     } elsif ($realm eq 'server') {
                   12393: # ----------------------------------------------------------------- system.time
                   12394: 	if ($space eq 'name') {
                   12395: 	    return $ENV{'SERVER_NAME'};
                   12396:         }
1.1415    raeburn  12397:     } elsif ($realm eq 'client') {
                   12398:         if ($space eq 'remote_addr') {
                   12399:             return $ENV{'REMOTE_ADDR'};
                   12400:         }
1.28      www      12401:     }
1.48      www      12402:     return '';
1.61      www      12403: }
                   12404: 
1.927     albertel 12405: sub get_reply {
                   12406:     my ($reply_value) = @_;
1.940     raeburn  12407:     if (ref($reply_value) eq 'ARRAY') {
                   12408:         if (wantarray) {
                   12409: 	    return @$reply_value;
                   12410:         }
                   12411:         return $reply_value->[0];
                   12412:     } else {
                   12413:         return $reply_value;
1.927     albertel 12414:     }
                   12415: }
                   12416: 
1.691     raeburn  12417: sub check_group_parms {
1.1301    raeburn  12418:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12419:         $recursed,$recurseupref) = @_;
                   12420:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12421:                   [$what,'course']);
                   12422:     my $coursereply;
1.691     raeburn  12423:     foreach my $group (@{$groups}) {
1.1301    raeburn  12424:         my @groupitems = ();
1.691     raeburn  12425:         foreach my $level (@levels) {
1.927     albertel 12426:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12427:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12428:         }
1.1301    raeburn  12429:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12430:                                    $env{'course.'.$courseid.'.domain'},
                   12431:                                    'course',$mapp,$recursed,$recurseupref,
                   12432:                                    $courseid,'.['.$group.'].',$what,
                   12433:                                    @groupitems);
                   12434:         last if (defined($coursereply));
1.691     raeburn  12435:     }
                   12436:     return $coursereply;
                   12437: }
                   12438: 
1.1301    raeburn  12439: sub get_map_hierarchy {
1.1302    raeburn  12440:     my ($mapname,$courseid) = @_;
                   12441:     my @recurseup = ();
1.1301    raeburn  12442:     if ($mapname) {
1.1302    raeburn  12443:         if (($cachedmapkey eq $courseid) &&
                   12444:             (abs($cachedmaptime-time)<5)) {
                   12445:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12446:                 return @{$cachedmaps{$mapname}};
                   12447:             }
                   12448:         }
1.1301    raeburn  12449:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12450:         if (ref($navmap)) {
                   12451:             @recurseup = $navmap->recurseup_maps($mapname);
                   12452:             undef($navmap);
1.1302    raeburn  12453:             $cachedmaps{$mapname} = \@recurseup;
                   12454:             $cachedmaptime=time;
                   12455:             $cachedmapkey=$courseid;
1.1301    raeburn  12456:         }
                   12457:     }
                   12458:     return @recurseup;
                   12459: }
                   12460: 
1.1302    raeburn  12461: }
                   12462: 
1.691     raeburn  12463: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12464:     my ($courseid,@groups) = @_;
                   12465:     @groups = sort(@groups);
1.691     raeburn  12466:     return @groups;
                   12467: }
                   12468: 
1.395     albertel 12469: sub packages_tab_default {
1.1362    raeburn  12470:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12471:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12472: 
                   12473:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12474:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12475: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12476: 	if ($pack_type eq 'default') {
                   12477: 	    $do_default=1;
                   12478: 	} elsif ($pack_type eq 'extension') {
                   12479: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12480: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12481: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12482: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12483: 	}
                   12484:     }
                   12485:     # first look for a package that matches the requested part id
                   12486:     foreach my $package (@specifics) {
                   12487: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12488: 	next if ($pack_part ne $part);
                   12489: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12490: 	    return $packagetab{"$pack_type&$name&default"};
                   12491: 	}
                   12492:     }
                   12493:     # look for any possible matching non extension_ package
                   12494:     foreach my $package (@specifics) {
                   12495: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12496: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12497: 	    return $packagetab{"$pack_type&$name&default"};
                   12498: 	}
1.585     albertel 12499: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12500: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12501: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12502: 	}
                   12503:     }
1.738     albertel 12504:     # look for any posible extension_ match
                   12505:     foreach my $package (@extension) {
                   12506: 	my ($package,$pack_type)=@{$package};
                   12507: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12508: 	    return $packagetab{"$pack_type&$name&default"};
                   12509: 	}
                   12510: 	if (defined($packagetab{$package."&$name&default"})) {
                   12511: 	    return $packagetab{$package."&$name&default"};
                   12512: 	}
                   12513:     }
                   12514:     # look for a global default setting
                   12515:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12516: 	return $packagetab{"default&$name&default"};
                   12517:     }
1.395     albertel 12518:     return undef;
                   12519: }
                   12520: 
1.334     albertel 12521: sub add_prefix_and_part {
                   12522:     my ($prefix,$part)=@_;
                   12523:     my $keyroot;
                   12524:     if (defined($prefix) && $prefix !~ /^__/) {
                   12525: 	# prefix that has a part already
                   12526: 	$keyroot=$prefix;
                   12527:     } elsif (defined($prefix)) {
                   12528: 	# prefix that is missing a part
                   12529: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12530:     } else {
                   12531: 	# no prefix at all
                   12532: 	if (defined($part)) { $keyroot='_'.$part; }
                   12533:     }
                   12534:     return $keyroot;
                   12535: }
                   12536: 
1.71      www      12537: # ---------------------------------------------------------------- Get metadata
                   12538: 
1.599     albertel 12539: my %metaentry;
1.1070    www      12540: my %importedpartids;
1.1369    raeburn  12541: my %importedrespids;
1.71      www      12542: sub metadata {
1.1362    raeburn  12543:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12544:     $uri=&declutter($uri);
1.288     albertel 12545:     # if it is a non metadata possible uri return quickly
1.529     albertel 12546:     if (($uri eq '') || 
                   12547: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12548: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12549:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12550: 	return undef;
                   12551:     }
1.1261    raeburn  12552:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12553: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12554: 	return undef;
1.288     albertel 12555:     }
1.73      www      12556:     my $filename=$uri;
                   12557:     $uri=~s/\.meta$//;
1.172     www      12558: #
                   12559: # Is the metadata already cached?
1.177     www      12560: # Look at timestamp of caching
1.172     www      12561: # Everything is cached by the main uri, libraries are never directly cached
                   12562: #
1.428     albertel 12563:     if (!defined($liburi)) {
1.599     albertel 12564: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12565: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12566:     }
1.1362    raeburn  12567: 
                   12568: #
                   12569: # If the uri is for an external tool the file from
                   12570: # which metadata should be retrieved depends on whether
                   12571: # the tool had been configured to be gradable (set in the Course
                   12572: # Editor or Resource Editor).
                   12573: #
                   12574: # If a valid symb has been included as the third arg in the call
                   12575: # to &metadata() that can be used to retrieve the value of
                   12576: # parameter_0_gradable set for the resource, and included in the
                   12577: # uploaded map containing the tool. The value is retrieved via
                   12578: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12579: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12580: # is retrieved via &get().
                   12581: #
                   12582: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12583: # hiddenresource and encrypturl (during course initialization)
                   12584: # the map-level parameter for resource.0.gradable included in the 
                   12585: # uploaded map containing the tool will not yet have been stored
                   12586: # in the user_course_parms.db file for the user's session, so in 
                   12587: # this case fall back to retrieving gradable status from the
                   12588: # exttool_$marker.db file.
1.1362    raeburn  12589: #
                   12590: # In order to avoid an infinite loop, &metadata() will return
                   12591: # before a call to &EXT(), if the uri is for an external tool
                   12592: # and the $what for which metadata is being requested is
                   12593: # parameter_0_gradable or 0_gradable.
                   12594: #
                   12595: 
                   12596:     if ($uri =~ /ext\.tool$/) {
                   12597:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12598:             return;
                   12599:         } else {
                   12600:             my ($checked,$use_passback);
                   12601:             if ($toolsymb ne '') {
                   12602:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12603:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12604:                     $checked = 1;
                   12605:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12606:                         $use_passback = 1;
                   12607:                     }
                   12608:                 }
                   12609:             }
                   12610:             unless ($checked) {
                   12611:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12612:                 $marker=~s/\D//g;
1.1363    raeburn  12613:                 if ($marker) {
1.1362    raeburn  12614:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12615:                     $use_passback = $toolsettings{'gradable'};
                   12616:                 }
                   12617:             }
                   12618:             if ($use_passback) {
                   12619:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12620:             } else {
                   12621:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12622:             }
                   12623:         }
                   12624:     }
                   12625: 
1.428     albertel 12626:     {
1.1069    www      12627: # Imported parts would go here
1.1369    raeburn  12628:         my @origfiletagids=();
1.1069    www      12629:         my $importedparts=0;
1.1369    raeburn  12630: 
                   12631: # Imported responseids would go here
                   12632:         my $importedresponses=0;
1.172     www      12633: #
                   12634: # Is this a recursive call for a library?
                   12635: #
1.599     albertel 12636: #	if (! exists($metacache{$uri})) {
                   12637: #	    $metacache{$uri}={};
                   12638: #	}
1.924     albertel 12639: 	my $cachetime = 60*60;
1.171     www      12640:         if ($liburi) {
                   12641: 	    $liburi=&declutter($liburi);
                   12642:             $filename=$liburi;
1.401     bowersj2 12643:         } else {
1.599     albertel 12644: 	    &devalidate_cache_new('meta',$uri);
                   12645: 	    undef(%metaentry);
1.401     bowersj2 12646: 	}
1.140     www      12647:         my %metathesekeys=();
1.73      www      12648:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12649: 	my $metastring;
1.1140    www      12650: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12651: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12652: 	    $metastring = 
1.929     albertel 12653: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12654: 					  ('grade_target' => 'meta'));
                   12655: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12656: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12657:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12658: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12659: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12660: 	    $metastring=&getfile($file);
1.489     albertel 12661: 	}
1.208     albertel 12662:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12663:         my $token;
1.140     www      12664:         undef %metathesekeys;
1.71      www      12665:         while ($token=$parser->get_token) {
1.339     albertel 12666: 	    if ($token->[0] eq 'S') {
                   12667: 		if (defined($token->[2]->{'package'})) {
1.172     www      12668: #
                   12669: # This is a package - get package info
                   12670: #
1.339     albertel 12671: 		    my $package=$token->[2]->{'package'};
                   12672: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12673: 		    if (defined($token->[2]->{'id'})) { 
                   12674: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12675: 		    }
1.599     albertel 12676: 		    if ($metaentry{':packages'}) {
                   12677: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12678: 		    } else {
1.599     albertel 12679: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12680: 		    }
1.736     albertel 12681: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12682: 			my $part=$keyroot;
                   12683: 			$part=~s/^\_//;
1.736     albertel 12684: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12685: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12686: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12687: 			    # ignore package.tab specified default values
                   12688:                             # here &package_tab_default() will fetch those
                   12689: 			    if ($subp eq 'default') { next; }
1.736     albertel 12690: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12691: 			    my $unikey;
                   12692: 			    if ($pack =~ /_0$/) {
                   12693: 				$unikey='parameter_0_'.$name;
                   12694: 				$part=0;
                   12695: 			    } else {
                   12696: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12697: 			    }
1.339     albertel 12698: 			    if ($subp eq 'display') {
                   12699: 				$value.=' [Part: '.$part.']';
                   12700: 			    }
1.599     albertel 12701: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12702: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12703: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12704: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12705: 			    }
1.599     albertel 12706: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12707: 				$metaentry{':'.$unikey}=
                   12708: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12709: 			    }
1.339     albertel 12710: 			}
                   12711: 		    }
                   12712: 		} else {
1.172     www      12713: #
                   12714: # This is not a package - some other kind of start tag
1.339     albertel 12715: #
                   12716: 		    my $entry=$token->[1];
1.1068    www      12717: 		    my $unikey='';
1.175     www      12718: 
1.339     albertel 12719: 		    if ($entry eq 'import') {
1.175     www      12720: #
                   12721: # Importing a library here
1.339     albertel 12722: #
1.1067    www      12723:                         my $location=$parser->get_text('/import');
                   12724:                         my $dir=$filename;
                   12725:                         $dir=~s|[^/]*$||;
                   12726:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12727: 
                   12728:                         my $importid=$token->[2]->{'id'};
1.1068    www      12729:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12730: #
                   12731: # Check metadata for imported file to
                   12732: # see if it contained response items
                   12733: #
1.1372    raeburn  12734:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12735:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12736:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12737:                                                            $depthcount+1));
                   12738:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12739:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12740:                                                              undef,$depthcount+1);
                   12741:                             if ($libresponseorder ne '') {
                   12742:                                 if ($#origfiletagids<0) {
                   12743:                                     undef(%importedrespids);
                   12744:                                     undef(%importedpartids);
                   12745:                                 }
1.1373    raeburn  12746:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12747:                                 if (@respids) {
                   12748:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12749:                                 }
                   12750:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12751:                                     $importedresponses = 1;
1.1369    raeburn  12752: # We need to get the original file and the imported file to get the response order correct
                   12753: # Load and inspect original file
1.1372    raeburn  12754:                                     if ($#origfiletagids<0) {
                   12755:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12756:                                         $origfile=&getfile($origfilelocation);
                   12757:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12758:                                     }
1.1369    raeburn  12759:                                 }
                   12760:                             }
                   12761:                         }
1.1370    raeburn  12762: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12763: # hash populated for imported library file
                   12764:                         %metaentry = %currmetaentry;
                   12765:                         undef(%currmetaentry);
1.1374    raeburn  12766:                         if ($importmode eq 'part') {
1.1068    www      12767: # Import as part(s)
1.1069    www      12768:                            $importedparts=1;
                   12769: # We need to get the original file and the imported file to get the part order correct
                   12770: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12771: # Load and inspect original file if we didn't do that already
                   12772:                            if ($#origfiletagids<0) {
                   12773:                                undef(%importedrespids);
                   12774:                                undef(%importedpartids);
                   12775:                                if ($origfile eq '') {
                   12776:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12777:                                    $origfile=&getfile($origfilelocation);
                   12778:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12779:                                }
1.1070    www      12780:                            }
1.1372    raeburn  12781:                            my @impfilepartids;
                   12782: # If <partorder> tag is included in metadata for the imported file
                   12783: # get the parts in the imported file from that.
                   12784:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12785:                                %currmetaentry = %metaentry;
                   12786:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12787:                                                             $depthcount+1);
                   12788:                                %metaentry = %currmetaentry;
                   12789:                                undef(%currmetaentry);
                   12790:                                if ($libpartorder ne '') {
                   12791:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12792:                                }
                   12793:                            } else {
                   12794: # If no <partorder> tag available, load and inspect imported file
                   12795:                                my $impfile=&getfile($location);
                   12796:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12797:                            }
1.1069    www      12798:                            if ($#impfilepartids>=0) {
                   12799: # This problem had parts
1.1070    www      12800:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12801:                            } else {
                   12802: # Importing by turning a single problem into a problem part
                   12803: # It gets the import-tags ID as part-ID
                   12804:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12805:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12806:                            }
1.1068    www      12807:                         } else {
1.1374    raeburn  12808: # Import as problem or as normal import
                   12809:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12810:                             unless ($importmode eq 'problem') {
1.1068    www      12811: # Normal import
1.1374    raeburn  12812:                                 if (defined($token->[2]->{'id'})) {
                   12813:                                     $unikey.='_'.$token->[2]->{'id'};
                   12814:                                 }
                   12815:                             }
                   12816: # Check metadata for imported file to
                   12817: # see if it contained parts
                   12818:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12819:                                 %currmetaentry = %metaentry;
                   12820:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12821:                                                              $depthcount+1);
                   12822:                                 %metaentry = %currmetaentry;
                   12823:                                 undef(%currmetaentry);
                   12824:                                 if ($libpartorder ne '') {
                   12825:                                     $importedparts = 1;
                   12826:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12827:                                 }
                   12828:                             }
1.1067    www      12829:                         }
1.339     albertel 12830: 			if ($depthcount<20) {
1.736     albertel 12831: 			    my $metadata = 
1.1362    raeburn  12832: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12833: 					  $depthcount+1);
                   12834: 			    foreach my $meta (split(',',$metadata)) {
                   12835: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12836: 				$metathesekeys{$meta}=1;
1.339     albertel 12837: 			    }
1.1068    www      12838:                         }
1.1067    www      12839: 		    } else {
                   12840: #
                   12841: # Not importing, some other kind of non-package, non-library start tag
                   12842: # 
                   12843:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12844:                         if (defined($token->[2]->{'id'})) {
                   12845:                             $unikey.='_'.$token->[2]->{'id'};
                   12846:                         }
1.339     albertel 12847: 			if (defined($token->[2]->{'name'})) { 
                   12848: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12849: 			}
                   12850: 			$metathesekeys{$unikey}=1;
1.736     albertel 12851: 			foreach my $param (@{$token->[3]}) {
                   12852: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12853: 				$token->[2]->{$param};
1.339     albertel 12854: 			}
                   12855: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12856: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12857: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12858: 		 # only ws inside the tag, and not in default, so use default
                   12859: 		 # as value
1.599     albertel 12860: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12861: 			} elsif ( $internaltext =~ /\S/ ) {
                   12862: 		  # something interesting inside the tag
                   12863: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12864: 			} else {
1.908     albertel 12865: 		  # no interesting values, don't set a default
1.339     albertel 12866: 			}
1.172     www      12867: # end of not-a-package not-a-library import
1.339     albertel 12868: 		    }
1.172     www      12869: # end of not-a-package start tag
1.339     albertel 12870: 		}
1.172     www      12871: # the next is the end of "start tag"
1.339     albertel 12872: 	    }
                   12873: 	}
1.483     albertel 12874: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12875: 	$extension = lc($extension);
                   12876: 	if ($extension eq 'htm') { $extension='html'; }
                   12877: 
1.737     albertel 12878: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12879: 	    #no specific packages #how's our extension
                   12880: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12881: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12882: 					 \%metathesekeys);
                   12883: 	}
1.883     albertel 12884: 
                   12885: 	if (!exists($metaentry{':packages'})
                   12886: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12887: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12888: 		#no specific packages well let's get default then
                   12889: 		if ($key!~/^default&/) { next; }
1.488     albertel 12890: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12891: 					     \%metathesekeys);
                   12892: 	    }
                   12893: 	}
1.338     www      12894: # are there custom rights to evaluate
1.599     albertel 12895: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12896: 
1.338     www      12897:     #
                   12898:     # Importing a rights file here
1.339     albertel 12899:     #
                   12900: 	    unless ($depthcount) {
1.599     albertel 12901: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12902: 		my $dir=$filename;
                   12903: 		$dir=~s|[^/]*$||;
                   12904: 		$location=&filelocation($dir,$location);
1.736     albertel 12905: 		my $rights_metadata =
1.1362    raeburn  12906: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12907: 			      $depthcount+1);
                   12908: 		foreach my $rights (split(',',$rights_metadata)) {
                   12909: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12910: 		    $metathesekeys{$rights}=1;
1.339     albertel 12911: 		}
                   12912: 	    }
                   12913: 	}
1.737     albertel 12914: 	# uniqifiy package listing
                   12915: 	my %seen;
                   12916: 	my @uniq_packages =
                   12917: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12918: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12919: 
1.1369    raeburn  12920:         if (($importedresponses) || ($importedparts)) {
                   12921:             if ($importedparts) {
1.1070    www      12922: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12923:                 $metaentry{':partorder'}='';
                   12924:                 $metathesekeys{'partorder'}=1;
                   12925:             }
                   12926:             if ($importedresponses) {
                   12927: # We had imported responses and need to rebuil responseorder
                   12928:                 $metaentry{':responseorder'}='';
                   12929:                 $metathesekeys{'responseorder'}=1;
                   12930:             }
                   12931:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12932:                 my $origid = $origfiletagids[$index+1];
                   12933:                 if ($origfiletagids[$index] eq 'part') {
                   12934: # Original part, part of the problem
                   12935:                     if ($importedparts) {
                   12936:                         $metaentry{':partorder'}.=','.$origid;
                   12937:                     }
                   12938:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12939:                     if ($importedparts) {
                   12940: # We have imported parts at this position
1.1373    raeburn  12941:                         if ($importedpartids{$origid} ne '') {
                   12942:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12943:                         }
1.1369    raeburn  12944:                     }
                   12945:                     if ($importedresponses) {
                   12946: # We have imported responses at this position
1.1373    raeburn  12947:                         if ($importedrespids{$origid} ne '') {
                   12948:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12949:                         }
                   12950:                     }
                   12951:                 } else {
                   12952: # Original response item, part of the problem
                   12953:                     if ($importedresponses) {
                   12954:                         $metaentry{':responseorder'}.=','.$origid;
                   12955:                     }
                   12956:                 }
                   12957:             }
                   12958:             if ($importedparts) {
                   12959:                 $metaentry{':partorder'}=~s/^\,//;
                   12960:             }
                   12961:             if ($importedresponses) {
                   12962:                 $metaentry{':responseorder'}=~s/^\,//;
                   12963:             }
1.1070    www      12964:         }
1.737     albertel 12965: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12966: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12967: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12968:         unless ($liburi) {
                   12969: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12970:         }
1.177     www      12971: # this is the end of "was not already recently cached
1.71      www      12972:     }
1.599     albertel 12973:     return $metaentry{':'.$what};
1.261     albertel 12974: }
                   12975: 
1.488     albertel 12976: sub metadata_create_package_def {
1.483     albertel 12977:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12978:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12979:     if ($subp eq 'default') { next; }
                   12980:     
1.599     albertel 12981:     if (defined($metaentry{':packages'})) {
                   12982: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12983:     } else {
1.599     albertel 12984: 	$metaentry{':packages'}=$package;
1.483     albertel 12985:     }
                   12986:     my $value=$packagetab{$key};
                   12987:     my $unikey;
                   12988:     $unikey='parameter_0_'.$name;
1.599     albertel 12989:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12990:     $$metathesekeys{$unikey}=1;
1.599     albertel 12991:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12992: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12993:     }
1.599     albertel 12994:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12995: 	$metaentry{':'.$unikey}=
                   12996: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12997:     }
                   12998: }
                   12999: 
1.261     albertel 13000: sub metadata_generate_part0 {
                   13001:     my ($metadata,$metacache,$uri) = @_;
                   13002:     my %allnames;
1.737     albertel 13003:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13004: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13005: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13006: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13007: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13008: 	    $allnames{$name}=$part;
                   13009: 	  }
                   13010: 	}
                   13011:     }
                   13012:     foreach my $name (keys(%allnames)) {
                   13013:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13014:       my $key=":parameter_0_$name";
1.261     albertel 13015:       $$metacache{"$key.part"}='0';
                   13016:       $$metacache{"$key.name"}=$name;
1.428     albertel 13017:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13018: 					   $allnames{$name}.'_'.$name.
                   13019: 					   '.type'};
1.428     albertel 13020:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13021: 			     '.display'};
1.644     www      13022:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13023:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13024:       $$metacache{"$key.display"}=$olddis;
                   13025:     }
1.71      www      13026: }
                   13027: 
1.764     albertel 13028: # ------------------------------------------------------ Devalidate title cache
                   13029: 
                   13030: sub devalidate_title_cache {
                   13031:     my ($url)=@_;
                   13032:     if (!$env{'request.course.id'}) { return; }
                   13033:     my $symb=&symbread($url);
                   13034:     if (!$symb) { return; }
                   13035:     my $key=$env{'request.course.id'}."\0".$symb;
                   13036:     &devalidate_cache_new('title',$key);
                   13037: }
                   13038: 
1.1014    droeschl 13039: # ------------------------------------------------- Get the title of a course
                   13040: 
                   13041: sub current_course_title {
                   13042:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13043: }
1.301     www      13044: # ------------------------------------------------- Get the title of a resource
                   13045: 
                   13046: sub gettitle {
                   13047:     my $urlsymb=shift;
                   13048:     my $symb=&symbread($urlsymb);
1.534     albertel 13049:     if ($symb) {
1.620     albertel 13050: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13051: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13052: 	if (defined($cached)) { 
                   13053: 	    return $result;
                   13054: 	}
1.534     albertel 13055: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13056: 	my $title='';
1.907     albertel 13057: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13058: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13059: 	} else {
                   13060: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13061: 		    &GDBM_READER(),0640)) {
                   13062: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13063: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13064: 		untie(%bighash);
                   13065: 	    }
1.534     albertel 13066: 	}
                   13067: 	$title=~s/\&colon\;/\:/gs;
                   13068: 	if ($title) {
1.1159    www      13069: # Remember both $symb and $title for dynamic metadata
                   13070:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13071:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13072: # Cache this title and then return it
1.599     albertel 13073: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13074: 	}
                   13075: 	$urlsymb=$url;
                   13076:     }
                   13077:     my $title=&metadata($urlsymb,'title');
                   13078:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13079:     return $title;
1.301     www      13080: }
1.613     albertel 13081: 
1.614     albertel 13082: sub get_slot {
                   13083:     my ($which,$cnum,$cdom)=@_;
                   13084:     if (!$cnum || !$cdom) {
1.790     albertel 13085: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13086: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13087: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13088:     }
1.703     albertel 13089:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13090:     my %slotinfo;
                   13091:     if (exists($remembered{$key})) {
                   13092: 	$slotinfo{$which} = $remembered{$key};
                   13093:     } else {
                   13094: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13095: 	&Apache::lonhomework::showhash(%slotinfo);
                   13096: 	my ($tmp)=keys(%slotinfo);
                   13097: 	if ($tmp=~/^error:/) { return (); }
                   13098: 	$remembered{$key} = $slotinfo{$which};
                   13099:     }
1.616     albertel 13100:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13101: 	return %{$slotinfo{$which}};
                   13102:     }
                   13103:     return $slotinfo{$which};
1.614     albertel 13104: }
1.1150    raeburn  13105: 
                   13106: sub get_reservable_slots {
                   13107:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13108:     my $now = time;
                   13109:     my $reservable_info;
                   13110:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13111:     if (exists($remembered{$key})) {
                   13112:         $reservable_info = $remembered{$key};
                   13113:     } else {
                   13114:         my %resv;
                   13115:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13116:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13117:         $reservable_info = \%resv;
                   13118:         $remembered{$key} = $reservable_info;
                   13119:     }
                   13120:     return $reservable_info;
                   13121: }
                   13122: 
                   13123: sub get_course_slots {
                   13124:     my ($cnum,$cdom) = @_;
                   13125:     my $hashid=$cnum.':'.$cdom;
                   13126:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13127:     if (defined($cached)) {
                   13128:         if (ref($result) eq 'HASH') {
                   13129:             return %{$result};
                   13130:         }
                   13131:     } else {
                   13132:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13133:         my ($tmp) = keys(%slots);
                   13134:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  13135:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13136:             return %slots;
                   13137:         }
                   13138:     }
                   13139:     return;
                   13140: }
                   13141: 
                   13142: sub devalidate_slots_cache {
                   13143:     my ($cnum,$cdom)=@_;
                   13144:     my $hashid=$cnum.':'.$cdom;
                   13145:     &devalidate_cache_new('allslots',$hashid);
                   13146: }
                   13147: 
1.1181    raeburn  13148: sub get_coursechange {
                   13149:     my ($cdom,$cnum) = @_;
                   13150:     if ($cdom eq '' || $cnum eq '') {
                   13151:         return unless ($env{'request.course.id'});
                   13152:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13153:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13154:     }
                   13155:     my $hashid=$cdom.'_'.$cnum;
                   13156:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13157:     if ((defined($cached)) && ($change ne '')) {
                   13158:         return $change;
                   13159:     } else {
                   13160:         my %crshash;
                   13161:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13162:         if ($crshash{'internal.contentchange'} eq '') {
                   13163:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13164:             if ($change eq '') {
                   13165:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13166:                 $change = $crshash{'internal.created'};
                   13167:             }
                   13168:         } else {
                   13169:             $change = $crshash{'internal.contentchange'};
                   13170:         }
                   13171:         my $cachetime = 600;
                   13172:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13173:     }
                   13174:     return $change;
                   13175: }
                   13176: 
                   13177: sub devalidate_coursechange_cache {
                   13178:     my ($cnum,$cdom)=@_;
                   13179:     my $hashid=$cnum.':'.$cdom;
                   13180:     &devalidate_cache_new('crschange',$hashid);
                   13181: }
                   13182: 
1.31      www      13183: # ------------------------------------------------- Update symbolic store links
                   13184: 
                   13185: sub symblist {
                   13186:     my ($mapname,%newhash)=@_;
1.438     www      13187:     $mapname=&deversion(&declutter($mapname));
1.31      www      13188:     my %hash;
1.620     albertel 13189:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13190:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13191:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13192: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13193: 		next if ($url eq 'last_known'
                   13194: 			 && $env{'form.no_update_last_known'});
                   13195: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13196: 						    $newhash{$url}->[1],
                   13197: 						    $newhash{$url}->[0]);
1.191     harris41 13198:             }
1.31      www      13199:             if (untie(%hash)) {
                   13200: 		return 'ok';
                   13201:             }
                   13202:         }
                   13203:     }
                   13204:     return 'error';
1.212     www      13205: }
                   13206: 
                   13207: # --------------------------------------------------------------- Verify a symb
                   13208: 
                   13209: sub symbverify {
1.1190    raeburn  13210:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13211:     my $thisfn=$thisurl;
1.439     www      13212:     $thisfn=&declutter($thisfn);
1.215     www      13213: # direct jump to resource in page or to a sequence - will construct own symbs
                   13214:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13215: # check URL part
1.409     www      13216:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13217: 
1.431     www      13218:     unless ($url eq $thisfn) { return 0; }
1.213     www      13219: 
1.216     www      13220:     $symb=&symbclean($symb);
1.510     www      13221:     $thisurl=&deversion($thisurl);
1.439     www      13222:     $thisfn=&deversion($thisfn);
1.213     www      13223: 
                   13224:     my %bighash;
                   13225:     my $okay=0;
1.431     www      13226: 
1.620     albertel 13227:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13228:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13229:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13230:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  13231:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13232:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13233:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13234:             }
                   13235:         }
                   13236:         my $ids;
1.1419    raeburn  13237:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13238:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  13239:         } else {
                   13240:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13241:         }
1.1102    raeburn  13242:         unless ($ids) {
                   13243:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   13244:             $ids=$bighash{$idkey};
1.216     www      13245:         }
                   13246:         if ($ids) {
                   13247: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  13248:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  13249:                 $symb =~ s/\?.+$//;
1.1202    raeburn  13250:             }
1.800     albertel 13251: 	    foreach my $id (split(/\,/,$ids)) {
                   13252: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13253:                if (
                   13254:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  13255:    eq $symb) {
                   13256:                    if (ref($encstate)) {
                   13257:                        $$encstate = $bighash{'encrypted_'.$id};
                   13258:                    }
1.620     albertel 13259: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  13260: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   13261:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  13262: 		       $okay=1;
1.1202    raeburn  13263:                        last;
1.582     albertel 13264: 		   }
                   13265: 	       }
1.216     www      13266: 	   }
                   13267:         }
1.213     www      13268: 	untie(%bighash);
                   13269:     }
                   13270:     return $okay;
1.31      www      13271: }
                   13272: 
1.210     www      13273: # --------------------------------------------------------------- Clean-up symb
                   13274: 
                   13275: sub symbclean {
                   13276:     my $symb=shift;
1.568     albertel 13277:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13278: # remove version from map
                   13279:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13280: 
1.210     www      13281: # remove version from URL
                   13282:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13283: 
1.507     www      13284: # remove wrapper
                   13285: 
1.510     www      13286:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13287:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13288:     return $symb;
1.409     www      13289: }
                   13290: 
                   13291: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13292: 
                   13293: sub encode_symb {
                   13294:     my ($map,$resid,$url)=@_;
                   13295:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13296: }
1.409     www      13297: 
                   13298: sub decode_symb {
1.568     albertel 13299:     my $symb=shift;
                   13300:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13301:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13302:     return (&fixversion($map),$resid,&fixversion($url));
                   13303: }
                   13304: 
                   13305: sub fixversion {
                   13306:     my $fn=shift;
1.609     banghart 13307:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13308:     my %bighash;
                   13309:     my $uri=&clutter($fn);
1.620     albertel 13310:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13311: # is this cached?
1.599     albertel 13312:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13313:     if (defined($cached)) { return $result; }
                   13314: # unfortunately not cached, or expired
1.620     albertel 13315:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13316: 	    &GDBM_READER(),0640)) {
                   13317:  	if ($bighash{'version_'.$uri}) {
                   13318:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13319:  	    unless (($version eq 'mostrecent') || 
                   13320: 		    ($version==&getversion($uri))) {
1.440     www      13321:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13322:  	    }
                   13323:  	}
                   13324:  	untie %bighash;
1.413     www      13325:     }
1.599     albertel 13326:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13327: }
                   13328: 
                   13329: sub deversion {
                   13330:     my $url=shift;
                   13331:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13332:     return $url;
1.210     www      13333: }
                   13334: 
1.31      www      13335: # ------------------------------------------------------ Return symb list entry
                   13336: 
                   13337: sub symbread {
1.1424    raeburn  13338:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  13339:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  13340:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  13341:     if (defined($env{$cache_str})) {
1.1424    raeburn  13342:         unless (ref($possibles) eq 'HASH') {
                   13343:             if ($ignorecachednull) {
                   13344:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13345:             } else {
                   13346:                 return $env{$cache_str};
                   13347:             }
1.1282    raeburn  13348:         }
                   13349:     }
1.242     www      13350: # no filename provided? try from environment
1.1265    raeburn  13351:     unless ($thisfn) {
1.620     albertel 13352:         if ($env{'request.symb'}) {
1.1427    raeburn  13353:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13354: 	}
1.620     albertel 13355: 	$thisfn=$env{'request.filename'};
1.44      www      13356:     }
1.569     albertel 13357:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13358: # is that filename actually a symb? Verify, clean, and return
                   13359:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13360: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  13361: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13362: 	}
1.242     www      13363:     }
1.44      www      13364:     $thisfn=declutter($thisfn);
1.31      www      13365:     my %hash;
1.37      www      13366:     my %bighash;
                   13367:     my $syval='';
1.620     albertel 13368:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13369:         my $targetfn = $thisfn;
1.609     banghart 13370:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13371:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13372:         }
1.687     albertel 13373: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13374: 	    $targetfn=$1;
                   13375: 	}
1.1427    raeburn  13376:         unless ($ignoresymbdb) {
1.1424    raeburn  13377:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13378:                           &GDBM_READER(),0640)) {
                   13379: 	        $syval=$hash{$targetfn};
                   13380:                 untie(%hash);
                   13381:             }
1.1427    raeburn  13382:             if ($syval && $checkforblock) {
                   13383:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  13384:                 if (@blockers) {
                   13385:                     $syval='';
                   13386:                 }
                   13387:             }
1.37      www      13388:         }
                   13389: # ---------------------------------------------------------- There was an entry
                   13390:         if ($syval) {
1.601     albertel 13391: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13392: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13393: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13394: 		    #return $env{$cache_str}='';
1.601     albertel 13395: 		#}    
                   13396: 		#$syval.=$1;
                   13397: 	    #}
1.37      www      13398:         } else {
                   13399: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13400:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13401:                             &GDBM_READER(),0640)) {
1.37      www      13402: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13403:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13404:               unless ($ids) { 
                   13405:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13406:               }
                   13407:               unless ($ids) {
                   13408: # alias?
                   13409: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13410:               }
1.37      www      13411:               if ($ids) {
                   13412: # ------------------------------------------------------------------- Has ID(s)
                   13413:                  my @possibilities=split(/\,/,$ids);
1.39      www      13414:                  if ($#possibilities==0) {
                   13415: # ----------------------------------------------- There is only one possibility
1.37      www      13416: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13417: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13418: 						    $resid,$thisfn);
1.1282    raeburn  13419:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  13420:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13421:                              $possibles->{$syval} = 1;
                   13422:                          }
1.1282    raeburn  13423:                      }
                   13424:                      if ($checkforblock) {
1.1424    raeburn  13425:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  13426:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  13427:                              if (@blockers) {
                   13428:                                  $syval = '';
1.1425    raeburn  13429:                                  untie(%bighash);
                   13430:                                  return $env{$cache_str}='';
1.1424    raeburn  13431:                              }
1.1282    raeburn  13432:                          }
                   13433:                      }
                   13434:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13435: # ------------------------------------------ There is more than one possibility
                   13436:                      my $realpossible=0;
1.800     albertel 13437:                      foreach my $id (@possibilities) {
                   13438: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13439:                          my $canaccess;
                   13440:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13441:                              $canaccess = 1;
                   13442:                          } else { 
                   13443:                              $canaccess = &allowed('bre',$file);
                   13444:                          }
                   13445:                          if ($canaccess) {
                   13446:          		     my ($mapid,$resid)=split(/\./,$id);
                   13447:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13448:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13449: 						             $resid,$thisfn);
1.1424    raeburn  13450:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  13451:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  13452:                                  if ($checkforblock) {
1.1426    raeburn  13453:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  13454:                                      if (@blockers > 0) {
                   13455:                                          $syval = '';
                   13456:                                      } else {
1.1282    raeburn  13457:                                          $syval = $poss_syval;
                   13458:                                          $realpossible++;
                   13459:                                      }
                   13460:                                  } else {
                   13461:                                      $syval = $poss_syval;
                   13462:                                      $realpossible++;
                   13463:                                  }
1.1424    raeburn  13464:                                  if ($syval) {
                   13465:                                      if (ref($possibles) eq 'HASH') {
                   13466:                                          $possibles->{$syval} = 1;
                   13467:                                      }
                   13468:                                  }
1.1282    raeburn  13469:                              }
1.39      www      13470: 			 }
1.191     harris41 13471:                      }
1.39      www      13472: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13473:                  } else {
                   13474:                      $syval='';
1.37      www      13475:                  }
                   13476: 	      }
1.1282    raeburn  13477:               untie(%bighash);
1.481     raeburn  13478:            }
1.31      www      13479:         }
1.62      www      13480:         if ($syval) {
1.1427    raeburn  13481: 	    return $env{$cache_str}=$syval;
1.62      www      13482:         }
1.31      www      13483:     }
1.949     raeburn  13484:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13485:     return $env{$cache_str}='';
1.31      www      13486: }
                   13487: 
                   13488: # ---------------------------------------------------------- Return random seed
                   13489: 
1.32      www      13490: sub numval {
                   13491:     my $txt=shift;
                   13492:     $txt=~tr/A-J/0-9/;
                   13493:     $txt=~tr/a-j/0-9/;
                   13494:     $txt=~tr/K-T/0-9/;
                   13495:     $txt=~tr/k-t/0-9/;
                   13496:     $txt=~tr/U-Z/0-5/;
                   13497:     $txt=~tr/u-z/0-5/;
                   13498:     $txt=~s/\D//g;
1.564     albertel 13499:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13500:     return int($txt);
1.368     albertel 13501: }
                   13502: 
1.484     albertel 13503: sub numval2 {
                   13504:     my $txt=shift;
                   13505:     $txt=~tr/A-J/0-9/;
                   13506:     $txt=~tr/a-j/0-9/;
                   13507:     $txt=~tr/K-T/0-9/;
                   13508:     $txt=~tr/k-t/0-9/;
                   13509:     $txt=~tr/U-Z/0-5/;
                   13510:     $txt=~tr/u-z/0-5/;
                   13511:     $txt=~s/\D//g;
                   13512:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13513:     my $total;
                   13514:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13515:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13516:     return int($total);
                   13517: }
                   13518: 
1.575     albertel 13519: sub numval3 {
                   13520:     use integer;
                   13521:     my $txt=shift;
                   13522:     $txt=~tr/A-J/0-9/;
                   13523:     $txt=~tr/a-j/0-9/;
                   13524:     $txt=~tr/K-T/0-9/;
                   13525:     $txt=~tr/k-t/0-9/;
                   13526:     $txt=~tr/U-Z/0-5/;
                   13527:     $txt=~tr/u-z/0-5/;
                   13528:     $txt=~s/\D//g;
                   13529:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13530:     my $total;
                   13531:     foreach my $val (@txts) { $total+=$val; }
                   13532:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13533:     return $total;
                   13534: }
                   13535: 
1.675     albertel 13536: sub digest {
                   13537:     my ($data)=@_;
                   13538:     my $digest=&Digest::MD5::md5($data);
                   13539:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13540:     my ($e,$f);
                   13541:     {
                   13542:         use integer;
                   13543:         $e=($a+$b);
                   13544:         $f=($c+$d);
                   13545:         if ($_64bit) {
                   13546:             $e=(($e<<32)>>32);
                   13547:             $f=(($f<<32)>>32);
                   13548:         }
                   13549:     }
                   13550:     if (wantarray) {
                   13551: 	return ($e,$f);
                   13552:     } else {
                   13553: 	my $g;
                   13554: 	{
                   13555: 	    use integer;
                   13556: 	    $g=($e+$f);
                   13557: 	    if ($_64bit) {
                   13558: 		$g=(($g<<32)>>32);
                   13559: 	    }
                   13560: 	}
                   13561: 	return $g;
                   13562:     }
                   13563: }
                   13564: 
1.368     albertel 13565: sub latest_rnd_algorithm_id {
1.675     albertel 13566:     return '64bit5';
1.366     albertel 13567: }
1.32      www      13568: 
1.503     albertel 13569: sub get_rand_alg {
                   13570:     my ($courseid)=@_;
1.790     albertel 13571:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13572:     if ($courseid) {
1.620     albertel 13573: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13574:     }
                   13575:     return &latest_rnd_algorithm_id();
                   13576: }
                   13577: 
1.562     albertel 13578: sub validCODE {
                   13579:     my ($CODE)=@_;
                   13580:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13581:     return 0;
                   13582: }
                   13583: 
1.491     albertel 13584: sub getCODE {
1.620     albertel 13585:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13586:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13587: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13588: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13589: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13590:     }
                   13591:     return undef;
                   13592: }
1.1133    foxr     13593: #
                   13594: #  Determines the random seed for a specific context:
                   13595: #
                   13596: # parameters:
                   13597: #   symb      - in course context the symb for the seed.
                   13598: #   course_id - The course id of the form domain_coursenum.
                   13599: #   domain    - Domain for the user.
                   13600: #   course    - Course for the user.
                   13601: #   cenv      - environment of the course.
                   13602: #
                   13603: # NOTE:
                   13604: #   All parameters are picked out of the environment if missing
                   13605: #   or not defined.
                   13606: #   If a symb cannot be determined the current time is used instead.
                   13607: #
                   13608: #  For a given well defined symb, courside, domain, username,
                   13609: #  and course environment, the seed is reproducible.
                   13610: #
1.31      www      13611: sub rndseed {
1.1133    foxr     13612:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13613:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13614:     if (!defined($symb)) {
1.366     albertel 13615: 	unless ($symb=$wsymb) { return time; }
                   13616:     }
1.1146    foxr     13617:     if (!defined $courseid) { 
                   13618: 	$courseid=$wcourseid; 
                   13619:     }
                   13620:     if (!defined $domain) { $domain=$wdomain; }
                   13621:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13622: 
                   13623:     my $which;
                   13624:     if (defined($cenv->{'rndseed'})) {
                   13625: 	$which = $cenv->{'rndseed'};
                   13626:     } else {
                   13627: 	$which =&get_rand_alg($courseid);
                   13628:     }
1.491     albertel 13629:     if (defined(&getCODE())) {
1.1133    foxr     13630: 
1.675     albertel 13631: 	if ($which eq '64bit5') {
                   13632: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13633: 	} elsif ($which eq '64bit4') {
1.575     albertel 13634: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13635: 	} else {
                   13636: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13637: 	}
1.675     albertel 13638:     } elsif ($which eq '64bit5') {
                   13639: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13640:     } elsif ($which eq '64bit4') {
                   13641: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13642:     } elsif ($which eq '64bit3') {
                   13643: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13644:     } elsif ($which eq '64bit2') {
                   13645: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13646:     } elsif ($which eq '64bit') {
                   13647: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13648:     }
                   13649:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13650: }
                   13651: 
                   13652: sub rndseed_32bit {
                   13653:     my ($symb,$courseid,$domain,$username)=@_;
                   13654:     {
                   13655: 	use integer;
                   13656: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13657: 	my $symbseed=numval($symb) << 22;
                   13658: 	my $namechck=unpack("%32C*",$username) << 17;
                   13659: 	my $nameseed=numval($username) << 12;
                   13660: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13661: 	my $courseseed=unpack("%32C*",$courseid);
                   13662: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13663: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13664: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13665: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13666: 	return $num;
                   13667:     }
                   13668: }
                   13669: 
                   13670: sub rndseed_64bit {
                   13671:     my ($symb,$courseid,$domain,$username)=@_;
                   13672:     {
                   13673: 	use integer;
                   13674: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13675: 	my $symbseed=numval($symb) << 10;
                   13676: 	my $namechck=unpack("%32S*",$username);
                   13677: 	
                   13678: 	my $nameseed=numval($username) << 21;
                   13679: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13680: 	my $courseseed=unpack("%32S*",$courseid);
                   13681: 	
                   13682: 	my $num1=$symbchck+$symbseed+$namechck;
                   13683: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13684: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13685: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13686: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13687: 	return "$num1,$num2";
1.155     albertel 13688:     }
1.366     albertel 13689: }
                   13690: 
1.443     albertel 13691: sub rndseed_64bit2 {
                   13692:     my ($symb,$courseid,$domain,$username)=@_;
                   13693:     {
                   13694: 	use integer;
                   13695: 	# strings need to be an even # of cahracters long, it it is odd the
                   13696:         # last characters gets thrown away
                   13697: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13698: 	my $symbseed=numval($symb) << 10;
                   13699: 	my $namechck=unpack("%32S*",$username.' ');
                   13700: 	
                   13701: 	my $nameseed=numval($username) << 21;
1.501     albertel 13702: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13703: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13704: 	
                   13705: 	my $num1=$symbchck+$symbseed+$namechck;
                   13706: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13707: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13708: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13709: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13710: 	return "$num1,$num2";
                   13711:     }
                   13712: }
                   13713: 
                   13714: sub rndseed_64bit3 {
                   13715:     my ($symb,$courseid,$domain,$username)=@_;
                   13716:     {
                   13717: 	use integer;
                   13718: 	# strings need to be an even # of cahracters long, it it is odd the
                   13719:         # last characters gets thrown away
                   13720: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13721: 	my $symbseed=numval2($symb) << 10;
                   13722: 	my $namechck=unpack("%32S*",$username.' ');
                   13723: 	
                   13724: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13725: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13726: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13727: 	
                   13728: 	my $num1=$symbchck+$symbseed+$namechck;
                   13729: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13730: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13731: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13732: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13733: 	
1.503     albertel 13734: 	return "$num1:$num2";
1.443     albertel 13735:     }
                   13736: }
                   13737: 
1.575     albertel 13738: sub rndseed_64bit4 {
                   13739:     my ($symb,$courseid,$domain,$username)=@_;
                   13740:     {
                   13741: 	use integer;
                   13742: 	# strings need to be an even # of cahracters long, it it is odd the
                   13743:         # last characters gets thrown away
                   13744: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13745: 	my $symbseed=numval3($symb) << 10;
                   13746: 	my $namechck=unpack("%32S*",$username.' ');
                   13747: 	
                   13748: 	my $nameseed=numval3($username) << 21;
                   13749: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13750: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13751: 	
                   13752: 	my $num1=$symbchck+$symbseed+$namechck;
                   13753: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13754: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13755: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13756: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13757: 	
1.575     albertel 13758: 	return "$num1:$num2";
                   13759:     }
                   13760: }
                   13761: 
1.675     albertel 13762: sub rndseed_64bit5 {
                   13763:     my ($symb,$courseid,$domain,$username)=@_;
                   13764:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13765:     return "$num1:$num2";
                   13766: }
                   13767: 
1.366     albertel 13768: sub rndseed_CODE_64bit {
                   13769:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13770:     {
1.366     albertel 13771: 	use integer;
1.443     albertel 13772: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13773: 	my $symbseed=numval2($symb);
1.491     albertel 13774: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13775: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13776: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13777: 	my $num1=$symbseed+$CODEchck;
                   13778: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13779: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13780: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13781: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13782: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13783: 	return "$num1:$num2";
1.366     albertel 13784:     }
                   13785: }
                   13786: 
1.575     albertel 13787: sub rndseed_CODE_64bit4 {
                   13788:     my ($symb,$courseid,$domain,$username)=@_;
                   13789:     {
                   13790: 	use integer;
                   13791: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13792: 	my $symbseed=numval3($symb);
                   13793: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13794: 	my $CODEseed=numval3(&getCODE());
                   13795: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13796: 	my $num1=$symbseed+$CODEchck;
                   13797: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13798: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13799: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13800: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13801: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13802: 	return "$num1:$num2";
                   13803:     }
                   13804: }
                   13805: 
1.675     albertel 13806: sub rndseed_CODE_64bit5 {
                   13807:     my ($symb,$courseid,$domain,$username)=@_;
                   13808:     my $code = &getCODE();
                   13809:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13810:     return "$num1:$num2";
                   13811: }
                   13812: 
1.366     albertel 13813: sub setup_random_from_rndseed {
                   13814:     my ($rndseed)=@_;
1.503     albertel 13815:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13816:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13817:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13818:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13819:         } else {
                   13820:             &Math::Random::random_set_seed($num1,$num2);
                   13821:         }
1.366     albertel 13822:     } else {
                   13823: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13824:     }
1.36      albertel 13825: }
                   13826: 
1.474     albertel 13827: sub latest_receipt_algorithm_id {
1.835     albertel 13828:     return 'receipt3';
1.474     albertel 13829: }
                   13830: 
1.480     www      13831: sub recunique {
                   13832:     my $fucourseid=shift;
                   13833:     my $unique;
1.835     albertel 13834:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13835: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13836: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13837:     } else {
                   13838: 	$unique=$perlvar{'lonReceipt'};
                   13839:     }
                   13840:     return unpack("%32C*",$unique);
                   13841: }
                   13842: 
                   13843: sub recprefix {
                   13844:     my $fucourseid=shift;
                   13845:     my $prefix;
1.835     albertel 13846:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13847: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13848: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13849:     } else {
                   13850: 	$prefix=$perlvar{'lonHostID'};
                   13851:     }
                   13852:     return unpack("%32C*",$prefix);
                   13853: }
                   13854: 
1.76      www      13855: sub ireceipt {
1.474     albertel 13856:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13857: 
                   13858:     my $return =&recprefix($fucourseid).'-';
                   13859: 
                   13860:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13861: 	$env{'request.state'} eq 'construct') {
                   13862: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13863: 	return $return;
                   13864:     }
                   13865: 
1.76      www      13866:     my $cuname=unpack("%32C*",$funame);
                   13867:     my $cudom=unpack("%32C*",$fudom);
                   13868:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13869:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13870:     my $cunique=&recunique($fucourseid);
1.474     albertel 13871:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13872:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13873: 
1.790     albertel 13874: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13875: 			       
                   13876: 	$return.= ($cunique%$cuname+
                   13877: 		   $cunique%$cudom+
                   13878: 		   $cusymb%$cuname+
                   13879: 		   $cusymb%$cudom+
                   13880: 		   $cucourseid%$cuname+
                   13881: 		   $cucourseid%$cudom+
                   13882: 		   $cpart%$cuname+
                   13883: 		   $cpart%$cudom);
                   13884:     } else {
                   13885: 	$return.= ($cunique%$cuname+
                   13886: 		   $cunique%$cudom+
                   13887: 		   $cusymb%$cuname+
                   13888: 		   $cusymb%$cudom+
                   13889: 		   $cucourseid%$cuname+
                   13890: 		   $cucourseid%$cudom);
                   13891:     }
                   13892:     return $return;
1.76      www      13893: }
                   13894: 
                   13895: sub receipt {
1.474     albertel 13896:     my ($part)=@_;
1.790     albertel 13897:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13898:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13899: }
1.260     ng       13900: 
1.790     albertel 13901: sub whichuser {
                   13902:     my ($passedsymb)=@_;
                   13903:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13904:     if (defined($env{'form.grade_symb'})) {
                   13905: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13906: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13907: 	if (!$allowed &&
                   13908: 	    exists($env{'request.course.sec'}) &&
                   13909: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13910: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13911: 			      '/'.$env{'request.course.sec'});
                   13912: 	}
                   13913: 	if ($allowed) {
                   13914: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13915: 	    $courseid=$tmp_courseid;
                   13916: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13917: 	    ($name)=&get_env_multiple('form.grade_username');
                   13918: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13919: 	}
                   13920:     }
                   13921:     if (!$passedsymb) {
                   13922: 	$symb=&symbread();
                   13923:     } else {
                   13924: 	$symb=$passedsymb;
                   13925:     }
                   13926:     $courseid=$env{'request.course.id'};
                   13927:     $domain=$env{'user.domain'};
                   13928:     $name=$env{'user.name'};
                   13929:     if ($name eq 'public' && $domain eq 'public') {
                   13930: 	if (!defined($env{'form.username'})) {
                   13931: 	    $env{'form.username'}.=time.rand(10000000);
                   13932: 	}
                   13933: 	$name.=$env{'form.username'};
                   13934:     }
                   13935:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13936: 
                   13937: }
                   13938: 
1.36      albertel 13939: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13940: # returns either the contents of the file or 
                   13941: # -1 if the file doesn't exist
1.481     raeburn  13942: #
                   13943: # if the target is a file that was uploaded via DOCS, 
                   13944: # a check will be made to see if a current copy exists on the local server,
                   13945: # if it does this will be served, otherwise a copy will be retrieved from
                   13946: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13947: # the local server.   
1.472     albertel 13948: 
1.36      albertel 13949: sub getfile {
1.538     albertel 13950:     my ($file) = @_;
1.609     banghart 13951:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13952:     &repcopy($file);
                   13953:     return &readfile($file);
                   13954: }
                   13955: 
                   13956: sub repcopy_userfile {
                   13957:     my ($file)=@_;
1.1142    raeburn  13958:     my $londocroot = $perlvar{'lonDocRoot'};
                   13959:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13960:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13961:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13962: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13963:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13964:     if (-e "$file") {
1.828     www      13965: # we already have a local copy, check it out
1.538     albertel 13966: 	my @fileinfo = stat($file);
1.828     www      13967: 	my $rtncode;
                   13968: 	my $info;
1.538     albertel 13969: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13970: 	if ($lwpresp ne 'ok') {
1.828     www      13971: # there is no such file anymore, even though we had a local copy
1.482     albertel 13972: 	    if ($rtncode eq '404') {
1.538     albertel 13973: 		unlink($file);
1.482     albertel 13974: 	    }
                   13975: 	    return -1;
                   13976: 	}
                   13977: 	if ($info < $fileinfo[9]) {
1.828     www      13978: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13979: 	    return 'ok';
1.828     www      13980: 	} else {
                   13981: # the file is outdated, get rid of it
                   13982: 	    unlink($file);
1.482     albertel 13983: 	}
1.828     www      13984:     }
                   13985: # one way or the other, at this point, we don't have the file
                   13986: # construct the correct path for the file
                   13987:     my @parts = ($cdom,$cnum); 
                   13988:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13989: 	push @parts, split(/\//,$1);
                   13990:     }
                   13991:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13992:     foreach my $part (@parts) {
                   13993: 	$path .= '/'.$part;
                   13994: 	if (!-e $path) {
                   13995: 	    mkdir($path,0770);
1.482     albertel 13996: 	}
                   13997:     }
1.828     www      13998: # now the path exists for sure
                   13999: # get a user agent
                   14000:     my $transferfile=$file.'.in.transfer';
                   14001: # FIXME: this should flock
                   14002:     if (-e $transferfile) { return 'ok'; }
                   14003:     my $request;
                   14004:     $uri=~s/^\///;
1.980     raeburn  14005:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  14006:     my $hostname = &hostname($homeserver);
1.980     raeburn  14007:     my $protocol = $protocol{$homeserver};
                   14008:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14009:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  14010:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      14011: # did it work?
                   14012:     if ($response->is_error()) {
                   14013: 	unlink($transferfile);
                   14014: 	&logthis("Userfile repcopy failed for $uri");
                   14015: 	return -1;
                   14016:     }
                   14017: # worked, rename the transfer file
                   14018:     rename($transferfile,$file);
1.607     raeburn  14019:     return 'ok';
1.481     raeburn  14020: }
                   14021: 
1.517     albertel 14022: sub tokenwrapper {
                   14023:     my $uri=shift;
1.980     raeburn  14024:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14025:     $uri=~s|^/||;
1.620     albertel 14026:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14027:     my $token=$1;
1.552     albertel 14028:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14029:     if ($udom && $uname && $file) {
                   14030: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14031:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14032:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  14033:         my $hostname = &hostname($homeserver);
1.980     raeburn  14034:         my $protocol = $protocol{$homeserver};
                   14035:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14036:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14037:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14038:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14039:     } else {
                   14040:         return '/adm/notfound.html';
                   14041:     }
                   14042: }
                   14043: 
1.828     www      14044: # call with reqtype HEAD: get last modification time
                   14045: # call with reqtype GET: get the file contents
                   14046: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14047: #
1.481     raeburn  14048: sub getuploaded {
                   14049:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14050:     $uri=~s/^\///;
1.980     raeburn  14051:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  14052:     my $hostname = &hostname($homeserver);
1.980     raeburn  14053:     my $protocol = $protocol{$homeserver};
                   14054:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14055:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14056:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  14057:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  14058:     $$rtncode = $response->code;
1.482     albertel 14059:     if (! $response->is_success()) {
                   14060: 	return 'failed';
                   14061:     }      
                   14062:     if ($reqtype eq 'HEAD') {
1.486     www      14063: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14064:     } elsif ($reqtype eq 'GET') {
                   14065: 	$$info = $response->content;
1.472     albertel 14066:     }
1.482     albertel 14067:     return 'ok';
1.36      albertel 14068: }
                   14069: 
1.481     raeburn  14070: sub readfile {
                   14071:     my $file = shift;
                   14072:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14073:     my $fh;
1.1359    raeburn  14074:     open($fh,"<",$file);
1.481     raeburn  14075:     my $a='';
1.800     albertel 14076:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14077:     return $a;
                   14078: }
                   14079: 
1.36      albertel 14080: sub filelocation {
1.590     banghart 14081:     my ($dir,$file) = @_;
                   14082:     my $location;
                   14083:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14084: 
                   14085:     if ($file =~ m-^/adm/-) {
                   14086: 	$file=~s-^/adm/wrapper/-/-;
                   14087: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14088:     }
1.882     albertel 14089: 
1.1139    www      14090:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14091:         $location = $file;
1.609     banghart 14092:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14093:         my ($udom,$uname,$filename)=
1.811     albertel 14094:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14095:         my $home=&homeserver($uname,$udom);
                   14096:         my $is_me=0;
                   14097:         my @ids=&current_machine_ids();
                   14098:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14099:         if ($is_me) {
1.1117    foxr     14100:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14101:         } else {
                   14102:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14103:   	      $udom.'/'.$uname.'/'.$filename;
                   14104:         }
1.882     albertel 14105:     } elsif ($file =~ m-^/adm/-) {
                   14106: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14107:     } else {
                   14108:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14109:         $file=~s:^/(res|priv)/:/:;
                   14110:         my $space=$1;
1.590     banghart 14111:         if ( !( $file =~ m:^/:) ) {
                   14112:             $location = $dir. '/'.$file;
                   14113:         } else {
1.1142    raeburn  14114:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14115:         }
1.59      albertel 14116:     }
1.590     banghart 14117:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14118:     while ($location=~m{/\.\./}) {
                   14119: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14120: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14121: 	} else {
                   14122: 	    $location=~ s{/\.\./}{/}g;
                   14123: 	}
                   14124:     } #remove dir/..
1.590     banghart 14125:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14126:     return $location;
1.46      www      14127: }
1.36      albertel 14128: 
1.46      www      14129: sub hreflocation {
                   14130:     my ($dir,$file)=@_;
1.980     raeburn  14131:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14132: 	$file=filelocation($dir,$file);
1.700     albertel 14133:     } elsif ($file=~m-^/adm/-) {
                   14134: 	$file=~s-^/adm/wrapper/-/-;
                   14135: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14136:     }
                   14137:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14138: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14139:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14140: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14141: 	        {/uploaded/$1/$2/}x;
1.46      www      14142:     }
1.913     albertel 14143:     if ($file=~ m{^/userfiles/}) {
                   14144: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14145:     }
1.462     albertel 14146:     return $file;
1.465     albertel 14147: }
                   14148: 
1.1139    www      14149: 
                   14150: 
                   14151: 
                   14152: 
1.465     albertel 14153: sub current_machine_domains {
1.853     albertel 14154:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14155: }
                   14156: 
                   14157: sub machine_domains {
                   14158:     my ($hostname) = @_;
1.465     albertel 14159:     my @domains;
1.838     albertel 14160:     my %hostname = &all_hostnames();
1.465     albertel 14161:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14162: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14163: 	if ($hostname eq $name) {
1.844     albertel 14164: 	    push(@domains,&host_domain($id));
1.465     albertel 14165: 	}
                   14166:     }
                   14167:     return @domains;
                   14168: }
                   14169: 
                   14170: sub current_machine_ids {
1.853     albertel 14171:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14172: }
                   14173: 
                   14174: sub machine_ids {
                   14175:     my ($hostname) = @_;
                   14176:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14177:     my @ids;
1.888     albertel 14178:     my %name_to_host = &all_names();
1.889     albertel 14179:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14180: 	return @{ $name_to_host{$hostname} };
                   14181:     }
                   14182:     return;
1.31      www      14183: }
                   14184: 
1.824     raeburn  14185: sub additional_machine_domains {
                   14186:     my @domains;
1.1359    raeburn  14187:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  14188:     while( my $line = <$fh>) {
                   14189:         $line =~ s/\s//g;
                   14190:         push(@domains,$line);
                   14191:     }
                   14192:     return @domains;
                   14193: }
                   14194: 
                   14195: sub default_login_domain {
                   14196:     my $domain = $perlvar{'lonDefDomain'};
                   14197:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14198:     foreach my $posdom (&current_machine_domains(),
                   14199:                         &additional_machine_domains()) {
                   14200:         if (lc($posdom) eq lc($testdomain)) {
                   14201:             $domain=$posdom;
                   14202:             last;
                   14203:         }
                   14204:     }
                   14205:     return $domain;
                   14206: }
                   14207: 
1.1414    raeburn  14208: sub shared_institution {
                   14209:     my ($dom) = @_;
                   14210:     my $same_intdom;
                   14211:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   14212:     if ($hostintdom ne '') {
                   14213:         my %iphost = &get_iphost();
                   14214:         my $primary_id = &domain($dom,'primary');
                   14215:         my $primary_ip = &get_host_ip($primary_id);
                   14216:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14217:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14218:                 my $intdom = &internet_dom($id);
                   14219:                 if ($intdom eq $hostintdom) {
                   14220:                     $same_intdom = 1;
                   14221:                     last;
                   14222:                 }
                   14223:             }
                   14224:         }
                   14225:     }
                   14226:     return $same_intdom;
                   14227: }
                   14228: 
1.1398    raeburn  14229: sub uses_sts {
                   14230:     my ($ignore_cache) = @_;
                   14231:     my $lonhost = $perlvar{'lonHostID'};
                   14232:     my $hostname = &hostname($lonhost);
                   14233:     my $sts_on;
                   14234:     if ($protocol{$lonhost} eq 'https') {
                   14235:         my $cachetime = 12*3600;
                   14236:         if (!$ignore_cache) {
                   14237:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14238:             if (defined($cached)) {
                   14239:                 return $sts_on;
                   14240:             }
                   14241:         }
                   14242:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14243:         my $request=new HTTP::Request('HEAD',$url);
                   14244:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   14245:         if ($response->is_success) {
                   14246:             my $has_sts = $response->header('Strict-Transport-Security');
                   14247:             if ($has_sts eq '') {
                   14248:                 $sts_on = 0;
                   14249:             } else {
                   14250:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14251:                     my $maxage = $1;
                   14252:                     if ($maxage) {
                   14253:                         $sts_on = 1;
                   14254:                     } else {
                   14255:                         $sts_on = 0;
                   14256:                     }
                   14257:                 } else {
                   14258:                     $sts_on = 0;
                   14259:                 }
                   14260:             }
                   14261:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14262:         }
                   14263:     }
                   14264:     return;
                   14265: }
                   14266: 
1.31      www      14267: # ------------------------------------------------------------- Declutters URLs
                   14268: 
                   14269: sub declutter {
                   14270:     my $thisfn=shift;
1.569     albertel 14271:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  14272:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14273:         $thisfn=~s{^/home/httpd/html}{};
                   14274:     }
1.31      www      14275:     $thisfn=~s/^\///;
1.697     albertel 14276:     $thisfn=~s|^adm/wrapper/||;
                   14277:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14278:     $thisfn=~s/^res\///;
1.1172    bisitz   14279:     $thisfn=~s/^priv\///;
1.1032    raeburn  14280:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14281:         $thisfn=~s/\?.+$//;
                   14282:     }
1.268     www      14283:     return $thisfn;
                   14284: }
                   14285: 
                   14286: # ------------------------------------------------------------- Clutter up URLs
                   14287: 
                   14288: sub clutter {
                   14289:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14290:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14291: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14292:        $thisfn='/res'.$thisfn; 
                   14293:     }
1.1031    raeburn  14294:     if ($thisfn !~m|^/adm|) {
                   14295: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14296: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14297: 	} else {
                   14298: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14299: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14300: 	    if ($embstyle eq 'ssi'
                   14301: 		|| ($embstyle eq 'hdn')
                   14302: 		|| ($embstyle eq 'rat')
                   14303: 		|| ($embstyle eq 'prv')
                   14304: 		|| ($embstyle eq 'ign')) {
                   14305: 		#do nothing with these
                   14306: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14307: 		|| ($embstyle eq 'emb')
                   14308: 		|| ($embstyle eq 'wrp')) {
                   14309: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14310: 	    } elsif ($embstyle eq 'unk'
                   14311: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14312: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14313: 	    } else {
1.718     www      14314: #		&logthis("Got a blank emb style");
1.695     albertel 14315: 	    }
1.694     albertel 14316: 	}
1.1343    raeburn  14317:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14318:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14319:     }
1.31      www      14320:     return $thisfn;
1.12      www      14321: }
                   14322: 
1.787     albertel 14323: sub clutter_with_no_wrapper {
                   14324:     my $uri = &clutter(shift);
                   14325:     if ($uri =~ m-^/adm/-) {
                   14326: 	$uri =~ s-^/adm/wrapper/-/-;
                   14327: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14328:     }
                   14329:     return $uri;
                   14330: }
                   14331: 
1.557     albertel 14332: sub freeze_escape {
                   14333:     my ($value)=@_;
                   14334:     if (ref($value)) {
                   14335: 	$value=&nfreeze($value);
                   14336: 	return '__FROZEN__'.&escape($value);
                   14337:     }
                   14338:     return &escape($value);
                   14339: }
                   14340: 
1.11      www      14341: 
1.557     albertel 14342: sub thaw_unescape {
                   14343:     my ($value)=@_;
                   14344:     if ($value =~ /^__FROZEN__/) {
                   14345: 	substr($value,0,10,undef);
                   14346: 	$value=&unescape($value);
                   14347: 	return &thaw($value);
                   14348:     }
                   14349:     return &unescape($value);
                   14350: }
                   14351: 
1.436     albertel 14352: sub correct_line_ends {
                   14353:     my ($result)=@_;
                   14354:     $$result =~s/\r\n/\n/mg;
                   14355:     $$result =~s/\r/\n/mg;
1.415     albertel 14356: }
1.1       albertel 14357: # ================================================================ Main Program
                   14358: 
1.184     www      14359: sub goodbye {
1.204     albertel 14360:    &logthis("Starting Shut down");
1.443     albertel 14361: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14362:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14363: #converted
1.599     albertel 14364: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14365:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14366: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14367: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14368: #1.1 only
1.870     albertel 14369: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14370: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14371: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14372: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14373:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14374:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14375:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14376:    &flushcourselogs();
                   14377:    &logthis("Shutting down");
                   14378: }
                   14379: 
1.852     albertel 14380: sub get_dns {
1.1210    raeburn  14381:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14382:     if (!$ignore_cache) {
                   14383: 	my ($content,$cached)=
                   14384: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14385: 	if ($cached) {
1.1210    raeburn  14386: 	    &$func($content,$hashref);
1.869     albertel 14387: 	    return;
                   14388: 	}
                   14389:     }
                   14390: 
                   14391:     my %alldns;
1.1379    raeburn  14392:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14393:         foreach my $dns (<$config>) {
                   14394: 	    next if ($dns !~ /^\^(\S*)/x);
                   14395:             my $line = $1;
                   14396:             my ($host,$protocol) = split(/:/,$line);
                   14397:             if ($protocol ne 'https') {
                   14398:                 $protocol = 'http';
                   14399:             }
                   14400: 	    $alldns{$host} = $protocol;
1.979     raeburn  14401:         }
1.1379    raeburn  14402:         close($config);
1.869     albertel 14403:     }
                   14404:     while (%alldns) {
1.1263    raeburn  14405: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  14406: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  14407:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  14408:         delete($alldns{$dns});
1.852     albertel 14409: 	next if ($response->is_error());
1.1379    raeburn  14410:         if ($url eq '/adm/dns/loncapaCRL') {
                   14411:             return &$func($response);
                   14412:         } else {
                   14413: 	    my @content = split("\n",$response->content);
                   14414: 	    unless ($nocache) {
                   14415: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   14416: 	    }
                   14417: 	    &$func(\@content,$hashref);
                   14418:             return;
                   14419:         }
                   14420:     }
                   14421:     my $which = (split('/',$url,4))[3];
                   14422:     if ($which eq 'loncapaCRL') {
                   14423:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   14424:         if (-e $diskfile) {
                   14425:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   14426:         } else {
                   14427:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   14428:         }
                   14429:     } else {
                   14430:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   14431:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14432:             my @content = <$config>;
                   14433:             close($config);
                   14434:             &$func(\@content,$hashref);
                   14435:         }
1.852     albertel 14436:     }
1.1210    raeburn  14437:     return;
                   14438: }
                   14439: 
                   14440: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  14441: sub parse_dns_checksums_tab {
1.1210    raeburn  14442:     my ($lines,$hashref) = @_;
1.1264    raeburn  14443:     my $lonhost = $perlvar{'lonHostID'};
                   14444:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  14445:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  14446:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14447:     my $webconfdir = '/etc/httpd/conf';
                   14448:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14449:         $webconfdir = '/etc/apache2';
                   14450:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14451:         if ($1 >= 10) {
                   14452:             $webconfdir = '/etc/apache2';
                   14453:         }
                   14454:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14455:         if ($1 >= 10.0) {
                   14456:             $webconfdir = '/etc/apache2';
                   14457:         }
                   14458:     }
1.1210    raeburn  14459:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14460:     my (%chksum,%revnum);
                   14461:     if (ref($lines) eq 'ARRAY') {
                   14462:         chomp(@{$lines});
1.1238    raeburn  14463:         my $version = shift(@{$lines});
                   14464:         if ($version eq $release) {  
1.1210    raeburn  14465:             foreach my $line (@{$lines}) {
1.1238    raeburn  14466:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  14467:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14468:                     if ($webconfdir eq '/etc/apache2') {
                   14469:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14470:                     }
                   14471:                 }
1.1238    raeburn  14472:                 $chksum{$file} = $shasum;
                   14473:                 $revnum{$file} = $version;
1.1210    raeburn  14474:             }
                   14475:             if (ref($hashref) eq 'HASH') {
                   14476:                 %{$hashref} = (
                   14477:                                 sums     => \%chksum,
                   14478:                                 versions => \%revnum,
                   14479:                               );
                   14480:             }
                   14481:         }
                   14482:     }
1.869     albertel 14483:     return;
1.852     albertel 14484: }
1.1210    raeburn  14485: 
                   14486: sub fetch_dns_checksums {
1.1238    raeburn  14487:     my %checksums;
                   14488:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  14489:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  14490:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14491:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  14492:              \%checksums);
1.1210    raeburn  14493:     return \%checksums;
                   14494: }
                   14495: 
1.1379    raeburn  14496: sub fetch_crl_pemfile {
                   14497:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   14498: }
                   14499: 
                   14500: sub save_crl_pem {
                   14501:     my ($response) = @_;
1.1380    raeburn  14502:     my ($msg,$hadchanges);
1.1379    raeburn  14503:     if (ref($response)) {
                   14504:         my $now = time;
                   14505:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   14506:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   14507:         if (open(my $fh,'>',"$tmpcrl")) {
                   14508:             print $fh $response->content;
                   14509:             close($fh);
                   14510:             if (-e $lonca) {
                   14511:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   14512:                     my $check = <PIPE>;
                   14513:                     close(PIPE);
                   14514:                     chomp($check);
                   14515:                     if ($check eq 'verify OK') {
                   14516:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  14517:                         my $backup;
1.1379    raeburn  14518:                         if (-e $dest) {
1.1380    raeburn  14519:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   14520:                                 $backup = 'ok';
                   14521:                             }
1.1379    raeburn  14522:                         }
                   14523:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   14524:                             $msg = 'ok';
1.1380    raeburn  14525:                             if ($backup) {
                   14526:                                 my (%oldnums,%newnums);
                   14527:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   14528:                                     while (<PIPE>) {
                   14529:                                         $oldnums{(split(/:/))[1]} = 1;
                   14530:                                     }
                   14531:                                     close(PIPE);
                   14532:                                 }
                   14533:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   14534:                                     while(<PIPE>) {
                   14535:                                         $newnums{(split(/:/))[1]} = 1;
                   14536:                                     }
                   14537:                                     close(PIPE);
                   14538:                                 }
                   14539:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   14540:                                     unless (exists($oldnums{$key})) {
                   14541:                                         $hadchanges = 1;
                   14542:                                         last;
                   14543:                                     }
                   14544:                                 }
                   14545:                                 unless ($hadchanges) {
                   14546:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   14547:                                         unless (exists($newnums{$key})) {
                   14548:                                             $hadchanges = 1;
                   14549:                                             last;
                   14550:                                         }
                   14551:                                     }
                   14552:                                 }
                   14553:                             }
1.1379    raeburn  14554:                         }
                   14555:                     } else {
                   14556:                         unlink($tmpcrl);
                   14557:                     }
                   14558:                 } else {
                   14559:                     unlink($tmpcrl);
                   14560:                 }
                   14561:             } else {
                   14562:                 unlink($tmpcrl);
                   14563:             }
                   14564:         }
                   14565:     }
1.1380    raeburn  14566:     return ($msg,$hadchanges);
1.1379    raeburn  14567: }
                   14568: 
1.327     albertel 14569: # ------------------------------------------------------------ Read domain file
                   14570: {
1.852     albertel 14571:     my $loaded;
1.846     albertel 14572:     my %domain;
                   14573: 
1.852     albertel 14574:     sub parse_domain_tab {
                   14575: 	my ($lines) = @_;
                   14576: 	foreach my $line (@$lines) {
                   14577: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14578: 
1.846     albertel 14579: 	    chomp($line);
1.852     albertel 14580: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14581: 	    my %this_domain;
                   14582: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14583: 			       'lang_def', 'city', 'longi', 'lati',
                   14584: 			       'primary') {
                   14585: 		$this_domain{$field} = shift(@elements);
                   14586: 	    }
                   14587: 	    $domain{$name} = \%this_domain;
1.852     albertel 14588: 	}
                   14589:     }
1.864     albertel 14590: 
                   14591:     sub reset_domain_info {
                   14592: 	undef($loaded);
                   14593: 	undef(%domain);
                   14594:     }
                   14595: 
1.852     albertel 14596:     sub load_domain_tab {
1.1293    raeburn  14597: 	my ($ignore_cache,$nocache) = @_;
                   14598: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14599: 	my $fh;
1.1359    raeburn  14600: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14601: 	    my @lines = <$fh>;
                   14602: 	    &parse_domain_tab(\@lines);
1.448     albertel 14603: 	}
1.852     albertel 14604: 	close($fh);
                   14605: 	$loaded = 1;
1.327     albertel 14606:     }
1.846     albertel 14607: 
                   14608:     sub domain {
1.852     albertel 14609: 	&load_domain_tab() if (!$loaded);
                   14610: 
1.846     albertel 14611: 	my ($name,$what) = @_;
                   14612: 	return if ( !exists($domain{$name}) );
                   14613: 
                   14614: 	if (!$what) {
                   14615: 	    return $domain{$name}{'description'};
                   14616: 	}
                   14617: 	return $domain{$name}{$what};
                   14618:     }
1.974     raeburn  14619: 
                   14620:     sub domain_info {
                   14621:         &load_domain_tab() if (!$loaded);
                   14622:         return %domain;
                   14623:     }
                   14624: 
1.327     albertel 14625: }
                   14626: 
                   14627: 
1.1       albertel 14628: # ------------------------------------------------------------- Read hosts file
                   14629: {
1.838     albertel 14630:     my %hostname;
1.844     albertel 14631:     my %hostdom;
1.845     albertel 14632:     my %libserv;
1.852     albertel 14633:     my $loaded;
1.888     albertel 14634:     my %name_to_host;
1.1074    raeburn  14635:     my %internetdom;
1.1107    raeburn  14636:     my %LC_dns_serv;
1.852     albertel 14637: 
                   14638:     sub parse_hosts_tab {
                   14639: 	my ($file) = @_;
                   14640: 	foreach my $configline (@$file) {
                   14641: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14642:             chomp($configline);
                   14643: 	    if ($configline =~ /^\^/) {
                   14644:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14645:                     $LC_dns_serv{$1} = 1;
                   14646:                 }
                   14647:                 next;
                   14648:             }
1.1074    raeburn  14649: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14650: 	    $name=~s/\s//g;
                   14651: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  14652:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14653:                     my $curr = $hostname{$id};
                   14654:                     my $skip;
                   14655:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14656:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14657:                             $skip = 1;
                   14658:                         } else {
                   14659:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14660:                         }
                   14661:                     }
                   14662:                     unless ($skip) {
                   14663:                         push(@{$name_to_host{$name}},$id);
                   14664:                     }
                   14665:                 } else {
                   14666:                     push(@{$name_to_host{$name}},$id);
                   14667:                 }
1.852     albertel 14668: 		$hostname{$id}=$name;
                   14669: 		$hostdom{$id}=$domain;
                   14670: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14671:                 if (defined($protocol)) {
                   14672:                     if ($protocol eq 'https') {
                   14673:                         $protocol{$id} = $protocol;
                   14674:                     } else {
                   14675:                         $protocol{$id} = 'http'; 
                   14676:                     }
1.968     raeburn  14677:                 } else {
1.969     raeburn  14678:                     $protocol{$id} = 'http';
1.968     raeburn  14679:                 }
1.1074    raeburn  14680:                 if (defined($intdom)) {
                   14681:                     $internetdom{$id} = $intdom;
                   14682:                 }
1.852     albertel 14683: 	    }
                   14684: 	}
                   14685:     }
1.864     albertel 14686:     
                   14687:     sub reset_hosts_info {
1.897     albertel 14688: 	&purge_remembered();
1.864     albertel 14689: 	&reset_domain_info();
                   14690: 	&reset_hosts_ip_info();
1.1339    raeburn  14691:         undef(%internetdom);
1.892     albertel 14692: 	undef(%name_to_host);
1.864     albertel 14693: 	undef(%hostname);
                   14694: 	undef(%hostdom);
                   14695: 	undef(%libserv);
                   14696: 	undef($loaded);
                   14697:     }
1.1       albertel 14698: 
1.852     albertel 14699:     sub load_hosts_tab {
1.1293    raeburn  14700: 	my ($ignore_cache,$nocache) = @_;
                   14701: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  14702: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14703: 	my @config = <$config>;
                   14704: 	&parse_hosts_tab(\@config);
                   14705: 	close($config);
                   14706: 	$loaded=1;
1.1       albertel 14707:     }
1.852     albertel 14708: 
1.838     albertel 14709:     sub hostname {
1.852     albertel 14710: 	&load_hosts_tab() if (!$loaded);
                   14711: 
1.838     albertel 14712: 	my ($lonid) = @_;
                   14713: 	return $hostname{$lonid};
                   14714:     }
1.845     albertel 14715: 
1.838     albertel 14716:     sub all_hostnames {
1.852     albertel 14717: 	&load_hosts_tab() if (!$loaded);
                   14718: 
1.838     albertel 14719: 	return %hostname;
                   14720:     }
1.845     albertel 14721: 
1.888     albertel 14722:     sub all_names {
1.1293    raeburn  14723:         my ($ignore_cache,$nocache) = @_;
                   14724: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14725: 
                   14726: 	return %name_to_host;
                   14727:     }
                   14728: 
1.974     raeburn  14729:     sub all_host_domain {
                   14730:         &load_hosts_tab() if (!$loaded);
                   14731:         return %hostdom;
                   14732:     }
                   14733: 
1.1339    raeburn  14734:     sub all_host_intdom {
                   14735:         &load_hosts_tab() if (!$loaded);
                   14736:         return %internetdom;
                   14737:     }
                   14738: 
1.845     albertel 14739:     sub is_library {
1.852     albertel 14740: 	&load_hosts_tab() if (!$loaded);
                   14741: 
1.845     albertel 14742: 	return exists($libserv{$_[0]});
                   14743:     }
                   14744: 
                   14745:     sub all_library {
1.852     albertel 14746: 	&load_hosts_tab() if (!$loaded);
                   14747: 
1.845     albertel 14748: 	return %libserv;
                   14749:     }
                   14750: 
1.1062    droeschl 14751:     sub unique_library {
                   14752: 	#2x reverse removes all hostnames that appear more than once
                   14753:         my %unique = reverse &all_library();
                   14754:         return reverse %unique;
                   14755:     }
                   14756: 
1.841     albertel 14757:     sub get_servers {
1.852     albertel 14758: 	&load_hosts_tab() if (!$loaded);
                   14759: 
1.841     albertel 14760: 	my ($domain,$type) = @_;
                   14761: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14762: 	                                          : %hostname;
                   14763: 	my %result;
1.842     albertel 14764: 	if (ref($domain) eq 'ARRAY') {
                   14765: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14766: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14767: 		    $result{$host} = $hostname;
                   14768: 		}
                   14769: 	    }
                   14770: 	} else {
                   14771: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14772: 		if ($hostdom{$host} eq $domain) {
                   14773: 		    $result{$host} = $hostname;
                   14774: 		}
1.841     albertel 14775: 	    }
                   14776: 	}
                   14777: 	return %result;
                   14778:     }
1.845     albertel 14779: 
1.1062    droeschl 14780:     sub get_unique_servers {
                   14781:         my %unique = reverse &get_servers(@_);
                   14782: 	return reverse %unique;
                   14783:     }
                   14784: 
1.844     albertel 14785:     sub host_domain {
1.852     albertel 14786: 	&load_hosts_tab() if (!$loaded);
                   14787: 
1.844     albertel 14788: 	my ($lonid) = @_;
                   14789: 	return $hostdom{$lonid};
                   14790:     }
                   14791: 
1.841     albertel 14792:     sub all_domains {
1.852     albertel 14793: 	&load_hosts_tab() if (!$loaded);
                   14794: 
1.841     albertel 14795: 	my %seen;
                   14796: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14797: 	return @uniq;
                   14798:     }
1.1074    raeburn  14799: 
                   14800:     sub internet_dom {
                   14801:         &load_hosts_tab() if (!$loaded);
                   14802: 
                   14803:         my ($lonid) = @_;
                   14804:         return $internetdom{$lonid};
                   14805:     }
1.1107    raeburn  14806: 
                   14807:     sub is_LC_dns {
                   14808:         &load_hosts_tab() if (!$loaded);
                   14809: 
                   14810:         my ($hostname) = @_;
                   14811:         return exists($LC_dns_serv{$hostname});
                   14812:     }
                   14813: 
1.1       albertel 14814: }
                   14815: 
1.847     albertel 14816: { 
                   14817:     my %iphost;
1.856     albertel 14818:     my %name_to_ip;
                   14819:     my %lonid_to_ip;
1.869     albertel 14820: 
1.847     albertel 14821:     sub get_hosts_from_ip {
                   14822: 	my ($ip) = @_;
                   14823: 	my %iphosts = &get_iphost();
                   14824: 	if (ref($iphosts{$ip})) {
                   14825: 	    return @{$iphosts{$ip}};
                   14826: 	}
                   14827: 	return;
1.839     albertel 14828:     }
1.864     albertel 14829:     
                   14830:     sub reset_hosts_ip_info {
                   14831: 	undef(%iphost);
                   14832: 	undef(%name_to_ip);
                   14833: 	undef(%lonid_to_ip);
                   14834:     }
1.856     albertel 14835: 
                   14836:     sub get_host_ip {
                   14837: 	my ($lonid) = @_;
                   14838: 	if (exists($lonid_to_ip{$lonid})) {
                   14839: 	    return $lonid_to_ip{$lonid};
                   14840: 	}
                   14841: 	my $name=&hostname($lonid);
                   14842:    	my $ip = gethostbyname($name);
                   14843: 	return if (!$ip || length($ip) ne 4);
                   14844: 	$ip=inet_ntoa($ip);
                   14845: 	$name_to_ip{$name}   = $ip;
                   14846: 	$lonid_to_ip{$lonid} = $ip;
                   14847: 	return $ip;
                   14848:     }
1.847     albertel 14849:     
                   14850:     sub get_iphost {
1.1293    raeburn  14851: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14852: 
1.869     albertel 14853: 	if (!$ignore_cache) {
                   14854: 	    if (%iphost) {
                   14855: 		return %iphost;
                   14856: 	    }
                   14857: 	    my ($ip_info,$cached)=
                   14858: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14859: 	    if ($cached) {
                   14860: 		%iphost      = %{$ip_info->[0]};
                   14861: 		%name_to_ip  = %{$ip_info->[1]};
                   14862: 		%lonid_to_ip = %{$ip_info->[2]};
                   14863: 		return %iphost;
                   14864: 	    }
                   14865: 	}
1.894     albertel 14866: 
                   14867: 	# get yesterday's info for fallback
                   14868: 	my %old_name_to_ip;
                   14869: 	my ($ip_info,$cached)=
                   14870: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14871: 	if ($cached) {
                   14872: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14873: 	}
                   14874: 
1.1293    raeburn  14875: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14876: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14877: 	    my $ip;
                   14878: 	    if (!exists($name_to_ip{$name})) {
                   14879: 		$ip = gethostbyname($name);
                   14880: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14881: 		    if (defined($old_name_to_ip{$name})) {
                   14882: 			$ip = $old_name_to_ip{$name};
                   14883: 			&logthis("Can't find $name defaulting to old $ip");
                   14884: 		    } else {
                   14885: 			&logthis("Name $name no IP found");
                   14886: 			next;
                   14887: 		    }
                   14888: 		} else {
                   14889: 		    $ip=inet_ntoa($ip);
1.847     albertel 14890: 		}
                   14891: 		$name_to_ip{$name} = $ip;
                   14892: 	    } else {
                   14893: 		$ip = $name_to_ip{$name};
1.653     albertel 14894: 	    }
1.888     albertel 14895: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14896: 		$lonid_to_ip{$id} = $ip;
                   14897: 	    }
                   14898: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14899: 	}
1.1293    raeburn  14900:         unless ($nocache) {
                   14901: 	    &do_cache_new('iphost','iphost',
                   14902: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14903: 		          48*60*60);
                   14904:         }
1.869     albertel 14905: 
1.847     albertel 14906: 	return %iphost;
1.598     albertel 14907:     }
                   14908: 
1.992     raeburn  14909:     #
                   14910:     #  Given a DNS returns the loncapa host name for that DNS 
                   14911:     # 
                   14912:     sub host_from_dns {
                   14913:         my ($dns) = @_;
                   14914:         my @hosts;
                   14915:         my $ip;
                   14916: 
1.993     raeburn  14917:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14918:             $ip = $name_to_ip{$dns};
                   14919:         }
                   14920:         if (!$ip) {
                   14921:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14922:             if (length($ip) == 4) { 
                   14923: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14924:             }
                   14925:         }
                   14926:         if ($ip) {
                   14927: 	    @hosts = get_hosts_from_ip($ip);
                   14928: 	    return $hosts[0];
                   14929:         }
                   14930:         return undef;
1.986     foxr     14931:     }
1.992     raeburn  14932: 
1.1074    raeburn  14933:     sub get_internet_names {
                   14934:         my ($lonid) = @_;
                   14935:         return if ($lonid eq '');
                   14936:         my ($idnref,$cached)=
                   14937:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14938:         if ($cached) {
                   14939:             return $idnref;
                   14940:         }
                   14941:         my $ip = &get_host_ip($lonid);
                   14942:         my @hosts = &get_hosts_from_ip($ip);
                   14943:         my %iphost = &get_iphost();
                   14944:         my (@idns,%seen);
                   14945:         foreach my $id (@hosts) {
                   14946:             my $dom = &host_domain($id);
                   14947:             my $prim_id = &domain($dom,'primary');
                   14948:             my $prim_ip = &get_host_ip($prim_id);
                   14949:             next if ($seen{$prim_ip});
                   14950:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14951:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14952:                     my $intdom = &internet_dom($id);
                   14953:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14954:                         push(@idns,$intdom);
                   14955:                     }
                   14956:                 }
                   14957:             }
                   14958:             $seen{$prim_ip} = 1;
                   14959:         }
1.1219    raeburn  14960:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14961:     }
                   14962: 
1.986     foxr     14963: }
                   14964: 
1.1079    raeburn  14965: sub all_loncaparevs {
1.1249    raeburn  14966:     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  14967: }
                   14968: 
1.1227    raeburn  14969: # ---------------------------------------------------------- Read loncaparev table
                   14970: {
                   14971:     sub load_loncaparevs { 
                   14972:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14973:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14974:                 while (my $configline=<$config>) {
                   14975:                     chomp($configline);
                   14976:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14977:                     $loncaparevs{$hostid}=$loncaparev;
                   14978:                 }
                   14979:                 close($config);
                   14980:             }
                   14981:         }
                   14982:     }
                   14983: }
                   14984: 
                   14985: # ---------------------------------------------------------- Read serverhostID table
                   14986: {
                   14987:     sub load_serverhomeIDs {
                   14988:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14989:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14990:                 while (my $configline=<$config>) {
                   14991:                     chomp($configline);
                   14992:                     my ($name,$id)=split(/:/,$configline);
                   14993:                     $serverhomeIDs{$name}=$id;
                   14994:                 }
                   14995:                 close($config);
                   14996:             }
                   14997:         }
                   14998:     }
                   14999: }
                   15000: 
                   15001: 
1.862     albertel 15002: BEGIN {
                   15003: 
                   15004: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15005:     unless ($readit) {
                   15006: {
                   15007:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15008:     %perlvar = (%perlvar,%{$configvars});
                   15009: }
                   15010: 
                   15011: 
1.1       albertel 15012: # ------------------------------------------------------ Read spare server file
                   15013: {
1.1359    raeburn  15014:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15015: 
                   15016:     while (my $configline=<$config>) {
                   15017:        chomp($configline);
1.284     matthew  15018:        if ($configline) {
1.784     albertel 15019: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15020: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15021: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15022:        }
                   15023:     }
1.448     albertel 15024:     close($config);
1.1       albertel 15025: }
1.11      www      15026: # ------------------------------------------------------------ Read permissions
                   15027: {
1.1359    raeburn  15028:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15029: 
                   15030:     while (my $configline=<$config>) {
1.448     albertel 15031: 	chomp($configline);
                   15032: 	if ($configline) {
                   15033: 	    my ($role,$perm)=split(/ /,$configline);
                   15034: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15035: 	}
1.11      www      15036:     }
1.448     albertel 15037:     close($config);
1.11      www      15038: }
                   15039: 
                   15040: # -------------------------------------------- Read plain texts for permissions
                   15041: {
1.1359    raeburn  15042:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15043: 
                   15044:     while (my $configline=<$config>) {
1.448     albertel 15045: 	chomp($configline);
                   15046: 	if ($configline) {
1.742     raeburn  15047: 	    my ($short,@plain)=split(/:/,$configline);
                   15048:             %{$prp{$short}} = ();
                   15049: 	    if (@plain > 0) {
                   15050:                 $prp{$short}{'std'} = $plain[0];
                   15051:                 for (my $i=1; $i<@plain; $i++) {
                   15052:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15053:                 }
                   15054:             }
1.448     albertel 15055: 	}
1.135     www      15056:     }
1.448     albertel 15057:     close($config);
1.135     www      15058: }
                   15059: 
                   15060: # ---------------------------------------------------------- Read package table
                   15061: {
1.1359    raeburn  15062:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15063: 
                   15064:     while (my $configline=<$config>) {
1.483     albertel 15065: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15066: 	chomp($configline);
                   15067: 	my ($short,$plain)=split(/:/,$configline);
                   15068: 	my ($pack,$name)=split(/\&/,$short);
                   15069: 	if ($plain ne '') {
                   15070: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15071: 	    $packagetab{$short}=$plain; 
                   15072: 	}
1.11      www      15073:     }
1.448     albertel 15074:     close($config);
1.329     matthew  15075: }
                   15076: 
1.1073    raeburn  15077: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  15078: 
                   15079: &load_loncaparevs();
1.1073    raeburn  15080: 
1.1074    raeburn  15081: # ---------------------------------------------------------- Read serverhostID table
                   15082: 
1.1227    raeburn  15083: &load_serverhomeIDs();
                   15084: 
                   15085: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15086: {
                   15087:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15088:     if (-e $file) {
                   15089:         my $parser = HTML::LCParser->new($file);
                   15090:         while (my $token = $parser->get_token()) {
                   15091:             if ($token->[0] eq 'S') {
                   15092:                 my $item = $token->[1];
                   15093:                 my $name = $token->[2]{'name'};
                   15094:                 my $value = $token->[2]{'value'};
1.1285    raeburn  15095:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  15096:                 my $namematch = $token->[2]{'namematch'};
                   15097:                 if ($item eq 'parameter') {
                   15098:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   15099:                         my $release = $parser->get_text();
                   15100:                         $release =~ s/(^\s*|\s*$ )//gx;
                   15101:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   15102:                     }
                   15103:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  15104:                     my $release = $parser->get_text();
                   15105:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  15106:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  15107:                 }
                   15108:             }
                   15109:         }
                   15110:     }
1.1073    raeburn  15111: }
                   15112: 
1.1138    raeburn  15113: # ---------------------------------------------------------- Read managers table
                   15114: {
                   15115:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  15116:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15117:             while (my $configline=<$config>) {
                   15118:                 chomp($configline);
                   15119:                 next if ($configline =~ /^\#/);
                   15120:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15121:                     $managerstab{$configline} = 1;
                   15122:                 }
                   15123:             }
                   15124:             close($config);
                   15125:         }
                   15126:     }
                   15127: }
                   15128: 
1.329     matthew  15129: # ------------- set up temporary directory
                   15130: {
1.1117    foxr     15131:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15132: 
1.11      www      15133: }
                   15134: 
1.1405    raeburn  15135: # ------------- set default texengine (domain default overrides this)
                   15136: {
                   15137:     $deftex = LONCAPA::texengine();
                   15138: }
                   15139: 
1.1416    raeburn  15140: # ------------- set default minimum length for passwords for internal auth users
                   15141: {
                   15142:     $passwdmin = LONCAPA::passwd_min();
                   15143: }
                   15144: 
1.794     albertel 15145: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15146: 				'compress_threshold'=> 20_000,
                   15147:  			        });
1.185     www      15148: 
1.281     www      15149: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15150: $dumpcount=0;
1.958     www      15151: $locknum=0;
1.22      www      15152: 
1.163     harris41 15153: &logtouch();
1.672     albertel 15154: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15155: $readit=1;
1.564     albertel 15156:     {
                   15157: 	use integer;
                   15158: 	my $test=(2**32)+1;
1.568     albertel 15159: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15160: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15161:     }
1.195     www      15162: }
1.1       albertel 15163: }
1.179     www      15164: 
1.1       albertel 15165: 1;
1.191     harris41 15166: __END__
                   15167: 
1.243     albertel 15168: =pod
                   15169: 
1.191     harris41 15170: =head1 NAME
                   15171: 
1.243     albertel 15172: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15173: 
                   15174: =head1 SYNOPSIS
                   15175: 
1.243     albertel 15176: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15177: 
                   15178:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15179: 
1.243     albertel 15180: Common parameters:
                   15181: 
                   15182: =over 4
                   15183: 
                   15184: =item *
                   15185: 
                   15186: $uname : an internal username (if $cname expecting a course Id specifically)
                   15187: 
                   15188: =item *
                   15189: 
                   15190: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15191: 
                   15192: =item *
                   15193: 
                   15194: $symb : a resource instance identifier
                   15195: 
                   15196: =item *
                   15197: 
                   15198: $namespace : the name of a .db file that contains the data needed or
                   15199: being set.
                   15200: 
                   15201: =back
                   15202: 
1.394     bowersj2 15203: =head1 OVERVIEW
1.191     harris41 15204: 
1.394     bowersj2 15205: lonnet provides subroutines which interact with the
                   15206: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15207: about classes, users, and resources.
1.243     albertel 15208: 
                   15209: For many of these objects you can also use this to store data about
                   15210: them or modify them in various ways.
1.191     harris41 15211: 
1.394     bowersj2 15212: =head2 Symbs
1.191     harris41 15213: 
1.394     bowersj2 15214: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15215: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15216: map, the resource number of the resource in the map, and the URL of
                   15217: the resource itself. The latter is somewhat redundant, but might help
                   15218: if maps change.
                   15219: 
                   15220: An example is
                   15221: 
                   15222:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15223: 
                   15224: The respective map entry is
                   15225: 
                   15226:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15227:   title="Problem 2">
                   15228:  </resource>
                   15229: 
                   15230: Symbs are used by the random number generator, as well as to store and
                   15231: restore data specific to a certain instance of for example a problem.
                   15232: 
                   15233: =head2 Storing And Retrieving Data
                   15234: 
                   15235: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15236: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15237: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15238: is is the non-critical message twin of cstore. These functions are for
                   15239: handlers to store a perl hash to a user's permanent data space in an
                   15240: easy manner, and to retrieve it again on another call. It is expected
                   15241: that a handler would use this once at the beginning to retrieve data,
                   15242: and then again once at the end to send only the new data back.
                   15243: 
                   15244: The data is stored in the user's data directory on the user's
                   15245: homeserver under the ID of the course.
                   15246: 
                   15247: The hash that is returned by restore will have all of the previous
                   15248: value for all of the elements of the hash.
                   15249: 
                   15250: Example:
                   15251: 
                   15252:  #creating a hash
                   15253:  my %hash;
                   15254:  $hash{'foo'}='bar';
                   15255: 
                   15256:  #storing it
                   15257:  &Apache::lonnet::cstore(\%hash);
                   15258: 
                   15259:  #changing a value
                   15260:  $hash{'foo'}='notbar';
                   15261: 
                   15262:  #adding a new value
                   15263:  $hash{'bar'}='foo';
                   15264:  &Apache::lonnet::cstore(\%hash);
                   15265: 
                   15266:  #retrieving the hash
                   15267:  my %history=&Apache::lonnet::restore();
                   15268: 
                   15269:  #print the hash
                   15270:  foreach my $key (sort(keys(%history))) {
                   15271:    print("\%history{$key} = $history{$key}");
                   15272:  }
                   15273: 
                   15274: Will print out:
1.191     harris41 15275: 
1.394     bowersj2 15276:  %history{1:foo} = bar
                   15277:  %history{1:keys} = foo:timestamp
                   15278:  %history{1:timestamp} = 990455579
                   15279:  %history{2:bar} = foo
                   15280:  %history{2:foo} = notbar
                   15281:  %history{2:keys} = foo:bar:timestamp
                   15282:  %history{2:timestamp} = 990455580
                   15283:  %history{bar} = foo
                   15284:  %history{foo} = notbar
                   15285:  %history{timestamp} = 990455580
                   15286:  %history{version} = 2
                   15287: 
                   15288: Note that the special hash entries C<keys>, C<version> and
                   15289: C<timestamp> were added to the hash. C<version> will be equal to the
                   15290: total number of versions of the data that have been stored. The
                   15291: C<timestamp> attribute will be the UNIX time the hash was
                   15292: stored. C<keys> is available in every historical section to list which
                   15293: keys were added or changed at a specific historical revision of a
                   15294: hash.
                   15295: 
                   15296: B<Warning>: do not store the hash that restore returns directly. This
                   15297: will cause a mess since it will restore the historical keys as if the
                   15298: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15299: 
1.394     bowersj2 15300: Calling convention:
1.191     harris41 15301: 
1.1225    raeburn  15302:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  15303:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15304: 
1.394     bowersj2 15305: For more detailed information, see lonnet specific documentation.
1.191     harris41 15306: 
1.394     bowersj2 15307: =head1 RETURN MESSAGES
1.191     harris41 15308: 
1.394     bowersj2 15309: =over 4
1.191     harris41 15310: 
1.394     bowersj2 15311: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15312: 
1.394     bowersj2 15313: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15314: when the connection is brought back up
1.191     harris41 15315: 
1.394     bowersj2 15316: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15317: for later delivery
1.191     harris41 15318: 
1.967     bisitz   15319: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15320: 
1.394     bowersj2 15321: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15322: that was requested
1.191     harris41 15323: 
1.243     albertel 15324: =back
1.191     harris41 15325: 
1.243     albertel 15326: =head1 PUBLIC SUBROUTINES
1.191     harris41 15327: 
1.243     albertel 15328: =head2 Session Environment Functions
1.191     harris41 15329: 
1.243     albertel 15330: =over 4
1.191     harris41 15331: 
1.394     bowersj2 15332: =item * 
                   15333: X<appenv()>
1.949     raeburn  15334: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15335: the user envirnoment file, and will be restored for each access this
1.620     albertel 15336: user makes during this session, also modifies the %env for the current
1.949     raeburn  15337: process. Optional rolesarrayref - if defined contains a reference to an array
                   15338: of roles which are exempt from the restriction on modifying user.role entries 
                   15339: in the user's environment.db and in %env.    
1.191     harris41 15340: 
                   15341: =item *
1.394     bowersj2 15342: X<delenv()>
1.987     raeburn  15343: B<delenv($delthis,$regexp)>: removes all items from the session
                   15344: environment file that begin with $delthis. If the 
                   15345: optional second arg - $regexp - is true, $delthis is treated as a 
                   15346: regular expression, otherwise \Q$delthis\E is used. 
                   15347: The values are also deleted from the current processes %env.
1.191     harris41 15348: 
1.795     albertel 15349: =item * get_env_multiple($name) 
                   15350: 
                   15351: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15352: values may be defined and end up as an array ref.
                   15353: 
                   15354: returns an array of values
                   15355: 
1.243     albertel 15356: =back
                   15357: 
                   15358: =head2 User Information
1.191     harris41 15359: 
1.243     albertel 15360: =over 4
1.191     harris41 15361: 
                   15362: =item *
1.394     bowersj2 15363: X<queryauthenticate()>
                   15364: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15365: authentication scheme
                   15366: 
                   15367: =item *
1.394     bowersj2 15368: X<authenticate()>
1.1073    raeburn  15369: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15370: authenticate user from domain's lib servers (first use the current
                   15371: one). C<$upass> should be the users password.
1.1073    raeburn  15372: $checkdefauth is optional (value is 1 if a check should be made to
                   15373:    authenticate user using default authentication method, and allow
                   15374:    account creation if username does not have account in the domain).
                   15375: $clientcancheckhost is optional (value is 1 if checking whether the
                   15376:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15377: 
                   15378: =item *
1.394     bowersj2 15379: X<homeserver()>
                   15380: B<homeserver($uname,$udom)>: find the server which has
                   15381: the user's directory and files (there must be only one), this caches
                   15382: the answer, and also caches if there is a borken connection.
1.191     harris41 15383: 
                   15384: =item *
1.394     bowersj2 15385: X<idget()>
1.1300    raeburn  15386: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   15387: a list of student/employee IDs or clicker IDs
                   15388: (student/employee IDs are a unique resource in a domain, there must be 
                   15389: only 1 ID per username, and only 1 username per ID in a specific domain).
                   15390: clickerIDs are not necessarily unique, as students might share clickers.
                   15391: (returns hash: id=>name,id=>name)
1.191     harris41 15392: 
                   15393: =item *
1.394     bowersj2 15394: X<idrget()>
                   15395: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15396: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15397: 
                   15398: =item *
1.394     bowersj2 15399: X<idput()>
1.1300    raeburn  15400: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   15401: names and associated student/employee IDs or clicker IDs.
                   15402: 
                   15403: =item *
                   15404: X<iddel()>
                   15405: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   15406: student/employee ID or clicker ID username look-ups from domain.
                   15407: The homeserver ($uhome) and namespace ($namespace) are optional.
                   15408: If no $uhome is provided, it will be determined usig &homeserver()
                   15409: for each user.  If no $namespace is provided, the default is ids.
                   15410: 
                   15411: =item *
                   15412: X<updateclickers()>
                   15413: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   15414: clicker ID-to-username look-ups in clickers.db on library server.
                   15415: Permitted actions are add or del (i.e., add or delete). The 
                   15416: clickers.db contains clickerID as keys (escaped), and each corresponding
                   15417: value is an escaped comma-separated list of usernames (for whom the
                   15418: library server is the homeserver), who registered that particular ID.
                   15419: If $critical is true, the update will be sent via &critical, otherwise
                   15420: &reply() will be used.
1.191     harris41 15421: 
                   15422: =item *
1.394     bowersj2 15423: X<rolesinit()>
1.1169    droeschl 15424: B<rolesinit($udom,$username)>: get user privileges.
                   15425: returns user role, first access and timer interval hashes
1.243     albertel 15426: 
                   15427: =item *
1.1171    droeschl 15428: X<privileged()>
                   15429: B<privileged($username,$domain)>: returns a true if user has a
                   15430: privileged and active role (i.e. su or dc), false otherwise.
                   15431: 
                   15432: =item *
1.551     albertel 15433: X<getsection()>
                   15434: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15435: course $cname, return section name/number or '' for "not in course"
                   15436: and '-1' for "no section"
                   15437: 
                   15438: =item *
1.394     bowersj2 15439: X<userenvironment()>
                   15440: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15441: passed in @what from the requested user's environment, returns a hash
                   15442: 
1.858     raeburn  15443: =item * 
                   15444: X<userlog_query()>
1.859     albertel 15445: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15446: activity.log file. %filters defines filters applied when parsing the
                   15447: log file. These can be start or end timestamps, or the type of action
                   15448: - log to look for Login or Logout events, check for Checkin or
                   15449: Checkout, role for role selection. The response is in the form
                   15450: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15451: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15452: 
1.243     albertel 15453: =back
                   15454: 
                   15455: =head2 User Roles
                   15456: 
                   15457: =over 4
                   15458: 
                   15459: =item *
                   15460: 
1.1284    raeburn  15461: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15462: returns codes for allowed actions.
                   15463: 
                   15464: The first argument is required, all others are optional.
                   15465: 
                   15466: $priv is the privilege being checked.
                   15467: $uri contains additional information about what is being checked for access (e.g.,
                   15468: URL, course ID etc.). 
                   15469: $symb is the unique resource instance identifier in a course; if needed,
                   15470: but not provided, it will be retrieved via a call to &symbread(). 
                   15471: $role is the role for which a priv is being checked (only used if priv is evb). 
                   15472: $clientip is the user's IP address (only used when checking for access to portfolio 
                   15473: files).
                   15474: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   15475: prevents recursive calls to &allowed.
                   15476: 
1.243     albertel 15477:  F: full access
                   15478:  U,I,K: authentication modes (cxx only)
                   15479:  '': forbidden
                   15480:  1: user needs to choose course
                   15481:  2: browse allowed
1.766     albertel 15482:  A: passphrase authentication needed
1.1284    raeburn  15483:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  15484:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 15485: 
                   15486: =item *
                   15487: 
1.1192    raeburn  15488: constructaccess($url,$setpriv) : check for access to construction space URL
                   15489: 
                   15490: See if the owner domain and name in the URL match those in the
                   15491: expected environment.  If so, return three element list
                   15492: ($ownername,$ownerdomain,$ownerhome).
                   15493: 
                   15494: Otherwise return the null string.
                   15495: 
                   15496: If second argument 'setpriv' is true, it assigns the privileges,
                   15497: and returns the same three element list, unless the owner has
                   15498: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15499: in which case the null string is returned.
                   15500: 
                   15501: =item *
                   15502: 
1.1326    raeburn  15503: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15504: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15505: for system, domain, and course level. $uname and $udom are optional (current
                   15506: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15507: 
                   15508: =item *
                   15509: 
1.988     raeburn  15510: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15511: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15512: $type is Course (default) or Community.
1.988     raeburn  15513: If $forcedefault evaluates to true, text returned will be default 
                   15514: text for $type. Otherwise, if this is a course, the text returned 
                   15515: will be a custom name for the role (if defined in the course's 
                   15516: environment).  If no custom name is defined the default is returned.
                   15517:    
1.832     raeburn  15518: =item *
                   15519: 
1.1219    raeburn  15520: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15521: All arguments are optional. Returns a hash of a roles, either for
                   15522: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15523: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15524: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15525: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15526: For each key, value is set to colon-separated start and end times for
                   15527: the role.  If no username and domain are specified, will default to
1.934     raeburn  15528: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15529: of role statuses (active, future or previous), roles 
                   15530: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15531: to restrict the list of roles reported. If no array ref is 
                   15532: provided for types, will default to return only active roles.
1.834     albertel 15533: 
1.1195    raeburn  15534: =item *
                   15535: 
                   15536: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  15537: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   15538: 
                   15539: Additional optional arguments are: $type (if role checking is to be restricted 
                   15540: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  15541: available roles) or future (roles available in the future), and
                   15542: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  15543: have active Domain Coordinator role in course's domain or in additional
                   15544: domains (specified in 'Domains to check for privileged users' in course
                   15545: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15546: 
                   15547: =item *
                   15548: 
                   15549: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15550: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15551: $possdomains and $possroles are optional array refs -- to domains to check and
                   15552: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15553: users' roles.db to check for a dc or su role in any domain. This can be
                   15554: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15555: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15556: this then allows &privileged_by_domain() to be used, which caches the identity
                   15557: of privileged users, eliminating the need for repeated calls to &dump().
                   15558: 
                   15559: =item *
                   15560: 
                   15561: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15562: where the outer hash keys are domains specified in the $possdomains array ref,
                   15563: next inner hash keys are privileged roles specified in the $roles array ref,
                   15564: and the innermost hash contains key = value pairs for username:domain = end:start
                   15565: for active or future "privileged" users with that role in that domain. To avoid
                   15566: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15567: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  15568: 
1.243     albertel 15569: =back
                   15570: 
                   15571: =head2 User Modification
                   15572: 
                   15573: =over 4
                   15574: 
                   15575: =item *
                   15576: 
1.957     raeburn  15577: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15578: user for the level given by URL.  Optional start and end dates (leave empty
                   15579: string or zero for "no date")
1.191     harris41 15580: 
                   15581: =item *
                   15582: 
1.243     albertel 15583: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15584: change a users, password, possible return values are: ok,
                   15585: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15586: refused
1.191     harris41 15587: 
                   15588: =item *
                   15589: 
1.243     albertel 15590: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15591: 
                   15592: =item *
                   15593: 
1.1058    raeburn  15594: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15595:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15596: 
                   15597: will update user information (firstname,middlename,lastname,generation,
                   15598: permanentemail), and if forceid is true, student/employee ID also.
                   15599: A user's institutional affiliation(s) can also be updated.
                   15600: User information fields will not be overwritten with empty entries 
                   15601: unless the field is included in the $candelete array reference.
                   15602: This array is included when a single user is modified via "Manage Users",
                   15603: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15604: 
                   15605: =item *
                   15606: 
1.286     matthew  15607: modifystudent
                   15608: 
1.957     raeburn  15609: modify a student's enrollment and identification information.
1.1235    raeburn  15610: The course id is resolved based on the current user's environment.  
                   15611: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15612: associated with a course.
                   15613: 
1.297     matthew  15614: This call is essentially a wrapper for lonnet::modifyuser and
                   15615: lonnet::modify_student_enrollment
1.286     matthew  15616: 
                   15617: Inputs: 
                   15618: 
                   15619: =over 4
                   15620: 
1.957     raeburn  15621: =item B<$udom> Student's loncapa domain
1.286     matthew  15622: 
1.957     raeburn  15623: =item B<$uname> Student's loncapa login name
1.286     matthew  15624: 
1.964     bisitz   15625: =item B<$uid> Student/Employee ID
1.286     matthew  15626: 
1.957     raeburn  15627: =item B<$umode> Student's authentication mode
1.286     matthew  15628: 
1.957     raeburn  15629: =item B<$upass> Student's password
1.286     matthew  15630: 
1.957     raeburn  15631: =item B<$first> Student's first name
1.286     matthew  15632: 
1.957     raeburn  15633: =item B<$middle> Student's middle name
1.286     matthew  15634: 
1.957     raeburn  15635: =item B<$last> Student's last name
1.286     matthew  15636: 
1.957     raeburn  15637: =item B<$gene> Student's generation
1.286     matthew  15638: 
1.957     raeburn  15639: =item B<$usec> Student's section in course
1.286     matthew  15640: 
                   15641: =item B<$end> Unix time of the roles expiration
                   15642: 
                   15643: =item B<$start> Unix time of the roles start date
                   15644: 
                   15645: =item B<$forceid> If defined, allow $uid to be changed
                   15646: 
                   15647: =item B<$desiredhome> server to use as home server for student
                   15648: 
1.957     raeburn  15649: =item B<$email> Student's permanent e-mail address
                   15650: 
                   15651: =item B<$type> Type of enrollment (auto or manual)
                   15652: 
1.963     raeburn  15653: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15654: 
                   15655: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15656: 
1.963     raeburn  15657: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15658: 
1.963     raeburn  15659: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15660: 
1.1216    raeburn  15661: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15662: 
                   15663: =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  15664: 
1.286     matthew  15665: =back
1.297     matthew  15666: 
                   15667: =item *
                   15668: 
                   15669: modify_student_enrollment
                   15670: 
1.1235    raeburn  15671: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15672: 'role.request.course' must be defined for this function to proceed.
                   15673: 
                   15674: Inputs:
                   15675: 
                   15676: =over 4
                   15677: 
1.1235    raeburn  15678: =item $udom, student's domain
1.297     matthew  15679: 
1.1235    raeburn  15680: =item $uname, student's name
1.297     matthew  15681: 
1.1235    raeburn  15682: =item $uid, student's user id
1.297     matthew  15683: 
1.1235    raeburn  15684: =item $first, student's first name
1.297     matthew  15685: 
                   15686: =item $middle
                   15687: 
                   15688: =item $last
                   15689: 
                   15690: =item $gene
                   15691: 
                   15692: =item $usec
                   15693: 
                   15694: =item $end
                   15695: 
                   15696: =item $start
                   15697: 
1.957     raeburn  15698: =item $type
                   15699: 
                   15700: =item $locktype
                   15701: 
                   15702: =item $cid
                   15703: 
                   15704: =item $selfenroll
                   15705: 
                   15706: =item $context
                   15707: 
1.1216    raeburn  15708: =item $credits, number of credits student will earn from this class
                   15709: 
1.1314    raeburn  15710: =item $instsec, institutional course section code for student
                   15711: 
1.297     matthew  15712: =back
                   15713: 
1.191     harris41 15714: 
                   15715: =item *
                   15716: 
1.243     albertel 15717: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15718: custom role; give a custom role to a user for the level given by URL.  Specify
                   15719: name and domain of role author, and role name
1.191     harris41 15720: 
                   15721: =item *
                   15722: 
1.243     albertel 15723: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15724: 
                   15725: =item *
                   15726: 
1.243     albertel 15727: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15728: 
                   15729: =back
                   15730: 
                   15731: =head2 Course Infomation
                   15732: 
                   15733: =over 4
1.191     harris41 15734: 
                   15735: =item *
                   15736: 
1.1118    foxr     15737: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15738: specified course id, including all environment settings for the
                   15739: course, the description of the course will be in the hash under the
                   15740: key 'description'
1.191     harris41 15741: 
1.1118    foxr     15742: $options is an optional parameter that if supplied is a hash reference that controls
                   15743: what how this function works.  It has the following key/values:
                   15744: 
                   15745: =over 4
                   15746: 
                   15747: =item freshen_cache
                   15748: 
                   15749: If defined, and the environment cache for the course is valid, it is 
                   15750: returned in the returned hash.
                   15751: 
                   15752: =item one_time
                   15753: 
                   15754: If defined, the last cache time is set to _now_
                   15755: 
                   15756: =item user
                   15757: 
                   15758: If defined, the supplied username is used instead of the current user.
                   15759: 
                   15760: 
                   15761: =back
                   15762: 
1.191     harris41 15763: =item *
                   15764: 
1.624     albertel 15765: resdata($name,$domain,$type,@which) : request for current parameter
                   15766: setting for a specific $type, where $type is either 'course' or 'user',
                   15767: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15768: answers for 10 minutes.
1.243     albertel 15769: 
1.877     foxr     15770: =item *
                   15771: 
                   15772: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15773: data base, returning a hash that is keyed by the resource name and has
                   15774: values that are the resource value.  I believe that the timestamps and
                   15775: versions are also returned.
                   15776: 
1.1236    raeburn  15777: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15778: supplemental content area. This routine caches the number of files for 
                   15779: 10 minutes.
                   15780: 
1.243     albertel 15781: =back
                   15782: 
                   15783: =head2 Course Modification
                   15784: 
                   15785: =over 4
1.191     harris41 15786: 
                   15787: =item *
                   15788: 
1.243     albertel 15789: writecoursepref($courseid,%prefs) : write preferences (environment
                   15790: database) for a course
1.191     harris41 15791: 
                   15792: =item *
                   15793: 
1.1011    raeburn  15794: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15795: 
                   15796: =item *
                   15797: 
1.1038    raeburn  15798: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15799: 
1.1167    droeschl 15800: =item *
                   15801: 
                   15802: is_course($courseid), is_course($cdom, $cnum)
                   15803: 
                   15804: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15805: two component version $cdom, $cnum. It checks if the specified course exists.
                   15806: 
                   15807: Returns:
                   15808:     undef if the course doesn't exist, otherwise
                   15809:     in scalar context the combined courseid.
                   15810:     in list context the two components of the course identifier, domain and 
                   15811:     courseid.    
                   15812: 
1.243     albertel 15813: =back
                   15814: 
1.1401    raeburn  15815: =head2 Bubblesheet Configuration
                   15816: 
                   15817: =over 4
                   15818: 
                   15819: =item *
                   15820: 
                   15821: get_scantron_config($which)
                   15822: 
                   15823: $which - the name of the configuration to parse from the file.
                   15824: 
                   15825: Parses and returns the bubblesheet configuration line selected as a
                   15826: hash of configuration file fields.
                   15827: 
                   15828: 
                   15829: Returns:
                   15830:     If the named configuration is not in the file, an empty
                   15831:     hash is returned.
                   15832: 
                   15833:     a hash with the fields
                   15834:       name         - internal name for the this configuration setup
                   15835:       description  - text to display to operator that describes this config
                   15836:       CODElocation - if 0 or the string 'none'
                   15837:                           - no CODE exists for this config
                   15838:                      if -1 || the string 'letter'
                   15839:                           - a CODE exists for this config and is
                   15840:                             a string of letters
                   15841:                      Unsupported value (but planned for future support)
                   15842:                           if a positive integer
                   15843:                                - The CODE exists as the first n items from
                   15844:                                  the question section of the form
                   15845:                           if the string 'number'
                   15846:                                - The CODE exists for this config and is
                   15847:                                  a string of numbers
                   15848:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15849:                      the CODE starts
                   15850:       CODElength  - length of the CODE
                   15851:       IDstart     - column where the student/employee ID starts
                   15852:       IDlength    - length of the student/employee ID info
                   15853:       Qstart      - column where the information from the bubbled
                   15854:                     'questions' start
                   15855:       Qlength     - number of columns comprising a single bubble line from
                   15856:                     the sheet. (usually either 1 or 10)
                   15857:       Qon         - either a single character representing the character used
                   15858:                     to signal a bubble was chosen in the positional setup, or
                   15859:                     the string 'letter' if the letter of the chosen bubble is
                   15860:                     in the final, or 'number' if a number representing the
                   15861:                     chosen bubble is in the file (1->A 0->J)
                   15862:       Qoff        - the character used to represent that a bubble was
                   15863:                     left blank
                   15864:       PaperID     - if the scanning process generates a unique number for each
                   15865:                     sheet scanned the column that this ID number starts in
                   15866:       PaperIDlength - number of columns that comprise the unique ID number
                   15867:                       for the sheet of paper
                   15868:       FirstName   - column that the first name starts in
                   15869:       FirstNameLength - number of columns that the first name spans
                   15870:       LastName    - column that the last name starts in
                   15871:       LastNameLength - number of columns that the last name spans
                   15872:       BubblesPerRow - number of bubbles available in each row used to
                   15873:                       bubble an answer. (If not specified, 10 assumed).
                   15874: 
                   15875: 
                   15876: =item *
                   15877: 
                   15878: get_scantronformat_file($cdom)
                   15879: 
                   15880: $cdom - the course's domain (optional); if not supplied, uses
                   15881: domain for current $env{'request.course.id'}.
                   15882: 
                   15883: Returns an array containing lines from the scantron format file for
                   15884: the domain of the course.
                   15885: 
                   15886: If a url for a custom.tab file is listed in domain's configuration.db,
                   15887: lines are from this file.
                   15888: 
                   15889: Otherwise, if a default.tab has been published in RES space by the
                   15890: domainconfig user, lines are from this file.
                   15891: 
                   15892: Otherwise, fall back to getting lines from the legacy file on the
                   15893: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15894: 
                   15895: =back
                   15896: 
1.243     albertel 15897: =head2 Resource Subroutines
                   15898: 
                   15899: =over 4
1.191     harris41 15900: 
                   15901: =item *
                   15902: 
1.243     albertel 15903: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15904: 
                   15905: =item *
                   15906: 
1.243     albertel 15907: repcopy($filename) : subscribes to the requested file, and attempts to
                   15908: replicate from the owning library server, Might return
1.607     raeburn  15909: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15910: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15911: resource. Expects the local filesystem pathname
                   15912: (/home/httpd/html/res/....)
                   15913: 
                   15914: =back
                   15915: 
                   15916: =head2 Resource Information
                   15917: 
                   15918: =over 4
1.191     harris41 15919: 
                   15920: =item *
                   15921: 
1.1228    raeburn  15922: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15923: and returns the value of a variety of different possible values,
                   15924: $varname should be a request string, and the other parameters can be
                   15925: used to specify who and what one is asking about. Ordinarily, $cid 
                   15926: does not need to be specified, as it is retrived from 
                   15927: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15928: within lonuserstate::loadmap() when initializing a course, before
                   15929: $env{'request.course.id'} has been set, so it needs to be provided
                   15930: in that one case.
1.243     albertel 15931: 
                   15932: Possible values for $varname are environment.lastname (or other item
                   15933: from the envirnment hash), user.name (or someother aspect about the
                   15934: user), resource.0.maxtries (or some other part and parameter of a
                   15935: resource)
1.204     albertel 15936: 
                   15937: =item *
                   15938: 
1.243     albertel 15939: directcondval($number) : get current value of a condition; reads from a state
                   15940: string
1.204     albertel 15941: 
                   15942: =item *
                   15943: 
1.243     albertel 15944: condval($condidx) : value of condition index based on state
1.204     albertel 15945: 
                   15946: =item *
                   15947: 
1.1362    raeburn  15948: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15949: resource's metadata, $what should be either a specific key, or either
                   15950: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15951: packages that this resource currently uses, the last 3 arguments are 
                   15952: only used internally for recursive metadata.
                   15953: 
                   15954: the toolsymb is only used where the uri is for an external tool (for which
                   15955: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15956: 
1.1371    raeburn  15957: this function automatically caches all requests except any made recursively
                   15958: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15959: defined).
1.191     harris41 15960: 
                   15961: =item *
                   15962: 
1.243     albertel 15963: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15964: network of library servers; returns file handle of where SQL and regex results
                   15965: will be stored for query
1.191     harris41 15966: 
                   15967: =item *
                   15968: 
1.1282    raeburn  15969: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15970: return symbolic list entry (all arguments optional). 
                   15971: 
                   15972: Args: filename is the filename (including path) for the file for which a symb 
                   15973: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15974: to check access status if more than one resource was found in the bighash 
                   15975: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15976: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15977: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15978: cause possible symbs to be checked to determine if they are subject to content
                   15979: blocking, if so they will not be included as possible symbs; possibles is a
                   15980: ref to a hash, which, as a side effect, will be populated with all possible 
                   15981: symbs (content blocking not tested).
                   15982:  
1.243     albertel 15983: returns the data handle
1.191     harris41 15984: 
                   15985: =item *
                   15986: 
1.1190    raeburn  15987: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15988: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15989: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15990: on failure, user must be in a course, as it assumes the existence of
                   15991: the course initial hash, and uses $env('request.course.id'}.  The third
                   15992: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15993: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15994: encrypted; otherwise it will be null.  
1.191     harris41 15995: 
                   15996: =item *
                   15997: 
1.243     albertel 15998: symbclean($symb) : removes versions numbers from a symb, returns the
                   15999: cleaned symb
1.191     harris41 16000: 
                   16001: =item *
                   16002: 
1.243     albertel 16003: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16004: course map, user must be in a course for it to work.
1.191     harris41 16005: 
                   16006: =item *
                   16007: 
1.243     albertel 16008: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16009: 
                   16010: =item *
                   16011: 
1.243     albertel 16012: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16013: a random seed, all arguments are optional, if they aren't sent it uses the
                   16014: environment to derive them. Note: if symb isn't sent and it can't get one
                   16015: from &symbread it will use the current time as its return value
1.191     harris41 16016: 
                   16017: =item *
                   16018: 
1.243     albertel 16019: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16020: unfakeable, receipt
1.191     harris41 16021: 
                   16022: =item *
                   16023: 
1.620     albertel 16024: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16025: 
                   16026: =item *
                   16027: 
1.243     albertel 16028: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16029: 
                   16030: =item *
                   16031: 
1.243     albertel 16032: 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 16033: 
                   16034: =item *
                   16035: 
1.243     albertel 16036: 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 16037: 
                   16038: =item *
                   16039: 
1.243     albertel 16040: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16041: 
                   16042: =item *
                   16043: 
1.243     albertel 16044: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16045: forcing spreadsheet to reevaluate the resource scores next time.
                   16046: 
1.1195    raeburn  16047: =item * 
                   16048: 
1.1196    raeburn  16049: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16050: when viewing in course context.
1.1195    raeburn  16051: 
1.1196    raeburn  16052:  input: six args -- filename (decluttered), course number, course domain,
                   16053:                     url, symb (if registered) and group (if this is a 
                   16054:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  16055: 
1.1196    raeburn  16056:  output: array of five scalars --
1.1195    raeburn  16057:          $cfile -- url for file editing if editable on current server
                   16058:          $home -- homeserver of resource (i.e., for author if published,
                   16059:                                           or course if uploaded.).
                   16060:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  16061:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   16062:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  16063: 
                   16064: =item *
                   16065: 
                   16066: is_course_upload($file,$cnum,$cdom)
                   16067: 
                   16068: Used in course context to determine if current file was uploaded to 
                   16069: the course (i.e., would be found in /userfiles/docs on the course's 
                   16070: homeserver.
                   16071: 
                   16072:   input: 3 args -- filename (decluttered), course number and course domain.
                   16073:   output: boolean -- 1 if file was uploaded.
                   16074: 
1.243     albertel 16075: =back
                   16076: 
                   16077: =head2 Storing/Retreiving Data
                   16078: 
                   16079: =over 4
1.191     harris41 16080: 
                   16081: =item *
                   16082: 
1.1269    raeburn  16083: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   16084: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16085: the remaining args aren't required and if they aren't passed or are '' they will
                   16086: be derived from the env (with the exception of $laststore, which is an 
                   16087: optional arg used when a user's submission is stored in grading).
                   16088: $laststore is $version=$timestamp, where $version is the most recent version
                   16089: number retrieved for the corresponding $symb in the $namespace db file, and
                   16090: $timestamp is the timestamp for that transaction (UNIX time).
                   16091: $laststore is currently only passed when cstore() is called by 
                   16092: structuretags::finalize_storage().
1.191     harris41 16093: 
                   16094: =item *
                   16095: 
1.1269    raeburn  16096: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   16097: but uses critical subroutine
1.191     harris41 16098: 
                   16099: =item *
                   16100: 
1.243     albertel 16101: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16102: all args are optional
1.191     harris41 16103: 
                   16104: =item *
                   16105: 
1.717     albertel 16106: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16107: dumps the complete (or key matching regexp) namespace into a hash
                   16108: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16109: normally &store()ed into
                   16110: 
                   16111: $range should be either an integer '100' (give me the first 100
                   16112:                                            matching records)
                   16113:               or be  two integers sperated by a - with no spaces
                   16114:                  '30-50' (give me the 30th through the 50th matching
                   16115:                           records)
                   16116: 
                   16117: 
                   16118: =item *
                   16119: 
1.1269    raeburn  16120: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16121: replaces a &store() version of data with a replacement set of data
                   16122: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  16123: reference. If $tolog is true, the transaction is logged in the courselog
                   16124: with an action=PUTSTORE.
1.717     albertel 16125: 
                   16126: =item *
                   16127: 
1.243     albertel 16128: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16129: works very similar to store/cstore, but all data is stored in a
                   16130: temporary location and can be reset using tmpreset, $storehash should
                   16131: be a hash reference, returns nothing on success
1.191     harris41 16132: 
                   16133: =item *
                   16134: 
1.243     albertel 16135: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16136: similar to restore, but all data is stored in a temporary location and
                   16137: can be reset using tmpreset. Returns a hash of values on success,
                   16138: error string otherwise.
1.191     harris41 16139: 
                   16140: =item *
                   16141: 
1.243     albertel 16142: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16143: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16144: 
                   16145: =item *
                   16146: 
1.243     albertel 16147: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16148: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16149: 
                   16150: =item *
                   16151: 
1.243     albertel 16152: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16153: namesp ($udom and $uname are optional)
1.191     harris41 16154: 
                   16155: =item *
                   16156: 
1.702     albertel 16157: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16158: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16159: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16160: 
1.702     albertel 16161: $range should be either an integer '100' (give me the first 100
                   16162:                                            matching records)
                   16163:               or be  two integers sperated by a - with no spaces
                   16164:                  '30-50' (give me the 30th through the 50th matching
                   16165:                           records)
1.449     matthew  16166: =item *
                   16167: 
                   16168: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16169: $store can be a scalar, an array reference, or if the amount to be 
                   16170: incremented is > 1, a hash reference.
                   16171: 
                   16172: ($udom and $uname are optional)
1.191     harris41 16173: 
                   16174: =item *
                   16175: 
1.243     albertel 16176: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16177: ($udom and $uname are optional)
1.191     harris41 16178: 
                   16179: =item *
                   16180: 
1.243     albertel 16181: cput($namespace,$storehash,$udom,$uname) : critical put
                   16182: ($udom and $uname are optional)
1.191     harris41 16183: 
                   16184: =item *
                   16185: 
1.748     albertel 16186: newput($namespace,$storehash,$udom,$uname) :
                   16187: 
                   16188: Attempts to store the items in the $storehash, but only if they don't
                   16189: currently exist, if this succeeds you can be certain that you have 
                   16190: successfully created a new key value pair in the $namespace db.
                   16191: 
                   16192: 
                   16193: Args:
                   16194:  $namespace: name of database to store values to
                   16195:  $storehash: hashref to store to the db
                   16196:  $udom: (optional) domain of user containing the db
                   16197:  $uname: (optional) name of user caontaining the db
                   16198: 
                   16199: Returns:
                   16200:  'ok' -> succeeded in storing all keys of $storehash
                   16201:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16202:                         least <key> already existed in the db (other
                   16203:                         requested keys may also already exist)
1.967     bisitz   16204:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16205:  'con_lost' -> unable to contact request server
                   16206:  'refused' -> action was not allowed by remote machine
                   16207: 
                   16208: 
                   16209: =item *
                   16210: 
1.243     albertel 16211: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16212: reference filled in from namesp (encrypts the return communication)
                   16213: ($udom and $uname are optional)
1.191     harris41 16214: 
                   16215: =item *
                   16216: 
1.243     albertel 16217: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16218: critical subroutine
                   16219: 
1.806     raeburn  16220: =item *
                   16221: 
1.860     raeburn  16222: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16223: array reference filled in from namespace found in domain level on either
                   16224: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16225: 
                   16226: =item *
                   16227: 
1.860     raeburn  16228: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16229: domain level either on specified domain server ($uhome) or primary domain 
                   16230: server ($udom and $uhome are optional)
1.806     raeburn  16231: 
1.943     raeburn  16232: =item * 
                   16233: 
1.1240    raeburn  16234: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   16235: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16236: the target domain.
                   16237: 
                   16238: May also include additional key => value pairs for the following groups:
                   16239: 
                   16240: =over
                   16241: 
                   16242: =item
                   16243: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16244: 
                   16245: =over
                   16246: 
                   16247: =item defaultquota, authorquota
                   16248: 
                   16249: =back
                   16250: 
                   16251: =item
                   16252: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16253: portfolio for users).
                   16254: 
                   16255: =over
                   16256: 
                   16257: =item
                   16258: aboutme, blog, webdav, portfolio
                   16259: 
                   16260: =back
                   16261: 
                   16262: =item
                   16263: requestcourses: ability to request courses, and how requests are processed.
                   16264: 
                   16265: =over
                   16266: 
                   16267: =item
1.1305    raeburn  16268: official, unofficial, community, textbook, placement
1.1240    raeburn  16269: 
                   16270: =back
                   16271: 
                   16272: =item
                   16273: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16274: 
                   16275: =over
                   16276: 
                   16277: =item
1.1256    raeburn  16278: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  16279: 
                   16280: =back
                   16281: 
                   16282: =item
                   16283: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16284: for course's uploaded content.
                   16285: 
                   16286: =over
                   16287: 
                   16288: =item
1.1246    raeburn  16289: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  16290: communityquota, textbookquota, placementquota
1.1240    raeburn  16291: 
                   16292: =back
                   16293: 
                   16294: =item
                   16295: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16296: on your servers.
                   16297: 
                   16298: =over
                   16299: 
                   16300: =item 
                   16301: remotesessions, hostedsessions
                   16302: 
                   16303: =back
                   16304: 
                   16305: =back
                   16306: 
                   16307: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16308: utility to create a configuration.db file on a domain's primary library server 
                   16309: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16310: -- corresponding values are authentication type (internal, krb4, krb5,
                   16311: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   16312: will be available. Values are retrieved from cache (if current), unless the
                   16313: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16314: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16315: 
                   16316: Typical usage:
1.943     raeburn  16317: 
1.1240    raeburn  16318: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16319: 
1.243     albertel 16320: =back
                   16321: 
                   16322: =head2 Network Status Functions
                   16323: 
                   16324: =over 4
1.191     harris41 16325: 
                   16326: =item *
                   16327: 
1.1137    raeburn  16328: dirlist() : return directory list based on URI (first arg).
                   16329: 
                   16330: Inputs: 1 required, 5 optional.
                   16331: 
                   16332: =over
                   16333: 
                   16334: =item 
                   16335: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16336: 
                   16337: =item
                   16338: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16339: 
                   16340: =item
                   16341: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16342: 
                   16343: =item
                   16344: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16345: 
                   16346: =item
                   16347: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16348: 
                   16349: =item 
                   16350: $alternateRoot - path to prepend in place of path from $uri.
                   16351: 
                   16352: =back
                   16353: 
                   16354: Returns: Array of up to two items.
                   16355: 
                   16356: =over
                   16357: 
                   16358: a reference to an array of files/subdirectories
                   16359: 
                   16360: =over
                   16361: 
                   16362: Each element in the array of files/subdirectories is a & separated list of
                   16363: item name and the result of running stat on the item.  If dirlist was requested
                   16364: for a file instead of a directory, the item name will be ''. For a directory 
                   16365: listing, if the item is a metadata file, the element will end &N&M 
                   16366: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16367: default copyright set (1).  
                   16368: 
                   16369: =back
                   16370: 
                   16371: a scalar containing error condition (if encountered).
                   16372: 
                   16373: =over
                   16374: 
                   16375: =item 
                   16376: no_host (no homeserver identified for $username:$domain).
                   16377: 
                   16378: =item 
                   16379: no_such_host (server contacted for listing not identified as valid host).
                   16380: 
                   16381: =item 
                   16382: con_lost (connection to remote server failed).
                   16383: 
                   16384: =item 
                   16385: refused (invalid $username:$domain received on lond side).
                   16386: 
                   16387: =item 
                   16388: no_such_dir (directory at specified path on lond side does not exist). 
                   16389: 
                   16390: =item 
                   16391: empty (directory at specified path on lond side is empty).
                   16392: 
                   16393: =over
                   16394: 
                   16395: This is currently not encountered because the &ls3, &ls2, 
                   16396: &ls (_handler) routines on the lond side do not filter out
                   16397: . and .. from a directory listing. 
                   16398: 
                   16399: =back
                   16400: 
                   16401: =back
                   16402: 
                   16403: =back
1.191     harris41 16404: 
                   16405: =item *
                   16406: 
1.243     albertel 16407: spareserver() : find server with least workload from spare.tab
                   16408: 
1.986     foxr     16409: 
                   16410: =item *
                   16411: 
                   16412: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16413: if there is no corresponding loncapa host.
                   16414: 
1.243     albertel 16415: =back
                   16416: 
1.986     foxr     16417: 
1.243     albertel 16418: =head2 Apache Request
                   16419: 
                   16420: =over 4
1.191     harris41 16421: 
                   16422: =item *
                   16423: 
1.243     albertel 16424: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16425: localhost, posts hash
                   16426: 
                   16427: =back
                   16428: 
                   16429: =head2 Data to String to Data
                   16430: 
                   16431: =over 4
1.191     harris41 16432: 
                   16433: =item *
                   16434: 
1.243     albertel 16435: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16436: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16437: 
                   16438: =item *
                   16439: 
1.243     albertel 16440: hashref2str($hashref) : convert a hashref into a string complete with
                   16441: escaping and '=' and '&' separators, supports elements that are
                   16442: arrayrefs and hashrefs
1.191     harris41 16443: 
                   16444: =item *
                   16445: 
1.243     albertel 16446: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16447: with escaping and '&' separators, supports elements that are arrayrefs
                   16448: and hashrefs
1.191     harris41 16449: 
                   16450: =item *
                   16451: 
1.243     albertel 16452: str2hash($string) : convert string to hash using unescaping and
                   16453: splitting on '=' and '&', supports elements that are arrayrefs and
                   16454: hashrefs
1.191     harris41 16455: 
                   16456: =item *
                   16457: 
1.243     albertel 16458: str2array($string) : convert string to hash using unescaping and
                   16459: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16460: 
                   16461: =back
                   16462: 
                   16463: =head2 Logging Routines
                   16464: 
                   16465: 
                   16466: These routines allow one to make log messages in the lonnet.log and
                   16467: lonnet.perm logfiles.
1.191     harris41 16468: 
1.1119    foxr     16469: =over 4
                   16470: 
1.191     harris41 16471: =item *
                   16472: 
1.243     albertel 16473: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16474: 
                   16475: =item *
                   16476: 
1.243     albertel 16477: logthis() : append message to the normal lonnet.log file, it gets
                   16478: preiodically rolled over and deleted.
1.191     harris41 16479: 
                   16480: =item *
                   16481: 
1.243     albertel 16482: logperm() : append a permanent message to lonnet.perm.log, this log
                   16483: file never gets deleted by any automated portion of the system, only
                   16484: messages of critical importance should go in here.
                   16485: 
1.1119    foxr     16486: 
1.243     albertel 16487: =back
                   16488: 
                   16489: =head2 General File Helper Routines
                   16490: 
                   16491: =over 4
1.191     harris41 16492: 
                   16493: =item *
                   16494: 
1.481     raeburn  16495: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16496: (a) files in /uploaded
                   16497:   (i) If a local copy of the file exists - 
                   16498:       compares modification date of local copy with last-modified date for 
                   16499:       definitive version stored on home server for course. If local copy is 
                   16500:       stale, requests a new version from the home server and stores it. 
                   16501:       If the original has been removed from the home server, then local copy 
                   16502:       is unlinked.
                   16503:   (ii) If local copy does not exist -
                   16504:       requests the file from the home server and stores it. 
                   16505:   
                   16506:   If $caller is 'uploadrep':  
                   16507:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16508:     for request for files originally uploaded via DOCS. 
                   16509:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16510:   
                   16511:   Otherwise:
                   16512:      This indicates a call from the content generation phase of the request.
                   16513:      -  returns the entire contents of the file or -1.
                   16514:      
                   16515: (b) files in /res
                   16516:    - returns the entire contents of a file or -1; 
                   16517:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16518: 
1.712     albertel 16519: 
                   16520: =item *
                   16521: 
                   16522: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16523:                   reference
                   16524: 
                   16525: returns either a stat() list of data about the file or an empty list
                   16526: if the file doesn't exist or couldn't find out about it (connection
                   16527: problems or user unknown)
                   16528: 
1.191     harris41 16529: =item *
                   16530: 
1.243     albertel 16531: filelocation($dir,$file) : returns file system location of a file
                   16532: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16533: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16534: and a file of ../bob will become /a/bob)
1.191     harris41 16535: 
                   16536: =item *
                   16537: 
                   16538: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16539: filelocation except for hrefs
                   16540: 
                   16541: =item *
                   16542: 
1.1261    raeburn  16543: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16544: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16545: 
1.243     albertel 16546: =back
                   16547: 
1.608     albertel 16548: =head2 Usererfile file routines (/uploaded*)
                   16549: 
                   16550: =over 4
                   16551: 
                   16552: =item *
                   16553: 
                   16554: userfileupload(): main rotine for putting a file in a user or course's
                   16555:                   filespace, arguments are,
                   16556: 
1.620     albertel 16557:  formname - required - this is the name of the element in $env where the
1.608     albertel 16558:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16559:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16560:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16561:  context - if coursedoc, store the file in the course of the active role
                   16562:              of the current user; 
                   16563:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16564:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16565:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16566:          if undefined, it will be placed in "unknown"
                   16567: 
                   16568:  (This routine calls clean_filename() to remove any dangerous
                   16569:  characters from the filename, and then calls finuserfileupload() to
                   16570:  complete the transaction)
                   16571: 
                   16572:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16573:  and /adm/notfound.html if unsuccessful
                   16574: 
                   16575: =item *
                   16576: 
                   16577: clean_filename(): routine for cleaing a filename up for storage in
                   16578:                  userfile space, argument is:
                   16579: 
                   16580:  filename - proposed filename
                   16581: 
                   16582: returns: the new clean filename
                   16583: 
                   16584: =item *
                   16585: 
1.1090    raeburn  16586: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16587: userspace, probably shouldn't be called directly
                   16588: 
                   16589:   docuname: username or courseid of destination for the file
                   16590:   docudom: domain of user/course of destination for the file
                   16591:   formname: same as for userfileupload()
1.1090    raeburn  16592:   fname: filename (including subdirectories) for the file
                   16593:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  16594:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16595:   allfiles: reference to hash used to store objects found by parser
                   16596:   codebase: reference to hash used for codebases of java objects found by parser
                   16597:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16598:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16599:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16600:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16601:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16602:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16603:   mimetype: reference to scalar to accommodate mime type determined
                   16604:             from File::MMagic if $parser = parse.
1.608     albertel 16605: 
                   16606:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16607:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16608:  was 'overwrite').
                   16609:  
1.608     albertel 16610: 
                   16611: =item *
                   16612: 
                   16613: renameuserfile(): renames an existing userfile to a new name
                   16614: 
                   16615:   Args:
                   16616:    docuname: username or courseid of destination for the file
                   16617:    docudom: domain of user/course of destination for the file
                   16618:    old: current file name (including any subdirs under userfiles)
                   16619:    new: desired file name (including any subdirs under userfiles)
                   16620: 
                   16621: =item *
                   16622: 
                   16623: mkdiruserfile(): creates a directory is a userfiles dir
                   16624: 
                   16625:   Args:
                   16626:    docuname: username or courseid of destination for the file
                   16627:    docudom: domain of user/course of destination for the file
                   16628:    dir: dir to create (including any subdirs under userfiles)
                   16629: 
                   16630: =item *
                   16631: 
                   16632: removeuserfile(): removes a file that exists in userfiles
                   16633: 
                   16634:   Args:
                   16635:    docuname: username or courseid of destination for the file
                   16636:    docudom: domain of user/course of destination for the file
                   16637:    fname: filname to delete (including any subdirs under userfiles)
                   16638: 
                   16639: =item *
                   16640: 
                   16641: removeuploadedurl(): convience function for removeuserfile()
                   16642: 
                   16643:   Args:
                   16644:    url:  a full /uploaded/... url to delete
                   16645: 
1.747     albertel 16646: =item * 
                   16647: 
                   16648: get_portfile_permissions():
                   16649:   Args:
                   16650:     domain: domain of user or course contain the portfolio files
                   16651:     user: name of user or num of course contain the portfolio files
                   16652:   Returns:
                   16653:     hashref of a dump of the proper file_permissions.db
                   16654:    
                   16655: 
                   16656: =item * 
                   16657: 
                   16658: get_access_controls():
                   16659: 
                   16660: Args:
                   16661:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16662:   group: (optional) the group you want the files associated with
                   16663:   file: (optional) the file you want access info on
                   16664: 
                   16665: Returns:
1.749     raeburn  16666:     a hash (keys are file names) of hashes containing
                   16667:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16668:         values are XML containing access control settings (see below) 
1.747     albertel 16669: 
                   16670: Internal notes:
                   16671: 
1.749     raeburn  16672:  access controls are stored in file_permissions.db as key=value pairs.
                   16673:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16674:         where scope -> public,guest,course,group,domains or users.
                   16675:               end -> UNIX time for end of access (0 -> no end date)
                   16676:               start -> UNIX time for start of access
                   16677: 
                   16678:     value -> XML description of access control
                   16679:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16680:             <start></start>
                   16681:             <end></end>
                   16682: 
                   16683:             <password></password>  for scope type = guest
                   16684: 
                   16685:             <domain></domain>     for scope type = course or group
                   16686:             <number></number>
                   16687:             <roles id="">
                   16688:              <role></role>
                   16689:              <access></access>
                   16690:              <section></section>
                   16691:              <group></group>
                   16692:             </roles>
                   16693: 
                   16694:             <dom></dom>         for scope type = domains
                   16695: 
                   16696:             <users>             for scope type = users
                   16697:              <user>
                   16698:               <uname></uname>
                   16699:               <udom></udom>
                   16700:              </user>
                   16701:             </users>
                   16702:            </scope> 
                   16703:               
                   16704:  Access data is also aggregated for each file in an additional key=value pair:
                   16705:  key -> path to file/file_name\0accesscontrol 
                   16706:  value -> reference to hash
                   16707:           hash contains key = value pairs
                   16708:           where key = uniqueID:scope_end_start
                   16709:                 value = UNIX time record was last updated
                   16710: 
                   16711:           Used to improve speed of look-ups of access controls for each file.  
                   16712:  
                   16713:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16714: 
1.1198    raeburn  16715: =item *
                   16716: 
1.749     raeburn  16717: modify_access_controls():
                   16718: 
                   16719: Modifies access controls for a portfolio file
                   16720: Args
                   16721: 1. file name
                   16722: 2. reference to hash of required changes,
                   16723: 3. domain
                   16724: 4. username
                   16725:   where domain,username are the domain of the portfolio owner 
                   16726:   (either a user or a course) 
                   16727: 
                   16728: Returns:
                   16729: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16730: 2. result of deletions ('ok' or 'error', with error message).
                   16731: 3. reference to hash of any new or updated access controls.
                   16732: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16733:    key = integer (inbound ID)
1.1198    raeburn  16734:    value = uniqueID
                   16735: 
                   16736: =item *
                   16737: 
                   16738: get_timebased_id():
                   16739: 
                   16740: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   16741: course via the Course Editor (e.g., folders, composite pages, 
                   16742: group bulletin boards).
                   16743: 
                   16744: Args: (first three required; six others optional)
                   16745: 
                   16746: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16747:    docssequence, or name of group
                   16748: 
                   16749: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16750:    e.g., num, boardids
                   16751: 
                   16752: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   16753:    file will be named nohist_namespace.db
                   16754: 
                   16755: 4. cdom: domain of course; default is current course domain from %env
                   16756: 
                   16757: 5. cnum: course number; default is current course number from %env
                   16758: 
                   16759: 6. idtype: set to concat if an additional digit is to be appended to the 
                   16760:    unix timestamp to form the suffix, if the plain timestamp is already
                   16761:    in use.  Default is to not do this, but simply increment the unix 
                   16762:    timestamp by 1 until a unique key is obtained.
                   16763: 
                   16764: 7. who: holder of locking key; defaults to user:domain for user.
                   16765: 
                   16766: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   16767:    retrying); default is 3.
                   16768: 
                   16769: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   16770: 
                   16771: Returns:
                   16772: 
                   16773: 1. suffix obtained (numeric)
                   16774: 
                   16775: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16776: 
                   16777: 3. error: contains (localized) error message if an error occurred.
                   16778: 
1.747     albertel 16779: 
1.608     albertel 16780: =back
                   16781: 
1.243     albertel 16782: =head2 HTTP Helper Routines
                   16783: 
                   16784: =over 4
                   16785: 
1.191     harris41 16786: =item *
                   16787: 
                   16788: escape() : unpack non-word characters into CGI-compatible hex codes
                   16789: 
                   16790: =item *
                   16791: 
                   16792: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16793: 
1.243     albertel 16794: =back
                   16795: 
                   16796: =head1 PRIVATE SUBROUTINES
                   16797: 
                   16798: =head2 Underlying communication routines (Shouldn't call)
                   16799: 
                   16800: =over 4
                   16801: 
                   16802: =item *
                   16803: 
                   16804: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16805: 
                   16806: =item *
                   16807: 
                   16808: reply() : uses subreply to send a message to remote machine, logs all failures
                   16809: 
                   16810: =item *
                   16811: 
                   16812: critical() : passes a critical message to another server; if cannot
                   16813: get through then place message in connection buffer directory and
                   16814: returns con_delayed, if incapable of saving message, returns
                   16815: con_failed
                   16816: 
                   16817: =item *
                   16818: 
                   16819: reconlonc() : tries to reconnect lonc client processes.
                   16820: 
                   16821: =back
                   16822: 
                   16823: =head2 Resource Access Logging
                   16824: 
                   16825: =over 4
                   16826: 
                   16827: =item *
                   16828: 
                   16829: flushcourselogs() : flush (save) buffer logs and access logs
                   16830: 
                   16831: =item *
                   16832: 
                   16833: courselog($what) : save message for course in hash
                   16834: 
                   16835: =item *
                   16836: 
                   16837: courseacclog($what) : save message for course using &courselog().  Perform
                   16838: special processing for specific resource types (problems, exams, quizzes, etc).
                   16839: 
1.191     harris41 16840: =item *
                   16841: 
                   16842: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16843: as a PerlChildExitHandler
1.243     albertel 16844: 
                   16845: =back
                   16846: 
                   16847: =head2 Other
                   16848: 
                   16849: =over 4
                   16850: 
                   16851: =item *
                   16852: 
                   16853: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16854: 
                   16855: =back
                   16856: 
                   16857: =cut
1.877     foxr     16858: 

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