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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1534  ! raeburn     4: # $Id: lonnet.pm,v 1.1533 2025/01/05 21:53:43 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.1434    raeburn    99: use Net::CIDR;
1.1456    raeburn   100: use Sys::Hostname::FQDN();
1.807     albertel  101: use LONCAPA qw(:DEFAULT :match);
1.740     www       102: use LONCAPA::Configuration;
1.1160    www       103: use LONCAPA::lonmetadata;
1.1167    droeschl  104: use LONCAPA::Lond;
1.1345    raeburn   105: use LONCAPA::LWPReq;
1.1406    raeburn   106: use LONCAPA::transliterate;
1.1117    foxr      107: 
1.1090    raeburn   108: use File::Copy;
1.676     albertel  109: 
1.195     www       110: my $readit;
1.1288    damieng   111: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  112: 
1.619     albertel  113: require Exporter;
                    114: 
                    115: our @ISA = qw (Exporter);
                    116: our @EXPORT = qw(%env);
                    117: 
1.449     matthew   118: 
1.1187    raeburn   119: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       120: {
                    121:     my $logid;
1.1187    raeburn   122:     sub write_log {
1.1188    raeburn   123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   124:         if ($context eq 'course') {
                    125:             if (($cnum eq '') || ($cdom eq '')) {
                    126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    128:             }
1.957     raeburn   129:         }
1.1184    raeburn   130: 	$logid ++;
1.957     raeburn   131:         my $now = time();
                    132: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1434    raeburn   133:         my $ip = &get_requestor_ip();
1.1184    raeburn   134:         my $logentry = { 
                    135:                           $id => {
                    136:                                    'exe_uname' => $env{'user.name'},
                    137:                                    'exe_udom'  => $env{'user.domain'},
                    138:                                    'exe_time'  => $now,
1.1434    raeburn   139:                                    'exe_ip'    => $ip,
1.1184    raeburn   140:                                    'delflag'   => $delflag,
                    141:                                    'logentry'  => $storehash,
                    142:                                    'uname'     => $uname,
                    143:                                    'udom'      => $udom,
                    144:                                   }
                    145:                        };
                    146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       147:     }
                    148: }
1.1       albertel  149: 
1.163     harris41  150: sub logtouch {
                    151:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  152:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  154: 	close $fh;
                    155:     }
                    156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    158: }
                    159: 
1.1       albertel  160: sub logthis {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.1359    raeburn   165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    167: 	print $fh $logstring;
1.448     albertel  168: 	close($fh);
                    169:     }
1.1       albertel  170:     return 1;
                    171: }
                    172: 
                    173: sub logperm {
                    174:     my $message=shift;
                    175:     my $execdir=$perlvar{'lonDaemons'};
                    176:     my $now=time;
                    177:     my $local=localtime($now);
1.1359    raeburn   178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  179: 	print $fh "$now:$message:$local\n";
                    180: 	close($fh);
                    181:     }
1.1       albertel  182:     return 1;
                    183: }
                    184: 
1.850     albertel  185: sub create_connection {
1.853     albertel  186:     my ($hostname,$lonid) = @_;
1.851     albertel  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  188: 				     Type    => SOCK_STREAM,
                    189: 				     Timeout => 10);
                    190:     return 0 if (!$client);
1.1528    raeburn   191:     if ($loncaparevs{$lonid} =~ /^(\d+\.\d+\.[\w.]+)-\d+$/) {
                    192:         print $client (join(':',$hostname,$lonid,$1,&machine_ids($hostname))."\n");
                    193:     } else {
                    194:         print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
                    195:     }
1.850     albertel  196:     my $result = <$client>;
                    197:     chomp($result);
                    198:     return 1 if ($result eq 'done');
                    199:     return 0;
                    200: }
                    201: 
1.983     raeburn   202: sub get_server_timezone {
                    203:     my ($cnum,$cdom) = @_;
                    204:     my $home=&homeserver($cnum,$cdom);
                    205:     if ($home ne 'no_host') {
                    206:         my $cachetime = 24*3600;
                    207:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    208:         if (defined($cached)) {
                    209:             return $timezone;
                    210:         } else {
                    211:             my $timezone = &reply('servertimezone',$home);
                    212:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    213:         }
                    214:     }
                    215: }
1.850     albertel  216: 
1.1106    raeburn   217: sub get_server_distarch {
                    218:     my ($lonhost,$ignore_cache) = @_;
                    219:     if (defined($lonhost)) {
                    220:         if (!defined(&hostname($lonhost))) {
                    221:             return;
                    222:         }
                    223:         my $cachetime = 12*3600;
                    224:         if (!$ignore_cache) {
                    225:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    226:             if (defined($cached)) {
                    227:                 return $distarch;
                    228:             }
                    229:         }
                    230:         my $rep = &reply('serverdistarch',$lonhost);
1.1531    raeburn   231:         unless ($rep eq 'unknown_cmd' || $rep eq 'no_such_host' ||
1.1106    raeburn   232:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    233:                 $rep eq '') {
                    234:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    235:         }
                    236:     }
                    237:     return;
                    238: }
                    239: 
1.1315    raeburn   240: sub get_servercerts_info {
1.1383    raeburn   241:     my ($lonhost,$hostname,$context) = @_;
                    242:     return if ($lonhost eq '');
                    243:     if ($hostname eq '') {
                    244:         $hostname = &hostname($lonhost);
                    245:     }
                    246:     return if ($hostname eq '');
1.1315    raeburn   247:     my ($rep,$uselocal);
1.1388    raeburn   248:     if ($context eq 'install') {
1.1387    raeburn   249:         $uselocal = 1;
                    250:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   251:         $uselocal = 1;
                    252:     }
1.1387    raeburn   253:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   254:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   255:         if ($distro eq '') {
                    256:             $uselocal = 0;
                    257:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   258:             if ($1 < 6) {
                    259:                 $uselocal = 0;
                    260:             }
1.1346    raeburn   261:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    262:             if ($1 < 12) {
                    263:                 $uselocal = 0;
                    264:             }
1.1315    raeburn   265:         }
                    266:     }
                    267:     if ($uselocal) {
1.1383    raeburn   268:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   269:     } else {
                    270:         $rep=&reply('servercerts',$lonhost);
                    271:     }
                    272:     my ($result,%returnhash);
                    273:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    274:         ($rep eq 'unknown_cmd')) {
                    275:         $result = $rep;
                    276:     } else {
                    277:         $result = 'ok';
                    278:         my @pairs=split(/\&/,$rep);
                    279:         foreach my $item (@pairs) {
                    280:             my ($key,$value)=split(/=/,$item,2);
                    281:             my $what = &unescape($key);
                    282:             $returnhash{$what}=&thaw_unescape($value);
                    283:         }
                    284:     }
                    285:     return ($result,\%returnhash);
                    286: }
                    287: 
1.993     raeburn   288: sub get_server_loncaparev {
1.1073    raeburn   289:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   290:     if (defined($lonhost)) {
                    291:         if (!defined(&hostname($lonhost))) {
                    292:             undef($lonhost);
                    293:         }
                    294:     }
                    295:     if (!defined($lonhost)) {
                    296:         if (defined(&domain($dom,'primary'))) {
                    297:             $lonhost=&domain($dom,'primary');
                    298:             if ($lonhost eq 'no_host') {
                    299:                 undef($lonhost);
                    300:             }
                    301:         }
                    302:     }
                    303:     if (defined($lonhost)) {
1.1073    raeburn   304:         my $cachetime = 12*3600;
                    305:         if (!$ignore_cache) {
                    306:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    307:             if (defined($cached)) {
                    308:                 return $loncaparev;
                    309:             }
                    310:         }
                    311:         my ($answer,$loncaparev);
                    312:         my @ids=&current_machine_ids();
                    313:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    314:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   315:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   316:                 $loncaparev = $1;
                    317:             }
                    318:         } else {
                    319:             $answer = &reply('serverloncaparev',$lonhost);
                    320:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    321:                 if ($caller eq 'loncron') {
1.1397    raeburn   322:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   323:                     my $protocol = $protocol{$lonhost};
                    324:                     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn   325:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   326:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   327:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   328:                     unless ($response->is_error()) {
                    329:                         my $content = $response->content;
1.1081    raeburn   330:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   331:                             $loncaparev = $1;
                    332:                         }
                    333:                     }
                    334:                 } else {
                    335:                     $loncaparev = $loncaparevs{$lonhost};
                    336:                 }
1.1081    raeburn   337:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   338:                 $loncaparev = $1;
                    339:             }
1.993     raeburn   340:         }
1.1073    raeburn   341:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   342:     }
                    343: }
                    344: 
1.1074    raeburn   345: sub get_server_homeID {
                    346:     my ($hostname,$ignore_cache,$caller) = @_;
                    347:     unless ($ignore_cache) {
                    348:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    349:         if (defined($cached)) {
                    350:             return $serverhomeID;
                    351:         }
                    352:     }
                    353:     my $cachetime = 12*3600;
                    354:     my $serverhomeID;
                    355:     if ($caller eq 'loncron') { 
                    356:         my @machine_ids = &machine_ids($hostname);
                    357:         foreach my $id (@machine_ids) {
                    358:             my $response = &reply('serverhomeID',$id);
                    359:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    360:                 $serverhomeID = $response;
                    361:                 last;
                    362:             }
                    363:         }
                    364:         if ($serverhomeID eq '') {
                    365:             $serverhomeID = $machine_ids[-1];
                    366:         }
                    367:     } else {
                    368:         $serverhomeID = $serverhomeIDs{$hostname};
                    369:     }
                    370:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    371: }
                    372: 
1.1121    raeburn   373: sub get_remote_globals {
                    374:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   375:     my ($result,%returnhash,%whatneeded);
                    376:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   377:         foreach my $what (sort(keys(%{$whathash}))) {
                    378:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   379:             my ($response,$cached);
1.1121    raeburn   380:             unless ($ignore_cache) {
1.1125    raeburn   381:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   382:             }
                    383:             if (defined($cached)) {
1.1125    raeburn   384:                 $returnhash{$what} = $response;
1.1121    raeburn   385:             } else {
1.1125    raeburn   386:                 $whatneeded{$what} = 1;
1.1121    raeburn   387:             }
                    388:         }
1.1125    raeburn   389:         if (keys(%whatneeded) == 0) {
                    390:             $result = 'ok';
                    391:         } else {
1.1121    raeburn   392:             my $requested = &freeze_escape(\%whatneeded);
                    393:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   394:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    395:                 ($rep eq 'unknown_cmd')) {
                    396:                 $result = $rep;
                    397:             } else {
                    398:                 $result = 'ok';
1.1121    raeburn   399:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   400:                 foreach my $item (@pairs) {
                    401:                     my ($key,$value)=split(/=/,$item,2);
                    402:                     my $what = &unescape($key);
                    403:                     my $hashid = $lonhost.'-'.$what;
                    404:                     $returnhash{$what}=&thaw_unescape($value);
                    405:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   406:                 }
                    407:             }
                    408:         }
                    409:     }
1.1125    raeburn   410:     return ($result,\%returnhash);
1.1121    raeburn   411: }
                    412: 
1.1124    raeburn   413: sub remote_devalidate_cache {
1.1241    raeburn   414:     my ($lonhost,$cachekeys) = @_;
                    415:     my $items;
                    416:     return unless (ref($cachekeys) eq 'ARRAY');
                    417:     my $cachestr = join('&',@{$cachekeys});
                    418:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   419:     return $response;
                    420: }
                    421: 
1.1510    raeburn   422: sub sign_lti {
1.1511    raeburn   423:     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
1.1510    raeburn   424:     my $chome;
                    425:     if (&domain($cdom) ne '') {
1.1511    raeburn   426:         if ($crsdef) {
1.1510    raeburn   427:             $chome = &homeserver($cnum,$cdom);
                    428:         } else {
                    429:             $chome = &domain($cdom,'primary');
                    430:         }
                    431:     }
                    432:     if ($cdom && $chome && ($chome ne 'no_host')) {
                    433:         if ((ref($paramsref) eq 'HASH') &&
                    434:             (ref($inforef) eq 'HASH')) {
                    435:             my $rep;
                    436:             if (grep { $_ eq $chome } &current_machine_ids()) {
                    437:                 # domain information is hosted on this machine
                    438:                 $rep =
1.1511    raeburn   439:                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
                    440:                                                      $context,$url,$ltinum,$keynum,
                    441:                                                      $perlvar{'lonVersion'},
                    442:                                                      $paramsref,$inforef);
                    443:                 if (ref($rep) eq 'HASH') {
1.1510    raeburn   444:                     return ('ok',$rep);
                    445:                 }
                    446:             } else {
                    447:                 my ($escurl,$params,$info);
                    448:                 $escurl = &escape($url);
                    449:                 if (ref($paramsref) eq 'HASH') {
                    450:                     $params = &freeze_escape($paramsref);
                    451:                 }
                    452:                 if (ref($inforef) eq 'HASH') {
                    453:                     $info = &freeze_escape($inforef);
                    454:                 }
1.1511    raeburn   455:                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
1.1510    raeburn   456:             }
                    457:             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
                    458:                 return ();
1.1511    raeburn   459:             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
                    460:                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
                    461:                 return ('ok',$rep);
1.1510    raeburn   462:             } else {
                    463:                 my %returnhash;
                    464:                 foreach my $item (split(/\&/,$rep)) {
                    465:                     my ($name,$value)=split(/\=/,$item);
                    466:                     $returnhash{&unescape($name)}=&thaw_unescape($value);
                    467:                 }
                    468:                 return('ok',\%returnhash);
                    469:             }
                    470:         } else {
                    471:             return ();
                    472:         }
                    473:     } else {
                    474:         return ();
                    475:         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
                    476:     }
                    477: }
                    478: 
1.1       albertel  479: # -------------------------------------------------- Non-critical communication
                    480: sub subreply {
                    481:     my ($cmd,$server)=@_;
1.838     albertel  482:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      483:     #
                    484:     #  With loncnew process trimming, there's a timing hole between lonc server
                    485:     #  process exit and the master server picking up the listen on the AF_UNIX
                    486:     #  socket.  In that time interval, a lock file will exist:
                    487: 
                    488:     my $lockfile=$peerfile.".lock";
                    489:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   490: 	sleep(0.1);
1.549     foxr      491:     }
                    492:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      493:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      494:     #
1.550     foxr      495:     #   We'll give the connection a few tries before abandoning it.  If
                    496:     #   connection is not possible, we'll con_lost back to the client.
                    497:     #   
                    498:     my $client;
                    499:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    500: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    501: 				      Type    => SOCK_STREAM,
                    502: 				      Timeout => 10);
1.869     albertel  503: 	if ($client) {
1.550     foxr      504: 	    last;		# Connected!
1.850     albertel  505: 	} else {
1.853     albertel  506: 	    &create_connection(&hostname($server),$server);
1.550     foxr      507: 	}
1.1289    damieng   508:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      509:     }
                    510:     my $answer;
                    511:     if ($client) {
1.704     albertel  512: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      513: 	$answer=<$client>;
                    514: 	if (!$answer) { $answer="con_lost"; }
                    515: 	chomp($answer);
                    516:     } else {
                    517: 	$answer = 'con_lost';	# Failed connection.
                    518:     }
1.1       albertel  519:     return $answer;
                    520: }
                    521: 
                    522: sub reply {
                    523:     my ($cmd,$server)=@_;
1.838     albertel  524:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  525:     my $answer=subreply($cmd,$server);
1.65      www       526:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396    raeburn   527:         my $logged = $cmd;
                    528:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    529:             my $subcmd = $1;
                    530:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    531:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462    raeburn   532:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
                    533:                 ($subcmd eq 'put')) {
1.1396    raeburn   534:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    535:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    536:                     splice(@rest,2,1,'Hidden');
                    537:                 } elsif ($subcmd eq 'passwd') {
                    538:                     splice(@rest,2,2,('Hidden','Hidden'));
                    539:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462    raeburn   540:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1396    raeburn   541:                     splice(@rest,3,1,'Hidden');
                    542:                 }
                    543:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    544:             }
                    545:         }
                    546:         &logthis("<font color=\"blue\">WARNING:".
                    547:                  " $logged to $server returned $answer</font>");
1.12      www       548:     }
1.1       albertel  549:     return $answer;
                    550: }
                    551: 
                    552: # ----------------------------------------------------------- Send USR1 to lonc
                    553: 
                    554: sub reconlonc {
1.891     albertel  555:     my ($lonid) = @_;
                    556:     if ($lonid) {
1.1295    raeburn   557:         my $hostname = &hostname($lonid);
1.891     albertel  558: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    559: 	if ($hostname && -e $peerfile) {
                    560: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    561: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    562: 					     Type    => SOCK_STREAM,
                    563: 					     Timeout => 10);
                    564: 	    if ($client) {
                    565: 		print $client ("reset_retries\n");
                    566: 		my $answer=<$client>;
                    567: 		#reset just this one.
                    568: 	    }
                    569: 	}
                    570: 	return;
                    571:     }
                    572: 
1.836     www       573:     &logthis("Trying to reconnect lonc");
1.1       albertel  574:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   575:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  576: 	my $loncpid=<$fh>;
                    577:         chomp($loncpid);
                    578:         if (kill 0 => $loncpid) {
                    579: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    580:             kill USR1 => $loncpid;
                    581:             sleep 1;
1.1295    raeburn   582:         } else {
1.12      www       583: 	    &logthis(
1.672     albertel  584:                "<font color=\"blue\">WARNING:".
1.12      www       585:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  586:         }
                    587:     } else {
1.836     www       588: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  589:     }
                    590: }
                    591: 
                    592: # ------------------------------------------------------ Critical communication
1.12      www       593: 
1.1       albertel  594: sub critical {
                    595:     my ($cmd,$server)=@_;
1.838     albertel  596:     unless (&hostname($server)) {
1.672     albertel  597:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       598:                " Critical message to unknown server ($server)</font>");
                    599:         return 'no_such_host';
                    600:     }
1.1       albertel  601:     my $answer=reply($cmd,$server);
                    602:     if ($answer eq 'con_lost') {
1.1295    raeburn   603: 	&reconlonc($server);
1.589     albertel  604: 	my $answer=reply($cmd,$server);
1.1       albertel  605:         if ($answer eq 'con_lost') {
                    606:             my $now=time;
                    607:             my $middlename=$cmd;
1.5       www       608:             $middlename=substr($middlename,0,16);
1.1       albertel  609:             $middlename=~s/\W//g;
                    610:             my $dfilename=
1.305     www       611:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    612:             $dumpcount++;
1.1       albertel  613:             {
1.448     albertel  614: 		my $dfh;
1.1359    raeburn   615: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  616: 		    print $dfh "$cmd\n"; 
                    617: 		    close($dfh);
                    618: 		}
1.1       albertel  619:             }
1.1288    damieng   620:             sleep 1;
1.1       albertel  621:             my $wcmd='';
                    622:             {
1.448     albertel  623: 		my $dfh;
1.1359    raeburn   624: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  625: 		    $wcmd=<$dfh>; 
                    626: 		    close($dfh);
                    627: 		}
1.1       albertel  628:             }
                    629:             chomp($wcmd);
1.7       www       630:             if ($wcmd eq $cmd) {
1.672     albertel  631: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       632:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  633:                 &logperm("D:$server:$cmd");
                    634: 	        return 'con_delayed';
                    635:             } else {
1.672     albertel  636:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       637:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  638:                 &logperm("F:$server:$cmd");
                    639:                 return 'con_failed';
                    640:             }
                    641:         }
                    642:     }
                    643:     return $answer;
1.405     albertel  644: }
                    645: 
1.755     albertel  646: # ------------------------------------------- check if return value is an error
                    647: 
                    648: sub error {
                    649:     my ($result) = @_;
1.756     albertel  650:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  651: 	if ($2 == 2) { return undef; }
                    652: 	return $1;
                    653:     }
                    654:     return undef;
                    655: }
                    656: 
1.783     albertel  657: sub convert_and_load_session_env {
                    658:     my ($lonidsdir,$handle)=@_;
                    659:     my @profile;
                    660:     {
1.917     albertel  661: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    662: 	if (!$opened) {
1.915     albertel  663: 	    return 0;
                    664: 	}
1.783     albertel  665: 	flock($idf,LOCK_SH);
                    666: 	@profile=<$idf>;
                    667: 	close($idf);
                    668:     }
                    669:     my %temp_env;
                    670:     foreach my $line (@profile) {
1.786     albertel  671: 	if ($line !~ m/=/) {
                    672: 	    return 0;
                    673: 	}
1.783     albertel  674: 	chomp($line);
                    675: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    676: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    677:     }
                    678:     unlink("$lonidsdir/$handle.id");
                    679:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    680: 	    0640)) {
                    681: 	%disk_env = %temp_env;
                    682: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    683: 	untie(%disk_env);
                    684:     }
1.786     albertel  685:     return 1;
1.783     albertel  686: }
                    687: 
1.374     www       688: # ------------------------------------------- Transfer profile into environment
1.780     albertel  689: my $env_loaded;
                    690: sub transfer_profile_to_env {
1.788     albertel  691:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    692:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       693: 
1.720     albertel  694:     if (!defined($lonidsdir)) {
                    695: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    696:     }
                    697:     if (!defined($handle)) {
                    698:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    699:     }
                    700: 
1.786     albertel  701:     my $convert;
                    702:     {
1.917     albertel  703:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    704: 	if (!$opened) {
1.915     albertel  705: 	    return;
                    706: 	}
1.786     albertel  707: 	flock($idf,LOCK_SH);
                    708: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    709: 		&GDBM_READER(),0640)) {
                    710: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    711: 	    untie(%disk_env);
                    712: 	} else {
                    713: 	    $convert = 1;
                    714: 	}
                    715:     }
                    716:     if ($convert) {
                    717: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    718: 	    &logthis("Failed to load session, or convert session.");
                    719: 	}
1.374     www       720:     }
1.783     albertel  721: 
1.786     albertel  722:     my %remove;
1.783     albertel  723:     while ( my $envname = each(%env) ) {
1.433     matthew   724:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    725:             if ($time < time-300) {
1.783     albertel  726:                 $remove{$key}++;
1.433     matthew   727:             }
                    728:         }
                    729:     }
1.783     albertel  730: 
1.619     albertel  731:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  732:     $env_loaded=1;
1.783     albertel  733:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   734:         &delenv($expired_key);
1.374     www       735:     }
1.1       albertel  736: }
                    737: 
1.916     albertel  738: # ---------------------------------------------------- Check for valid session 
                    739: sub check_for_valid_session {
1.1355    raeburn   740:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  741:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   742:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    743:     if ($name eq 'lonDAV') {
                    744:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    745:     } else {
                    746:         $lonidsdir=$r->dir_config('lonIDsDir');
                    747:         if ($name eq '') {
                    748:             $name = 'lonID';
                    749:         }
                    750:     }
                    751:     if ($name eq 'lonID') {
                    752:         $secure = 'lonSID';
1.1337    raeburn   753:         $linkname = 'lonLinkID';
                    754:         $pubname = 'lonPubID';
1.1378    raeburn   755:         if (exists($cookies{$secure})) {
                    756:             $lonid=$cookies{$secure};
                    757:         } elsif (exists($cookies{$name})) {
                    758:             $lonid=$cookies{$name};
1.1400    raeburn   759:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337    raeburn   760:             $lonid=$cookies{$linkname};
1.1378    raeburn   761:         } elsif (exists($cookies{$pubname})) {
                    762:             $lonid=$cookies{$pubname};
1.1337    raeburn   763:         }
1.1378    raeburn   764:     } else {
                    765:         $lonid=$cookies{$name};
1.1337    raeburn   766:     }
1.916     albertel  767:     return undef if (!$lonid);
                    768: 
                    769:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   770:     if (-l "$lonidsdir/$handle.id") {
                    771:         my $link = readlink("$lonidsdir/$handle.id");
                    772:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    773:             $handle = $1;
                    774:         }
1.1155    raeburn   775:     }
1.1355    raeburn   776:     if (!-e "$lonidsdir/$handle.id") {
                    777:         if ((ref($domref)) && ($name eq 'lonID') && 
                    778:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    779:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    780:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    781:                 $$domref = $possudom;
                    782:             }
                    783:         }
                    784:         return undef;
                    785:     }
1.916     albertel  786: 
1.917     albertel  787:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    788:     return undef if (!$opened);
1.916     albertel  789: 
                    790:     flock($idf,LOCK_SH);
                    791:     my %disk_env;
                    792:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    793: 	    &GDBM_READER(),0640)) {
                    794: 	return undef;	
                    795:     }
                    796: 
                    797:     if (!defined($disk_env{'user.name'})
                    798: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   799:         untie(%disk_env);
1.916     albertel  800: 	return undef;
                    801:     }
1.1245    raeburn   802: 
                    803:     if (ref($userhashref) eq 'HASH') {
                    804:         $userhashref->{'name'} = $disk_env{'user.name'};
                    805:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448    raeburn   806:         if ($disk_env{'request.role'}) {
                    807:             $userhashref->{'role'} = $disk_env{'request.role'};
                    808:         }
1.1361    raeburn   809:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   810:         if ($userhashref->{'lti'}) {
                    811:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    812:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    813:         }
1.1212    raeburn   814:     }
1.1394    raeburn   815:     untie(%disk_env);
1.1245    raeburn   816: 
1.916     albertel  817:     return $handle;
                    818: }
                    819: 
1.830     albertel  820: sub timed_flock {
                    821:     my ($file,$lock_type) = @_;
                    822:     my $failed=0;
                    823:     eval {
                    824: 	local $SIG{__DIE__}='DEFAULT';
                    825: 	local $SIG{ALRM}=sub {
                    826: 	    $failed=1;
                    827: 	    die("failed lock");
                    828: 	};
                    829: 	alarm(13);
                    830: 	flock($file,$lock_type);
                    831: 	alarm(0);
                    832:     };
                    833:     if ($failed) {
                    834: 	return undef;
                    835:     } else {
                    836: 	return 1;
                    837:     }
                    838: }
                    839: 
1.1392    raeburn   840: sub get_sessionfile_vars {
                    841:     my ($handle,$lonidsdir,$storearr) = @_;
                    842:     my %returnhash;
                    843:     unless (ref($storearr) eq 'ARRAY') {
                    844:         return %returnhash;
                    845:     }
                    846:     if (-l "$lonidsdir/$handle.id") {
                    847:         my $link = readlink("$lonidsdir/$handle.id");
                    848:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    849:             $handle = $1;
                    850:         }
                    851:     }
                    852:     if ((-e "$lonidsdir/$handle.id") &&
                    853:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    854:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    855:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    856:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    857:                 flock($idf,LOCK_SH);
                    858:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    859:                         &GDBM_READER(),0640)) {
                    860:                     foreach my $item (@{$storearr}) {
                    861:                         $returnhash{$item} = $disk_env{$item};
                    862:                     }
                    863:                     untie(%disk_env);
                    864:                 }
                    865:             }
                    866:         }
                    867:     }
                    868:     return %returnhash;
                    869: }
                    870: 
1.5       www       871: # ---------------------------------------------------------- Append Environment
                    872: 
                    873: sub appenv {
1.949     raeburn   874:     my ($newenv,$roles) = @_;
                    875:     if (ref($newenv) eq 'HASH') {
                    876:         foreach my $key (keys(%{$newenv})) {
                    877:             my $refused = 0;
                    878: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    879:                 $refused = 1;
                    880:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   881:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   882:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    883:                         $refused = 0;
                    884:                     }
                    885:                 }
                    886:             }
                    887:             if ($refused) {
                    888:                 &logthis("<font color=\"blue\">WARNING: ".
                    889:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    890:                          .'</font>');
                    891: 	        delete($newenv->{$key});
                    892:             } else {
                    893:                 $env{$key}=$newenv->{$key};
                    894:             }
                    895:         }
1.1376    raeburn   896:         my $lonids = $perlvar{'lonIDsDir'};
                    897:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    898:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    899:             if ($opened
                    900: 	        && &timed_flock($env_file,LOCK_EX)
                    901: 	        &&
                    902: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    903: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    904: 	        while (my ($key,$value) = each(%{$newenv})) {
                    905: 	            $disk_env{$key} = $value;
                    906: 	        }
                    907: 	        untie(%disk_env);
                    908:             }
1.35      www       909:         }
1.191     harris41  910:     }
1.56      www       911:     return 'ok';
                    912: }
                    913: # ----------------------------------------------------- Delete from Environment
                    914: 
                    915: sub delenv {
1.1104    raeburn   916:     my ($delthis,$regexp,$roles) = @_;
                    917:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    918:         my $refused = 1;
                    919:         if (ref($roles) eq 'ARRAY') {
                    920:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    921:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    922:                 $refused = 0;
                    923:             }
                    924:         }
                    925:         if ($refused) {
                    926:             &logthis("<font color=\"blue\">WARNING: ".
                    927:                      "Attempt to delete from environment ".$delthis);
                    928:             return 'error';
                    929:         }
1.56      www       930:     }
1.917     albertel  931:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    932:     if ($opened
1.915     albertel  933: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  934: 	&&
                    935: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    936: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  937: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   938: 	    if ($regexp) {
                    939:                 if ($key=~/^$delthis/) {
                    940:                     delete($env{$key});
                    941:                     delete($disk_env{$key});
                    942:                 } 
                    943:             } else {
                    944:                 if ($key=~/^\Q$delthis\E/) {
                    945: 		    delete($env{$key});
                    946: 		    delete($disk_env{$key});
                    947: 	        }
                    948:             }
1.448     albertel  949: 	}
1.783     albertel  950: 	untie(%disk_env);
1.5       www       951:     }
                    952:     return 'ok';
1.369     albertel  953: }
                    954: 
1.790     albertel  955: sub get_env_multiple {
                    956:     my ($name) = @_;
                    957:     my @values;
                    958:     if (defined($env{$name})) {
                    959:         # exists is it an array
                    960:         if (ref($env{$name})) {
                    961:             @values=@{ $env{$name} };
                    962:         } else {
                    963:             $values[0]=$env{$name};
                    964:         }
                    965:     }
                    966:     return(@values);
                    967: }
                    968: 
1.958     www       969: # ------------------------------------------------------------------- Locking
                    970: 
                    971: sub set_lock {
                    972:     my ($text)=@_;
                    973:     $locknum++;
                    974:     my $id=$$.'-'.$locknum;
                    975:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    976:              'session.lock.'.$id => $text});
                    977:     return $id;
                    978: }
                    979: 
                    980: sub get_locks {
                    981:     my $num=0;
                    982:     my %texts=();
                    983:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    984:        if ($lock=~/\w/) {
                    985:           $num++;
                    986:           $texts{$lock}=$env{'session.lock.'.$lock};
                    987:        }
                    988:    }
                    989:    return ($num,%texts);
                    990: }
                    991: 
                    992: sub remove_lock {
                    993:     my ($id)=@_;
                    994:     my $newlocks='';
                    995:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    996:        if (($lock=~/\w/) && ($lock ne $id)) {
                    997:           $newlocks.=','.$lock;
                    998:        }
                    999:     }
                   1000:     &appenv({'session.locks' => $newlocks});
                   1001:     &delenv('session.lock.'.$id);
                   1002: }
                   1003: 
                   1004: sub remove_all_locks {
                   1005:     my $activelocks=$env{'session.locks'};
                   1006:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                   1007:        if ($lock=~/\w/) {
                   1008:           &remove_lock($lock);
                   1009:        }
                   1010:     }
                   1011: }
                   1012: 
                   1013: 
1.369     albertel 1014: # ------------------------------------------ Find out current server userload
                   1015: sub userload {
                   1016:     my $numusers=0;
                   1017:     {
                   1018: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   1019: 	my $filename;
                   1020: 	my $curtime=time;
                   1021: 	while ($filename=readdir(LONIDS)) {
1.925     albertel 1022: 	    next if ($filename eq '.' || $filename eq '..');
                   1023: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn  1024:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel 1025: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel 1026: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel 1027: 	}
                   1028: 	closedir(LONIDS);
                   1029:     }
                   1030:     my $userloadpercent=0;
                   1031:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   1032:     if ($maxuserload) {
1.371     albertel 1033: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel 1034:     }
1.372     albertel 1035:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel 1036:     return $userloadpercent;
1.283     www      1037: }
                   1038: 
1.1       albertel 1039: # ------------------------------ Find server with least workload from spare.tab
1.11      www      1040: 
1.1       albertel 1041: sub spareserver {
1.1451    raeburn  1042:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel 1043:     my $spare_server;
1.370     albertel 1044:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel 1045:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                   1046:                                                      :  $userloadpercent;
1.1083    raeburn  1047:     my ($uint_dom,$remotesessions);
                   1048:     if (($udom ne '') && (&domain($udom) ne '')) {
1.1494    raeburn  1049:         my $uprimary_id = &domain($udom,'primary');
                   1050:         $uint_dom = &internet_dom($uprimary_id);
                   1051:         my %udomdefaults = &get_domain_defaults($udom);
1.1083    raeburn  1052:         $remotesessions = $udomdefaults{'remotesessions'};
                   1053:     }
1.1123    raeburn  1054:     my $spareshash = &this_host_spares($udom);
                   1055:     if (ref($spareshash) eq 'HASH') {
                   1056:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1057:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn  1058:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                   1059:                                              $try_server));
1.1123    raeburn  1060: 	        ($spare_server, $lowest_load) =
                   1061: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                   1062:             }
1.1083    raeburn  1063:         }
1.784     albertel 1064: 
1.1123    raeburn  1065:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                   1066: 
                   1067:         if (!$found_server) {
                   1068:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1069: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1070:                     next unless (&spare_can_host($udom,$uint_dom,
                   1071:                                                  $remotesessions,$try_server));
1.1123    raeburn  1072: 	            ($spare_server, $lowest_load) =
                   1073: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1074:                 }
                   1075: 	    }
                   1076:         }
1.784     albertel 1077:     }
                   1078: 
                   1079:     if (!$want_server_name) {
1.1001    raeburn  1080:         if (defined($spare_server)) {
                   1081:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1082:             if (defined($hostname)) {
1.1397    raeburn  1083:                 my $protocol = 'http';
                   1084:                 if ($protocol{$spare_server} eq 'https') {
                   1085:                     $protocol = $protocol{$spare_server};
                   1086:                 }
1.1494    raeburn  1087:                 my $alias = &use_proxy_alias($r,$spare_server);
1.1451    raeburn  1088:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn  1089: 	        $spare_server = $protocol.'://'.$hostname;
                   1090:             }
                   1091:         }
1.784     albertel 1092:     }
                   1093:     return $spare_server;
                   1094: }
                   1095: 
                   1096: sub compare_server_load {
1.1253    raeburn  1097:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1098: 
                   1099:     if ($required) {
                   1100:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1101:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1102:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1103:         if (($major eq '' && $minor eq '') ||
                   1104:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1105:             return ($spare_server,$lowest_load);
                   1106:         }
                   1107:     }
1.784     albertel 1108: 
                   1109:     my $loadans     = &reply('load',    $try_server);
                   1110:     my $userloadans = &reply('userload',$try_server);
                   1111: 
                   1112:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1113: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1114:     }
                   1115: 
                   1116:     my $load;
                   1117:     if ($loadans =~ /\d/) {
                   1118: 	if ($userloadans =~ /\d/) {
                   1119: 	    #both are numbers, pick the bigger one
                   1120: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1121: 		                              : $userloadans;
1.411     albertel 1122: 	} else {
1.784     albertel 1123: 	    $load = $loadans;
1.411     albertel 1124: 	}
1.784     albertel 1125:     } else {
                   1126: 	$load = $userloadans;
                   1127:     }
                   1128: 
                   1129:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1130: 	$spare_server = $try_server;
                   1131: 	$lowest_load  = $load;
1.370     albertel 1132:     }
1.784     albertel 1133:     return ($spare_server,$lowest_load);
1.202     matthew  1134: }
1.914     albertel 1135: 
                   1136: # --------------------------- ask offload servers if user already has a session
                   1137: sub find_existing_session {
                   1138:     my ($udom,$uname) = @_;
1.1123    raeburn  1139:     my $spareshash = &this_host_spares($udom);
                   1140:     if (ref($spareshash) eq 'HASH') {
                   1141:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1142:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1143:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1144:             }
                   1145:         }
                   1146:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1147:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1148:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1149:             }
                   1150:         }
1.914     albertel 1151:     }
                   1152:     return;
                   1153: }
                   1154: 
1.1411    raeburn  1155: sub delusersession {
                   1156:     my ($lonid,$udom,$uname) = @_;
                   1157:     my $uprimary_id = &domain($udom,'primary');
                   1158:     my $uintdom = &internet_dom($uprimary_id);
                   1159:     my $intdom = &internet_dom($lonid);
                   1160:     my $serverhomedom = &host_domain($lonid);
                   1161:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1162:         return &reply(join(':','delusersession',
                   1163:                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1164:     }
                   1165:     return;
                   1166: }
                   1167: 
1.1389    raeburn  1168: # check if user's browser sent load balancer cookie and server still has session
                   1169: # and is not overloaded.
                   1170: sub check_for_balancer_cookie {
                   1171:     my ($r,$update_mtime) = @_;
                   1172:     my ($otherserver,$cookie);
                   1173:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1174:     if (exists($cookies{'balanceID'})) {
                   1175:         my $balid = $cookies{'balanceID'};
                   1176:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1177:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1178:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1179:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1180:                 my ($possudom,$possuname) = ($1,$2);
                   1181:                 my $has_session = 0;
                   1182:                 if ((&domain($possudom) ne '') &&
                   1183:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1184:                     my $try_server;
                   1185:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1186:                     if ($opened) {
                   1187:                         flock($idf,LOCK_SH);
                   1188:                         while (my $line = <$idf>) {
                   1189:                             chomp($line);
                   1190:                             if (&hostname($line) ne '') {
                   1191:                                 $try_server = $line;
                   1192:                                 last;
                   1193:                             }
                   1194:                         }
                   1195:                         close($idf);
                   1196:                         if (($try_server) &&
                   1197:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1198:                             my $lowest_load = 30000;
                   1199:                             ($otherserver,$lowest_load) =
                   1200:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1201:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1202:                                 $has_session = 1;
                   1203:                             } else {
                   1204:                                 undef($otherserver);
                   1205:                             }
                   1206:                         }
                   1207:                     }
                   1208:                 }
                   1209:                 if ($has_session) {
                   1210:                     if ($update_mtime) {
                   1211:                         my $atime = my $mtime = time;
                   1212:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1213:                     }
                   1214:                 } else {
                   1215:                     unlink("$balancedir/$cookie.id");
                   1216:                 }
                   1217:             }
                   1218:         }
                   1219:     }
                   1220:     return ($otherserver,$cookie);
                   1221: }
                   1222: 
1.1431    raeburn  1223: sub updatebalcookie {
                   1224:     my ($cookie,$balancer,$lastentry)=@_;
                   1225:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1226:         my ($udom,$uname) = ($1,$2);
                   1227:         my $uprimary_id = &domain($udom,'primary');
                   1228:         my $uintdom = &internet_dom($uprimary_id);
                   1229:         my $intdom = &internet_dom($balancer);
                   1230:         my $serverhomedom = &host_domain($balancer);
                   1231:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1232:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1233:         }
                   1234:     }
                   1235:     return;
                   1236: }
                   1237: 
1.1389    raeburn  1238: sub delbalcookie {
                   1239:     my ($cookie,$balancer) =@_;
                   1240:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1241:         my ($udom,$uname) = ($1,$2);
                   1242:         my $uprimary_id = &domain($udom,'primary');
                   1243:         my $uintdom = &internet_dom($uprimary_id);
                   1244:         my $intdom = &internet_dom($balancer);
                   1245:         my $serverhomedom = &host_domain($balancer);
                   1246:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431    raeburn  1247:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389    raeburn  1248:         }
                   1249:     }
                   1250: }
                   1251: 
1.914     albertel 1252: # -------------------------------- ask if server already has a session for user
                   1253: sub has_user_session {
                   1254:     my ($lonid,$udom,$uname) = @_;
                   1255:     my $result = &reply(join(':','userhassession',
                   1256: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1257:     return 1 if ($result eq 'ok');
                   1258: 
                   1259:     return 0;
                   1260: }
                   1261: 
1.1076    raeburn  1262: # --------- determine least loaded server in a user's domain which allows login
                   1263: 
                   1264: sub choose_server {
1.1259    raeburn  1265:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1266:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1267:     my %servers = &get_servers($udom);
1.1076    raeburn  1268:     my $lowest_load = 30000;
1.1259    raeburn  1269:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1270:     if ($skiploadbal) {
                   1271:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1272:         unless (defined($cached)) {
                   1273:             my $cachetime = 60*60*24;
                   1274:             my %domconfig =
1.1494    raeburn  1275:                 &get_dom('configuration',['loadbalancing'],$udom);
1.1259    raeburn  1276:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1277:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1278:                                            $cachetime);
                   1279:             }
                   1280:         }
                   1281:     }
1.1076    raeburn  1282:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1283:         if ($skiploadbal) {
                   1284:             if (ref($balancers) eq 'HASH') {
                   1285:                 next if (exists($balancers->{$lonhost}));
                   1286:             }
1.1389    raeburn  1287:         }
1.1115    raeburn  1288:         my $loginvia;
                   1289:         if ($checkloginvia) {
                   1290:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1291:             if ($loginvia) {
                   1292:                 my ($server,$path) = split(/:/,$loginvia);
                   1293:                 ($login_host, $lowest_load) =
1.1253    raeburn  1294:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1295:                 if ($login_host eq $server) {
                   1296:                     $portal_path = $path;
1.1151    raeburn  1297:                     $isredirect = 1;
1.1116    raeburn  1298:                 }
                   1299:             } else {
                   1300:                 ($login_host, $lowest_load) =
1.1253    raeburn  1301:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1302:                 if ($login_host eq $lonhost) {
                   1303:                     $portal_path = '';
1.1151    raeburn  1304:                     $isredirect = ''; 
1.1116    raeburn  1305:                 }
                   1306:             }
                   1307:         } else {
1.1076    raeburn  1308:             ($login_host, $lowest_load) =
1.1253    raeburn  1309:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1310:         }
                   1311:     }
                   1312:     if ($login_host ne '') {
1.1116    raeburn  1313:         $hostname = &hostname($login_host);
1.1076    raeburn  1314:     }
1.1331    raeburn  1315:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1316: }
                   1317: 
1.1420    raeburn  1318: sub get_course_sessions {
                   1319:     my ($cnum,$cdom,$lastactivity) = @_;
                   1320:     my %servers = &internet_dom_servers($cdom);
                   1321:     my %returnhash;
                   1322:     foreach my $server (sort(keys(%servers))) {
                   1323:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1324:         my @pairs=split(/\&/,$rep);
                   1325:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1326:             foreach my $item (@pairs) {
                   1327:                 my ($key,$value)=split(/=/,$item,2);
                   1328:                 $key = &unescape($key);
                   1329:                 next if ($key =~ /^error: 2 /);
                   1330:                 if (exists($returnhash{$key})) {
                   1331:                     next if ($value < $returnhash{$key});
                   1332:                 }
                   1333:                 $returnhash{$key}=$value;
                   1334:             }
                   1335:         }
                   1336:     }
                   1337:     return %returnhash;
                   1338: }
                   1339: 
1.202     matthew  1340: # --------------------------------------------- Try to change a user's password
                   1341: 
                   1342: sub changepass {
1.799     raeburn  1343:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1344:     $currentpass = &escape($currentpass);
                   1345:     $newpass     = &escape($newpass);
1.1030    raeburn  1346:     my $lonhost = $perlvar{'lonHostID'};
                   1347:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1348: 		       $server);
                   1349:     if (! $answer) {
                   1350: 	&logthis("No reply on password change request to $server ".
                   1351: 		 "by $uname in domain $udom.");
                   1352:     } elsif ($answer =~ "^ok") {
                   1353:         &logthis("$uname in $udom successfully changed their password ".
                   1354: 		 "on $server.");
                   1355:     } elsif ($answer =~ "^pwchange_failure") {
                   1356: 	&logthis("$uname in $udom was unable to change their password ".
                   1357: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1358: 		 "or pwchange");
                   1359:     } elsif ($answer =~ "^non_authorized") {
                   1360:         &logthis("$uname in $udom did not get their password correct when ".
                   1361: 		 "attempting to change it on $server.");
                   1362:     } elsif ($answer =~ "^auth_mode_error") {
                   1363:         &logthis("$uname in $udom attempted to change their password despite ".
                   1364: 		 "not being locally or internally authenticated on $server.");
                   1365:     } elsif ($answer =~ "^unknown_user") {
                   1366:         &logthis("$uname in $udom attempted to change their password ".
                   1367: 		 "on $server but were unable to because $server is not ".
                   1368: 		 "their home server.");
                   1369:     } elsif ($answer =~ "^refused") {
                   1370: 	&logthis("$server refused to change $uname in $udom password because ".
                   1371: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1372:     } elsif ($answer =~ "invalid_client") {
                   1373:         &logthis("$server refused to change $uname in $udom password because ".
                   1374:                  "it was a reset by e-mail originating from an invalid server.");
1.1408    raeburn  1375:     } elsif ($answer =~ "^prioruse") {
                   1376:        &logthis("$server refused to change $uname in $udom password because ".
                   1377:                 "the password had been used before");
1.202     matthew  1378:     }
                   1379:     return $answer;
1.1       albertel 1380: }
                   1381: 
1.169     harris41 1382: # ----------------------- Try to determine user's current authentication scheme
                   1383: 
                   1384: sub queryauthenticate {
                   1385:     my ($uname,$udom)=@_;
1.456     albertel 1386:     my $uhome=&homeserver($uname,$udom);
1.1484    raeburn  1387:     if ((!$uhome) || ($uhome eq 'no_host')) {
1.456     albertel 1388: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1389: 	return 'no_host';
                   1390:     }
                   1391:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1392:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1393: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1394:     }
1.456     albertel 1395:     return $answer;
1.169     harris41 1396: }
                   1397: 
1.1       albertel 1398: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1399: 
1.1       albertel 1400: sub authenticate {
1.1073    raeburn  1401:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1402:     $upass=&escape($upass);
                   1403:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1404:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1405:     my $newhome;
1.836     www      1406:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1407: # Maybe the machine was offline and only re-appeared again recently?
                   1408:         &reconlonc();
                   1409: # One more
1.952     raeburn  1410: 	$uhome=&homeserver($uname,$udom,1);
                   1411:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1412:             if (defined(&domain($udom,'primary'))) {
                   1413:                 $newhome=&domain($udom,'primary');
                   1414:             }
                   1415:             if ($newhome ne '') {
                   1416:                 $uhome = $newhome;
                   1417:             }
                   1418:         }
1.836     www      1419: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1420: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1421: 	    return 'no_host';
                   1422:         }
1.1       albertel 1423:     }
1.1073    raeburn  1424:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1425:     if ($answer eq 'authorized') {
1.952     raeburn  1426:         if ($newhome) {
                   1427:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1428:             return 'no_account_on_host'; 
                   1429:         } else {
                   1430:             &logthis("User $uname at $udom authorized by $uhome");
                   1431:             return $uhome;
                   1432:         }
1.471     albertel 1433:     }
                   1434:     if ($answer eq 'non_authorized') {
                   1435: 	&logthis("User $uname at $udom rejected by $uhome");
1.1484    raeburn  1436: 	return 'no_host';
1.9       www      1437:     }
1.471     albertel 1438:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1439:     return 'no_host';
                   1440: }
                   1441: 
1.1491    raeburn  1442: sub can_switchserver {
                   1443:     my ($udom,$home) = @_;
                   1444:     my ($canswitch,@intdoms);
                   1445:     my $internet_names = &get_internet_names($home);
                   1446:     if (ref($internet_names) eq 'ARRAY') {
                   1447:         @intdoms = @{$internet_names};
                   1448:     }
                   1449:     my $uint_dom = &internet_dom(&domain($udom,'primary'));
                   1450:     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1451:         $canswitch = 1;
                   1452:     } else {
                   1453:          my $serverhomeID = &get_server_homeID(&hostname($home));
                   1454:          my $serverhomedom = &host_domain($serverhomeID);
                   1455:          my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1456:          my %udomdefaults = &get_domain_defaults($udom);
                   1457:          my $remoterev = &get_server_loncaparev('',$home);
                   1458:          $canswitch = &can_host_session($udom,$home,$remoterev,
                   1459:                                         $udomdefaults{'remotesessions'},
                   1460:                                         $defdomdefaults{'hostedsessions'});
                   1461:     }
                   1462:     return $canswitch;
                   1463: }
                   1464: 
1.1073    raeburn  1465: sub can_host_session {
1.1074    raeburn  1466:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1467:     my $canhost = 1;
1.1494    raeburn  1468:     my $host_idn = &internet_dom($lonhost);
1.1073    raeburn  1469:     if (ref($remotesessions) eq 'HASH') {
                   1470:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1471:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1472:                 $canhost = 0;
                   1473:             } else {
                   1474:                 $canhost = 1;
                   1475:             }
                   1476:         }
                   1477:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1478:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1479:                 $canhost = 1;
                   1480:             } else {
                   1481:                 $canhost = 0;
                   1482:             }
                   1483:         }
                   1484:         if ($canhost) {
                   1485:             if ($remotesessions->{'version'} ne '') {
                   1486:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1487:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1488:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1489:                         my $major = $1;
                   1490:                         my $minor = $2;
                   1491:                         if (($major < $reqmajor ) ||
                   1492:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1493:                             $canhost = 0;
                   1494:                         }
                   1495:                     } else {
                   1496:                         $canhost = 0;
                   1497:                     }
                   1498:                 }
                   1499:             }
                   1500:         }
                   1501:     }
                   1502:     if ($canhost) {
                   1503:         if (ref($hostedsessions) eq 'HASH') {
1.1494    raeburn  1504:             my $uprimary_id = &domain($udom,'primary');
                   1505:             my $uint_dom = &internet_dom($uprimary_id);
1.1073    raeburn  1506:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1507:                 if (($uint_dom ne '') && 
                   1508:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1509:                     $canhost = 0;
                   1510:                 } else {
                   1511:                     $canhost = 1;
                   1512:                 }
                   1513:             }
                   1514:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1515:                 if (($uint_dom ne '') && 
                   1516:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1517:                     $canhost = 1;
                   1518:                 } else {
                   1519:                     $canhost = 0;
                   1520:                 }
                   1521:             }
                   1522:         }
                   1523:     }
                   1524:     return $canhost;
                   1525: }
                   1526: 
1.1083    raeburn  1527: sub spare_can_host {
                   1528:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1529:     my $canhost=1;
1.1279    raeburn  1530:     my $try_server_hostname = &hostname($try_server);
                   1531:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1532:     my $serverhomedom = &host_domain($serverhomeID);
                   1533:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1534:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1535:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1536:             $canhost = 0;
                   1537:         }
                   1538:     }
1.1439    raeburn  1539:     if ($canhost) {
                   1540:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1541:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1542:                 unless (&shared_institution($udom,$try_server)) {
                   1543:                     $canhost = 0;
                   1544:                 }
                   1545:             }
                   1546:         }
                   1547:     }
1.1279    raeburn  1548:     if (($canhost) && ($uint_dom)) {
                   1549:         my @intdoms;
                   1550:         my $internet_names = &get_internet_names($try_server);
                   1551:         if (ref($internet_names) eq 'ARRAY') {
                   1552:             @intdoms = @{$internet_names};
                   1553:         }
                   1554:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1555:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1556:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1557:                                          $remotesessions,
                   1558:                                          $defdomdefaults{'hostedsessions'});
                   1559:         }
1.1083    raeburn  1560:     }
                   1561:     return $canhost;
                   1562: }
                   1563: 
1.1123    raeburn  1564: sub this_host_spares {
                   1565:     my ($dom) = @_;
1.1126    raeburn  1566:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1567:     my @hosts = &current_machine_ids();
                   1568:     foreach my $lonhost (@hosts) {
                   1569:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1570:             $dom_in_use = $dom;
                   1571:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1572:             last;
                   1573:         }
                   1574:     }
1.1126    raeburn  1575:     if ($dom_in_use ne '') {
                   1576:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1577:     }
                   1578:     if (ref($result) ne 'HASH') {
                   1579:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1580:         $dom_in_use = &host_domain($lonhost_in_use);
                   1581:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1582:         if (ref($result) ne 'HASH') {
                   1583:             $result = \%spareid;
                   1584:         }
                   1585:     }
                   1586:     return $result;
                   1587: }
                   1588: 
                   1589: sub spares_for_offload  {
                   1590:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1591:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1592:     if (defined($cached)) {
                   1593:         return $result;
                   1594:     } else {
1.1126    raeburn  1595:         my $cachetime = 60*60*24;
                   1596:         my %domconfig =
1.1494    raeburn  1597:             &get_dom('configuration',['usersessions'],$dom_in_use);
1.1126    raeburn  1598:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1599:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1600:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1601:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1602:                 }
                   1603:             }
                   1604:         }
                   1605:     }
1.1126    raeburn  1606:     return;
1.1123    raeburn  1607: }
                   1608: 
1.1129    raeburn  1609: sub get_lonbalancer_config {
                   1610:     my ($servers) = @_;
                   1611:     my ($currbalancer,$currtargets);
                   1612:     if (ref($servers) eq 'HASH') {
                   1613:         foreach my $server (keys(%{$servers})) {
                   1614:             my %what = (
                   1615:                          spareid => 1,
                   1616:                          perlvar => 1,
                   1617:                        );
                   1618:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1619:             if ($result eq 'ok') {
                   1620:                 if (ref($returnhash) eq 'HASH') {
                   1621:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1622:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1623:                             $currbalancer = $server;
                   1624:                             $currtargets = {};
                   1625:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1626:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1627:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1628:                                 }
                   1629:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1630:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1631:                                 }
                   1632:                             }
                   1633:                             last;
                   1634:                         }
                   1635:                     }
                   1636:                 }
                   1637:             }
                   1638:         }
                   1639:     }
                   1640:     return ($currbalancer,$currtargets);
                   1641: }
                   1642: 
                   1643: sub check_loadbalancing {
1.1331    raeburn  1644:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1645:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1646:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1647:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1648:     my @hosts = &current_machine_ids();
1.1494    raeburn  1649:     my $uprimary_id = &domain($udom,'primary');
                   1650:     my $uintdom = &internet_dom($uprimary_id);
                   1651:     my $intdom = &internet_dom($lonhost);
1.1129    raeburn  1652:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1653:     my $domneedscache;
1.1129    raeburn  1654:     my $cachetime = 60*60*24;
                   1655: 
                   1656:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1657:         $dom_in_use = $udom;
                   1658:         $homeintdom = 1;
                   1659:     } else {
                   1660:         $dom_in_use = $serverhomedom;
                   1661:     }
                   1662:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1663:     unless (defined($cached)) {
                   1664:         my %domconfig =
1.1494    raeburn  1665:             &get_dom('configuration',['loadbalancing'],$dom_in_use);
1.1129    raeburn  1666:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1667:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1668:         } else {
                   1669:             $domneedscache = $dom_in_use;
1.1129    raeburn  1670:         }
                   1671:     }
                   1672:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1673:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1674:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1675:         if ($is_balancer) {
                   1676:             if (ref($currrules) eq 'HASH') {
                   1677:                 if ($homeintdom) {
                   1678:                     if ($uname ne '') {
                   1679:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1680:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1681:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1682:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1683:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1684:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1685:                             }
                   1686:                         }
                   1687:                         if ($rule_in_effect eq '') {
                   1688:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1689:                             if ($userenv{'inststatus'} ne '') {
                   1690:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1691:                                 my ($othertitle,$usertypes,$types) =
                   1692:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1693:                                 if (ref($types) eq 'ARRAY') {
                   1694:                                     foreach my $type (@{$types}) {
                   1695:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1696:                                             if (exists($currrules->{$type})) {
                   1697:                                                 $rule_in_effect = $currrules->{$type};
                   1698:                                             }
                   1699:                                         }
                   1700:                                     }
                   1701:                                 }
                   1702:                             } else {
                   1703:                                 if (exists($currrules->{'default'})) {
                   1704:                                     $rule_in_effect = $currrules->{'default'};
                   1705:                                 }
                   1706:                             }
                   1707:                         }
                   1708:                     } else {
                   1709:                         if (exists($currrules->{'default'})) {
                   1710:                             $rule_in_effect = $currrules->{'default'};
                   1711:                         }
                   1712:                     }
                   1713:                 } else {
                   1714:                     if ($currrules->{'_LC_external'} ne '') {
                   1715:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1716:                     }
                   1717:                 }
                   1718:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1719:                                                        $uname,$udom);
                   1720:             }
                   1721:         }
                   1722:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1723:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1724:         unless (defined($cached)) {
                   1725:             my %domconfig =
1.1494    raeburn  1726:                 &get_dom('configuration',['loadbalancing'],$serverhomedom);
1.1129    raeburn  1727:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1728:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1729:             } else {
                   1730:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1731:             }
                   1732:         }
                   1733:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1734:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1735:                 &check_balancer_result($result,@hosts);
                   1736:             if ($is_balancer) {
1.1129    raeburn  1737:                 if (ref($currrules) eq 'HASH') {
                   1738:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1739:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1740:                     }
                   1741:                 }
                   1742:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1743:                                                        $uname,$udom);
                   1744:             }
                   1745:         } else {
                   1746:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1747:                 $is_balancer = 1;
                   1748:                 $offloadto = &this_host_spares($dom_in_use);
                   1749:             }
1.1307    raeburn  1750:             unless (defined($cached)) {
                   1751:                 $domneedscache = $serverhomedom;
                   1752:             }
1.1129    raeburn  1753:         }
                   1754:     } else {
                   1755:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1756:             $is_balancer = 1;
                   1757:             $offloadto = &this_host_spares($dom_in_use);
                   1758:         }
1.1307    raeburn  1759:         unless (defined($cached)) {
                   1760:             $domneedscache = $serverhomedom;
                   1761:         }
                   1762:     }
                   1763:     if ($domneedscache) {
                   1764:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1765:     }
1.1430    raeburn  1766:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176    raeburn  1767:         my $lowest_load = 30000;
                   1768:         if (ref($offloadto) eq 'HASH') {
                   1769:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1770:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1771:                     ($otherserver,$lowest_load) =
                   1772:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1773:                 }
1.1129    raeburn  1774:             }
1.1176    raeburn  1775:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1776: 
1.1176    raeburn  1777:             if (!$found_server) {
                   1778:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1779:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1780:                         ($otherserver,$lowest_load) =
                   1781:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1782:                     }
                   1783:                 }
                   1784:             }
                   1785:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1786:             if (@{$offloadto} == 1) {
                   1787:                 $otherserver = $offloadto->[0];
                   1788:             } elsif (@{$offloadto} > 1) {
                   1789:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1790:                     ($otherserver,$lowest_load) =
                   1791:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1792:                 }
                   1793:             }
                   1794:         }
1.1331    raeburn  1795:         unless ($caller eq 'login') {
                   1796:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1797:                 $is_balancer = 0;
                   1798:                 if ($uname ne '' && $udom ne '') {
                   1799:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1800:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1801:                                  'user.loadbalcheck.time' => time});
                   1802:                     }
1.1176    raeburn  1803:                 }
1.1129    raeburn  1804:             }
                   1805:         }
1.1430    raeburn  1806:     }
                   1807:     if (($is_balancer) && (!$homeintdom)) {
                   1808:         undef($setcookie);
1.1129    raeburn  1809:     }
1.1391    raeburn  1810:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1811: }
                   1812: 
1.1191    raeburn  1813: sub check_balancer_result {
                   1814:     my ($result,@hosts) = @_;
1.1391    raeburn  1815:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1816:     if (ref($result) eq 'HASH') {
                   1817:         if ($result->{'lonhost'} ne '') {
                   1818:             my $currbalancer = $result->{'lonhost'};
                   1819:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1820:                 $is_balancer = 1;
                   1821:                 $currtargets = $result->{'targets'};
                   1822:                 $currrules = $result->{'rules'};
                   1823:             }
1.1391    raeburn  1824:             $dom_balancers = $currbalancer;
1.1191    raeburn  1825:         } else {
1.1391    raeburn  1826:             if (keys(%{$result})) {
                   1827:                 foreach my $key (keys(%{$result})) {
                   1828:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1829:                         (ref($result->{$key}) eq 'HASH')) {
                   1830:                         $is_balancer = 1;
                   1831:                         $currrules = $result->{$key}{'rules'};
                   1832:                         $currtargets = $result->{$key}{'targets'};
                   1833:                         $setcookie = $result->{$key}{'cookie'};
                   1834:                         last;
                   1835:                     }
1.1191    raeburn  1836:                 }
1.1391    raeburn  1837:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1838:             }
                   1839:         }
                   1840:     }
1.1391    raeburn  1841:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1842: }
                   1843: 
1.1129    raeburn  1844: sub get_loadbalancer_targets {
                   1845:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1846:     my $offloadto;
1.1175    raeburn  1847:     if ($rule_in_effect eq 'none') {
                   1848:         return [$perlvar{'lonHostID'}];
                   1849:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1850:         $offloadto = $currtargets;
                   1851:     } else {
                   1852:         if ($rule_in_effect eq 'homeserver') {
                   1853:             my $homeserver = &homeserver($uname,$udom);
                   1854:             if ($homeserver ne 'no_host') {
                   1855:                 $offloadto = [$homeserver];
                   1856:             }
                   1857:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1858:             my %domconfig =
1.1494    raeburn  1859:                 &get_dom('configuration',['loadbalancing'],$udom);
1.1129    raeburn  1860:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1861:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1862:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1863:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1864:                     }
                   1865:                 }
                   1866:             } else {
1.1178    raeburn  1867:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1868:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1869:                 if (&hostname($remotebalancer) ne '') {
                   1870:                     $offloadto = [$remotebalancer];
                   1871:                 }
                   1872:             }
                   1873:         } elsif (&hostname($rule_in_effect) ne '') {
                   1874:             $offloadto = [$rule_in_effect];
                   1875:         }
                   1876:     }
                   1877:     return $offloadto;
                   1878: }
                   1879: 
1.1127    raeburn  1880: sub internet_dom_servers {
                   1881:     my ($dom) = @_;
                   1882:     my (%uniqservers,%servers);
                   1883:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1884:     my @machinedoms = &machine_domains($primaryserver);
                   1885:     foreach my $mdom (@machinedoms) {
                   1886:         my %currservers = %servers;
                   1887:         my %server = &get_servers($mdom);
                   1888:         %servers = (%currservers,%server);
                   1889:     }
                   1890:     my %by_hostname;
                   1891:     foreach my $id (keys(%servers)) {
                   1892:         push(@{$by_hostname{$servers{$id}}},$id);
                   1893:     }
                   1894:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1895:         if (@{$by_hostname{$hostname}} > 1) {
                   1896:             my $match = 0;
                   1897:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1898:                 if (&host_domain($id) eq $dom) {
                   1899:                     $uniqservers{$id} = $hostname;
                   1900:                     $match = 1;
                   1901:                 }
                   1902:             }
                   1903:             unless ($match) {
                   1904:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1905:             }
                   1906:         } else {
                   1907:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1908:         }
                   1909:     }
                   1910:     return %uniqservers;
                   1911: }
                   1912: 
1.1347    raeburn  1913: sub trusted_domains {
                   1914:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1915:     my ($trusted,$untrusted);
1.1347    raeburn  1916:     if (&domain($calldom) eq '') {
1.1349    raeburn  1917:         return ($trusted,$untrusted);
1.1347    raeburn  1918:     }
1.1395    raeburn  1919:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1920:         return ($trusted,$untrusted);
1.1347    raeburn  1921:     }
                   1922:     my $callprimary = &domain($calldom,'primary');
1.1494    raeburn  1923:     my $intcalldom = &internet_dom($callprimary);
1.1347    raeburn  1924:     if ($intcalldom eq '') {
1.1349    raeburn  1925:         return ($trusted,$untrusted);
1.1347    raeburn  1926:     }
                   1927: 
1.1494    raeburn  1928:     my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
1.1347    raeburn  1929:     unless (defined($cached)) {
1.1494    raeburn  1930:         my %domconfig = &get_dom('configuration',['trust'],$calldom);
                   1931:         &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1.1347    raeburn  1932:         $trustconfig = $domconfig{'trust'};
                   1933:     }
                   1934:     if (ref($trustconfig)) {
                   1935:         my (%possexc,%possinc,@allexc,@allinc); 
                   1936:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1937:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1938:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1939:             }
                   1940:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1941:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1942:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1943:             }
                   1944:         }
                   1945:         if (keys(%possexc)) {
                   1946:             if (keys(%possinc)) {
                   1947:                 foreach my $key (sort(keys(%possexc))) {
                   1948:                     next if ($key eq $intcalldom);
                   1949:                     unless ($possinc{$key}) {
                   1950:                         push(@allexc,$key);
                   1951:                     }
                   1952:                 }
                   1953:             } else {
                   1954:                 @allexc = sort(keys(%possexc));
                   1955:             }
                   1956:         }
                   1957:         if (keys(%possinc)) {
                   1958:             $possinc{$intcalldom} = 1;
                   1959:             @allinc = sort(keys(%possinc));
                   1960:         }
                   1961:         if ((@allexc > 0) || (@allinc > 0)) {
                   1962:             my %doms_by_intdom;
                   1963:             my %allintdoms = &all_host_intdom();
                   1964:             my %alldoms = &all_host_domain();
                   1965:             foreach my $key (%allintdoms) {
                   1966:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1967:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1968:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1969:                     }
                   1970:                 } else {
                   1971:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1972:                 }
                   1973:             }
                   1974:             foreach my $exc (@allexc) {
                   1975:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1976:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1977:                 }
                   1978:             }
                   1979:             foreach my $inc (@allinc) {
                   1980:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1981:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1982:                 }
                   1983:             }
                   1984:         }
                   1985:     }
1.1349    raeburn  1986:     return ($trusted,$untrusted);
1.1347    raeburn  1987: }
                   1988: 
                   1989: sub will_trust {
                   1990:     my ($cmdtype,$domain,$possdom) = @_;
                   1991:     return 1 if ($domain eq $possdom);
                   1992:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1993:     my $willtrust; 
                   1994:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1995:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1996:             $willtrust = 1;
                   1997:         }
                   1998:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1999:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   2000:             $willtrust = 1;
                   2001:         }
                   2002:     } else {
                   2003:         $willtrust = 1;
                   2004:     }
                   2005:     return $willtrust;
                   2006: }
                   2007: 
1.1       albertel 2008: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      2009: 
1.599     albertel 2010: my %homecache;
1.1       albertel 2011: sub homeserver {
1.230     stredwic 2012:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 2013:     my $index="$uname:$udom";
1.426     albertel 2014: 
1.599     albertel 2015:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 2016: 
                   2017:     my %servers = &get_servers($udom,'library');
                   2018:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 2019:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 2020: 		 exists($badServerCache{$tryserver}));
1.841     albertel 2021: 
                   2022: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   2023: 	if ($answer eq 'found') {
                   2024: 	    delete($badServerCache{$tryserver}); 
                   2025: 	    return $homecache{$index}=$tryserver;
                   2026: 	} elsif ($answer eq 'no_host') {
                   2027: 	    $badServerCache{$tryserver}=1;
                   2028: 	}
1.1       albertel 2029:     }    
                   2030:     return 'no_host';
1.70      www      2031: }
                   2032: 
1.1300    raeburn  2033: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      2034: 
                   2035: sub idget {
1.1300    raeburn  2036:     my ($udom,$idsref,$namespace)=@_;
1.70      www      2037:     my %returnhash=();
1.1300    raeburn  2038:     my @ids=(); 
                   2039:     if (ref($idsref) eq 'ARRAY') {
                   2040:         @ids = @{$idsref};
                   2041:     } else {
                   2042:         return %returnhash; 
                   2043:     }
                   2044:     if ($namespace eq '') {
                   2045:         $namespace = 'ids';
                   2046:     }
1.70      www      2047:     
1.841     albertel 2048:     my %servers = &get_servers($udom,'library');
                   2049:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  2050: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  2051: 	if ($namespace eq 'ids') {
                   2052: 	    $idlist=~tr/A-Z/a-z/;
                   2053: 	}
                   2054: 	my $reply;
                   2055: 	if ($namespace eq 'ids') {
                   2056: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   2057: 	} else {
                   2058: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   2059: 	}
1.841     albertel 2060: 	my @answer=();
                   2061: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   2062: 	    @answer=split(/\&/,$reply);
                   2063: 	}                    ;
                   2064: 	my $i;
                   2065: 	for ($i=0;$i<=$#ids;$i++) {
                   2066: 	    if ($answer[$i]) {
1.1299    raeburn  2067: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  2068: 	    }
1.841     albertel 2069: 	}
1.1300    raeburn  2070:     }
1.70      www      2071:     return %returnhash;
                   2072: }
                   2073: 
                   2074: # ------------------------------------- Find the IDs behind a list of usernames
                   2075: 
                   2076: sub idrget {
                   2077:     my ($udom,@unames)=@_;
                   2078:     my %returnhash=();
1.800     albertel 2079:     foreach my $uname (@unames) {
                   2080:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 2081:     }
1.70      www      2082:     return %returnhash;
                   2083: }
                   2084: 
1.1300    raeburn  2085: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      2086: 
                   2087: sub idput {
1.1300    raeburn  2088:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      2089:     my %servers=();
1.1300    raeburn  2090:     my %ids=();
                   2091:     my %byid = ();
                   2092:     if (ref($idsref) eq 'HASH') {
                   2093:         %ids=%{$idsref};
                   2094:     }
                   2095:     if ($namespace eq '') {
                   2096:         $namespace = 'ids'; 
                   2097:     }
1.800     albertel 2098:     foreach my $uname (keys(%ids)) {
                   2099: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  2100:         if ($uhom eq '') {
                   2101:             $uhom=&homeserver($uname,$udom);
                   2102:         }
1.70      www      2103:         if ($uhom ne 'no_host') {
1.800     albertel 2104:             my $esc_unam=&escape($uname);
1.1300    raeburn  2105:             if ($namespace eq 'ids') {
                   2106:                 my $id=&escape($ids{$uname});
                   2107:                 $id=~tr/A-Z/a-z/;
                   2108:                 my $esc_unam=&escape($uname);
                   2109:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      2110:             } else {
1.1300    raeburn  2111:                 my @currids = split(/,/,$ids{$uname});
                   2112:                 foreach my $id (@currids) {
                   2113:                     $byid{$uhom}{$id} .= $uname.',';
                   2114:                 }
                   2115:             }
                   2116:         }
                   2117:     }
                   2118:     if ($namespace eq 'clickers') {
                   2119:         foreach my $server (keys(%byid)) {
                   2120:             if (ref($byid{$server}) eq 'HASH') {
                   2121:                 foreach my $id (keys(%{$byid{$server}})) {
                   2122:                     $byid{$server} =~ s/,$//;
                   2123:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   2124:                 }
1.70      www      2125:             }
                   2126:         }
1.191     harris41 2127:     }
1.800     albertel 2128:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2129:         $servers{$server} =~ s/\&$//;
                   2130:         if ($namespace eq 'ids') {     
                   2131:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   2132:         } else {
                   2133:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   2134:         }
1.191     harris41 2135:     }
1.344     www      2136: }
                   2137: 
1.1300    raeburn  2138: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  2139: 
                   2140: sub iddel {
1.1300    raeburn  2141:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  2142:     my %result=();
1.1300    raeburn  2143:     my %ids=();
                   2144:     my %byid = ();
                   2145:     if (ref($idshashref) eq 'HASH') {
                   2146:         %ids=%{$idshashref};
                   2147:     } else {
1.1231    raeburn  2148:         return %result;
                   2149:     }
1.1300    raeburn  2150:     if ($namespace eq '') {
                   2151:         $namespace = 'ids';
                   2152:     }
1.1231    raeburn  2153:     my %servers=();
1.1300    raeburn  2154:     while (my ($id,$unamestr) = each(%ids)) {
                   2155:         if ($namespace eq 'ids') {
                   2156:             my $uhom = $uhome;
                   2157:             if ($uhom eq '') { 
                   2158:                 $uhom=&homeserver($unamestr,$udom);
                   2159:             }
                   2160:             if ($uhom ne 'no_host') {
                   2161:                 $servers{$uhom}.='&'.&escape($id);
                   2162:             }
                   2163:          } else {
                   2164:             my @curritems = split(/,/,$ids{$id});
                   2165:             foreach my $uname (@curritems) {
                   2166:                 my $uhom = $uhome;
                   2167:                 if ($uhom eq '') {
                   2168:                     $uhom=&homeserver($uname,$udom);
                   2169:                 }
                   2170:                 if ($uhom ne 'no_host') { 
                   2171:                     $byid{$uhom}{$id} .= $uname.',';
                   2172:                 }
                   2173:             }
1.1231    raeburn  2174:         }
1.1300    raeburn  2175:     }
                   2176:     if ($namespace eq 'clickers') {
                   2177:         foreach my $server (keys(%byid)) {
                   2178:             if (ref($byid{$server}) eq 'HASH') {
                   2179:                 foreach my $id (keys(%{$byid{$server}})) {
                   2180:                     $byid{$server}{$id} =~ s/,$//;
                   2181:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2182:                 }
1.1231    raeburn  2183:             }
                   2184:         }
                   2185:     }
                   2186:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2187:         $servers{$server} =~ s/\&$//;
                   2188:         if ($namespace eq 'ids') {
                   2189:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2190:         } elsif ($namespace eq 'clickers') {
                   2191:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2192:         }
1.1231    raeburn  2193:     }
                   2194:     return %result;
                   2195: }
                   2196: 
1.1300    raeburn  2197: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2198: 
                   2199: sub updateclickers {
                   2200:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2201:     my %clickers;
                   2202:     if (ref($idshashref) eq 'HASH') {
                   2203:         %clickers=%{$idshashref};
                   2204:     } else {
                   2205:         return;
                   2206:     }
                   2207:     my $items='';
                   2208:     foreach my $item (keys(%clickers)) {
                   2209:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2210:     }
                   2211:     $items=~s/\&$//;
                   2212:     my $request = "updateclickers:$udom:$action:$items";
                   2213:     if ($critical) {
                   2214:         return &critical($request,$uhome);
                   2215:     } else {
                   2216:         return &reply($request,$uhome);
                   2217:     }
                   2218: }
                   2219: 
1.1023    raeburn  2220: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2221: sub dump_dom {
1.1165    droeschl 2222:     my ($namespace, $udom, $regexp) = @_;
                   2223: 
                   2224:     $udom ||= $env{'user.domain'};
                   2225: 
                   2226:     return () unless $udom;
                   2227: 
                   2228:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2229: }
                   2230: 
1.1023    raeburn  2231: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2232: 
                   2233: sub get_dom {
1.1462    raeburn  2234:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267    raeburn  2235:     return if ($udom eq 'public');
1.806     raeburn  2236:     my $items='';
                   2237:     foreach my $item (@$storearr) {
                   2238:         $items.=&escape($item).'&';
                   2239:     }
                   2240:     $items=~s/\&$//;
1.860     raeburn  2241:     if (!$udom) {
                   2242:         $udom=$env{'user.domain'};
1.1267    raeburn  2243:         return if ($udom eq 'public');
1.860     raeburn  2244:         if (defined(&domain($udom,'primary'))) {
                   2245:             $uhome=&domain($udom,'primary');
                   2246:         } else {
1.874     albertel 2247:             undef($uhome);
1.860     raeburn  2248:         }
                   2249:     } else {
                   2250:         if (!$uhome) {
                   2251:             if (defined(&domain($udom,'primary'))) {
                   2252:                 $uhome=&domain($udom,'primary');
                   2253:             }
                   2254:         }
                   2255:     }
                   2256:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2257:         my $rep;
1.1442    raeburn  2258:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2259:             # domain information is hosted on this machine
1.1462    raeburn  2260:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344    raeburn  2261:         } else {
1.1462    raeburn  2262:             if ($encrypt) {
1.1442    raeburn  2263:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2264:             } else {
                   2265:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2266:             }
1.1344    raeburn  2267:         }
1.866     raeburn  2268:         my %returnhash;
1.875     albertel 2269:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2270:             return %returnhash;
                   2271:         }
1.806     raeburn  2272:         my @pairs=split(/\&/,$rep);
                   2273:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2274:             return @pairs;
                   2275:         }
                   2276:         my $i=0;
                   2277:         foreach my $item (@$storearr) {
                   2278:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2279:             $i++;
                   2280:         }
                   2281:         return %returnhash;
                   2282:     } else {
1.880     banghart 2283:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2284:     }
                   2285: }
                   2286: 
                   2287: # -------------------------------------------- put items in domain db files 
                   2288: 
                   2289: sub put_dom {
1.1462    raeburn  2290:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  2291:     if (!$udom) {
                   2292:         $udom=$env{'user.domain'};
                   2293:         if (defined(&domain($udom,'primary'))) {
                   2294:             $uhome=&domain($udom,'primary');
                   2295:         } else {
1.874     albertel 2296:             undef($uhome);
1.860     raeburn  2297:         }
                   2298:     } else {
                   2299:         if (!$uhome) {
                   2300:             if (defined(&domain($udom,'primary'))) {
                   2301:                 $uhome=&domain($udom,'primary');
                   2302:             }
                   2303:         }
                   2304:     } 
                   2305:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2306:         my $items='';
                   2307:         foreach my $item (keys(%$storehash)) {
                   2308:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2309:         }
                   2310:         $items=~s/\&$//;
1.1462    raeburn  2311:         if ($encrypt) {
1.1344    raeburn  2312:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2313:         } else {
                   2314:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2315:         }
1.806     raeburn  2316:     } else {
1.860     raeburn  2317:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2318:     }
                   2319: }
                   2320: 
1.1023    raeburn  2321: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2322: sub newput_dom {
1.1023    raeburn  2323:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2324:     my $result;
                   2325:     if (!$udom) {
                   2326:         $udom=$env{'user.domain'};
                   2327:     }
1.1023    raeburn  2328:     if ($udom) {
                   2329:         my $uname = &get_domainconfiguser($udom);
                   2330:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2331:     }
                   2332:     return $result;
                   2333: }
                   2334: 
1.1023    raeburn  2335: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2336: sub del_dom {
1.1023    raeburn  2337:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2338:     if (ref($storearr) eq 'ARRAY') {
                   2339:         if (!$udom) {
                   2340:             $udom=$env{'user.domain'};
                   2341:         }
1.1023    raeburn  2342:         if ($udom) {
                   2343:             my $uname = &get_domainconfiguser($udom); 
                   2344:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2345:         }
                   2346:     }
                   2347: }
                   2348: 
1.1481    raeburn  2349: sub store_dom {
1.1482    raeburn  2350:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481    raeburn  2351:     $$storehash{'ip'}=&get_requestor_ip();
                   2352:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2353:     my $namevalue='';
                   2354:     foreach my $key (keys(%{$storehash})) {
                   2355:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2356:     }
                   2357:     $namevalue=~s/\&$//;
                   2358:     if (grep { $_ eq $home } current_machine_ids()) {
                   2359:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2360:     } else {
                   2361:         if ($namespace eq 'private') {
                   2362:             return 'refused';
1.1482    raeburn  2363:         } elsif ($encrypt) {
                   2364:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481    raeburn  2365:         } else {
1.1482    raeburn  2366:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481    raeburn  2367:         }
                   2368:     }
                   2369: }
                   2370: 
1.1482    raeburn  2371: sub restore_dom {
                   2372:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2373:     my $answer;
                   2374:     if (grep { $_ eq $home } current_machine_ids()) {
                   2375:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2376:     } elsif ($namespace ne 'private') {
                   2377:         if ($encrypt) {
                   2378:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2379:         } else {
                   2380:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2381:         }
                   2382:     }
                   2383:     my %returnhash=();
                   2384:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
                   2385:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2386:         foreach my $line (split(/\&/,$answer)) {
                   2387:             my ($name,$value)=split(/\=/,$line);
                   2388:             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2389:         }
                   2390:         my $version;
                   2391:         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2392:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2393:                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2394:             }
                   2395:         }
                   2396:     }
                   2397:     return %returnhash;
                   2398: }
                   2399: 
1.1023    raeburn  2400: # ----------------------------------construct domainconfig user for a domain 
                   2401: sub get_domainconfiguser {
                   2402:     my ($udom) = @_;
                   2403:     return $udom.'-domainconfig';
                   2404: }
                   2405: 
1.837     raeburn  2406: sub retrieve_inst_usertypes {
                   2407:     my ($udom) = @_;
                   2408:     my (%returnhash,@order);
1.1494    raeburn  2409:     my %domdefs = &get_domain_defaults($udom);
1.989     raeburn  2410:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2411:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2412:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2413:     } else {
                   2414:         if (defined(&domain($udom,'primary'))) {
                   2415:             my $uhome=&domain($udom,'primary');
                   2416:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2417:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2418:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2419:                 return (\%returnhash,\@order);
                   2420:             }
                   2421:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2422:             my @pairs=split(/\&/,$hashitems);
                   2423:             foreach my $item (@pairs) {
                   2424:                 my ($key,$value)=split(/=/,$item,2);
                   2425:                 $key = &unescape($key);
                   2426:                 next if ($key =~ /^error: 2 /);
                   2427:                 $returnhash{$key}=&thaw_unescape($value);
                   2428:             }
                   2429:             my @esc_order = split(/\&/,$orderitems);
                   2430:             foreach my $item (@esc_order) {
                   2431:                 push(@order,&unescape($item));
                   2432:             }
                   2433:         } else {
1.1256    raeburn  2434:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2435:         }
1.1256    raeburn  2436:         return (\%returnhash,\@order);
1.837     raeburn  2437:     }
                   2438: }
                   2439: 
1.868     raeburn  2440: sub is_domainimage {
                   2441:     my ($url) = @_;
1.1468    raeburn  2442:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2443:         if (&domain($1) ne '') {
                   2444:             return '1';
                   2445:         }
                   2446:     }
                   2447:     return;
                   2448: }
                   2449: 
1.899     raeburn  2450: sub inst_directory_query {
                   2451:     my ($srch) = @_;
                   2452:     my $udom = $srch->{'srchdomain'};
                   2453:     my %results;
                   2454:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2455:     my $outcome;
1.899     raeburn  2456:     if ($homeserver ne '') {
1.1357    raeburn  2457:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2458:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2459:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2460:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2461:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2462:                     (($major == 2) && ($minor < 12))) {
                   2463:                     return;
                   2464:                 }
                   2465:             }
                   2466:         }
1.904     albertel 2467: 	my $queryid=&reply("querysend:instdirsearch:".
                   2468: 			   &escape($srch->{'srchby'}).':'.
                   2469: 			   &escape($srch->{'srchterm'}).':'.
                   2470: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2471: 	my $host=&hostname($homeserver);
                   2472: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2473: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2474: 	    return;
                   2475: 	}
                   2476: 	my $response = &get_query_reply($queryid);
                   2477: 	my $maxtries = 5;
                   2478: 	my $tries = 1;
                   2479: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2480: 	    $response = &get_query_reply($queryid);
                   2481: 	    $tries ++;
                   2482: 	}
                   2483: 
                   2484:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2485:             if ($response eq 'unavailable') {
                   2486:                 $outcome = $response;
                   2487:             } else {
                   2488:                 $outcome = 'ok';
                   2489:                 my @matches = split(/\n/,$response);
                   2490:                 foreach my $match (@matches) {
                   2491:                     my ($key,$value) = split(/=/,$match);
                   2492:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2493:                 }
1.899     raeburn  2494:             }
                   2495:         }
                   2496:     }
1.909     raeburn  2497:     return ($outcome,%results);
1.899     raeburn  2498: }
                   2499: 
                   2500: sub usersearch {
                   2501:     my ($srch) = @_;
                   2502:     my $dom = $srch->{'srchdomain'};
                   2503:     my %results;
                   2504:     my %libserv = &all_library();
                   2505:     my $query = 'usersearch';
                   2506:     foreach my $tryserver (keys(%libserv)) {
                   2507:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2508:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2509:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2510:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2511:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2512:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2513:                              (($major == 2) && ($minor < 12)));
                   2514:                 }
                   2515:             }
1.899     raeburn  2516:             my $host=&hostname($tryserver);
                   2517:             my $queryid=
1.911     raeburn  2518:                 &reply("querysend:".&escape($query).':'.
                   2519:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2520:                        &escape($srch->{'srchtype'}).':'.
                   2521:                        &escape($srch->{'srchterm'}),$tryserver);
                   2522:             if ($queryid !~/^\Q$host\E\_/) {
                   2523:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2524:                 next;
1.899     raeburn  2525:             }
                   2526:             my $reply = &get_query_reply($queryid);
                   2527:             my $maxtries = 1;
                   2528:             my $tries = 1;
                   2529:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2530:                 $reply = &get_query_reply($queryid);
                   2531:                 $tries ++;
                   2532:             }
                   2533:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2534:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2535:             } else {
1.911     raeburn  2536:                 my @matches;
                   2537:                 if ($reply =~ /\n/) {
                   2538:                     @matches = split(/\n/,$reply);
                   2539:                 } else {
                   2540:                     @matches = split(/\&/,$reply);
                   2541:                 }
1.899     raeburn  2542:                 foreach my $match (@matches) {
                   2543:                     my ($uname,$udom,%userhash);
1.911     raeburn  2544:                     foreach my $entry (split(/:/,$match)) {
                   2545:                         my ($key,$value) =
                   2546:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2547:                         $userhash{$key} = $value;
                   2548:                         if ($key eq 'username') {
                   2549:                             $uname = $value;
                   2550:                         } elsif ($key eq 'domain') {
                   2551:                             $udom = $value;
1.911     raeburn  2552:                         }
1.899     raeburn  2553:                     }
                   2554:                     $results{$uname.':'.$udom} = \%userhash;
                   2555:                 }
                   2556:             }
                   2557:         }
                   2558:     }
                   2559:     return %results;
                   2560: }
                   2561: 
1.912     raeburn  2562: sub get_instuser {
                   2563:     my ($udom,$uname,$id) = @_;
                   2564:     my $homeserver = &domain($udom,'primary');
                   2565:     my ($outcome,%results);
                   2566:     if ($homeserver ne '') {
                   2567:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2568:                            &escape($id).':'.&escape($udom),$homeserver);
                   2569:         my $host=&hostname($homeserver);
                   2570:         if ($queryid !~/^\Q$host\E\_/) {
                   2571:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2572:             return;
                   2573:         }
                   2574:         my $response = &get_query_reply($queryid);
                   2575:         my $maxtries = 5;
                   2576:         my $tries = 1;
                   2577:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2578:             $response = &get_query_reply($queryid);
                   2579:             $tries ++;
                   2580:         }
                   2581:         if (!&error($response) && $response ne 'refused') {
                   2582:             if ($response eq 'unavailable') {
                   2583:                 $outcome = $response;
                   2584:             } else {
                   2585:                 $outcome = 'ok';
                   2586:                 my @matches = split(/\n/,$response);
                   2587:                 foreach my $match (@matches) {
                   2588:                     my ($key,$value) = split(/=/,$match);
                   2589:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2590:                 }
                   2591:             }
                   2592:         }
                   2593:     }
                   2594:     my %userinfo;
                   2595:     if (ref($results{$uname}) eq 'HASH') {
                   2596:         %userinfo = %{$results{$uname}};
                   2597:     } 
                   2598:     return ($outcome,%userinfo);
                   2599: }
                   2600: 
1.1290    raeburn  2601: sub get_multiple_instusers {
                   2602:     my ($udom,$users,$caller) = @_;
                   2603:     my ($outcome,$results);
                   2604:     if (ref($users) eq 'HASH') {
                   2605:         my $count = keys(%{$users}); 
                   2606:         my $requested = &freeze_escape($users);
                   2607:         my $homeserver = &domain($udom,'primary');
                   2608:         if ($homeserver ne '') {
                   2609:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2610:             my $host=&hostname($homeserver);
                   2611:             if ($queryid !~/^\Q$host\E\_/) {
                   2612:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2613:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2614:                 return ($outcome,$results);
                   2615:             }
                   2616:             my $response = &get_query_reply($queryid);
                   2617:             my $maxtries = 5;
                   2618:             if ($count > 100) {
                   2619:                 $maxtries = 1+int($count/20);
                   2620:             }
                   2621:             my $tries = 1;
                   2622:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2623:                 $response = &get_query_reply($queryid);
                   2624:                 $tries ++;
                   2625:             }
                   2626:             if ($response eq '') {
                   2627:                 $results = {};
                   2628:                 foreach my $key (keys(%{$users})) {
                   2629:                     my ($uname,$id);
                   2630:                     if ($caller eq 'id') {
                   2631:                         $id = $key;
                   2632:                     } else {
                   2633:                         $uname = $key;
                   2634:                     }
                   2635:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2636:                     $outcome = $resp;
1.1290    raeburn  2637:                     if ($resp eq 'ok') {
                   2638:                         %{$results} = (%{$results}, %info);
                   2639:                     } else {
                   2640:                         last;
                   2641:                     }
                   2642:                 }
                   2643:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2644:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2645:                     $outcome = $response;
                   2646:                 } else {
1.1291    raeburn  2647:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2648:                     if ($outcome eq 'ok') {
                   2649:                         $results = &thaw_unescape($userdata); 
                   2650:                     }
                   2651:                 }
                   2652:             }
                   2653:         }
                   2654:     }
                   2655:     return ($outcome,$results);
                   2656: }
                   2657: 
1.912     raeburn  2658: sub inst_rulecheck {
1.923     raeburn  2659:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2660:     my %returnhash;
                   2661:     if ($udom ne '') {
                   2662:         if (ref($rules) eq 'ARRAY') {
                   2663:             @{$rules} = map {&escape($_);} (@{$rules});
                   2664:             my $rulestr = join(':',@{$rules});
                   2665:             my $homeserver=&domain($udom,'primary');
                   2666:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2667:                 my $response;
                   2668:                 if ($item eq 'username') {                
                   2669:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2670:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2671:                                               $homeserver));
1.923     raeburn  2672:                 } elsif ($item eq 'id') {
                   2673:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2674:                                               ':'.&escape($id).':'.$rulestr,
                   2675:                                               $homeserver));
1.945     raeburn  2676:                 } elsif ($item eq 'selfcreate') {
                   2677:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2678:                                                &escape($udom).':'.&escape($uname).
                   2679:                                               ':'.$rulestr,$homeserver));
1.1484    raeburn  2680:                 } elsif ($item eq 'unamemap') {
                   2681:                     $response=&unescape(&reply('instunamemapcheck:'.
                   2682:                                                &escape($udom).':'.&escape($uname).
                   2683:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2684:                 }
1.912     raeburn  2685:                 if ($response ne 'refused') {
                   2686:                     my @pairs=split(/\&/,$response);
                   2687:                     foreach my $item (@pairs) {
                   2688:                         my ($key,$value)=split(/=/,$item,2);
                   2689:                         $key = &unescape($key);
                   2690:                         next if ($key =~ /^error: 2 /);
                   2691:                         $returnhash{$key}=&thaw_unescape($value);
                   2692:                     }
                   2693:                 }
                   2694:             }
                   2695:         }
                   2696:     }
                   2697:     return %returnhash;
                   2698: }
                   2699: 
                   2700: sub inst_userrules {
1.923     raeburn  2701:     my ($udom,$check) = @_;
1.912     raeburn  2702:     my (%ruleshash,@ruleorder);
                   2703:     if ($udom ne '') {
                   2704:         my $homeserver=&domain($udom,'primary');
                   2705:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2706:             my $response;
                   2707:             if ($check eq 'id') {
                   2708:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2709:                                  $homeserver);
1.943     raeburn  2710:             } elsif ($check eq 'email') {
                   2711:                 $response=&reply('instemailrules:'.&escape($udom),
                   2712:                                  $homeserver);
1.1484    raeburn  2713:             } elsif ($check eq 'unamemap') {
                   2714:                 $response=&reply('unamemaprules:'.&escape($udom),
                   2715:                                  $homeserver); 
1.923     raeburn  2716:             } else {
                   2717:                 $response=&reply('instuserrules:'.&escape($udom),
                   2718:                                  $homeserver);
                   2719:             }
1.912     raeburn  2720:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2721:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2722:                 ($response ne 'no_such_host')) {
                   2723:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2724:                 my @pairs=split(/\&/,$hashitems);
                   2725:                 foreach my $item (@pairs) {
                   2726:                     my ($key,$value)=split(/=/,$item,2);
                   2727:                     $key = &unescape($key);
                   2728:                     next if ($key =~ /^error: 2 /);
                   2729:                     $ruleshash{$key}=&thaw_unescape($value);
                   2730:                 }
                   2731:                 my @esc_order = split(/\&/,$orderitems);
                   2732:                 foreach my $item (@esc_order) {
                   2733:                     push(@ruleorder,&unescape($item));
                   2734:                 }
                   2735:             }
                   2736:         }
                   2737:     }
                   2738:     return (\%ruleshash,\@ruleorder);
                   2739: }
                   2740: 
1.976     raeburn  2741: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2742: 
                   2743: sub get_domain_defaults {
1.1240    raeburn  2744:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2745:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2746:     my $cachetime = 60*60*24;
1.1240    raeburn  2747:     unless ($ignore_cache) {
                   2748:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2749:         if (defined($cached)) {
                   2750:             if (ref($result) eq 'HASH') {
                   2751:                 return %{$result};
                   2752:             }
1.943     raeburn  2753:         }
                   2754:     }
                   2755:     my %domdefaults;
                   2756:     my %domconfig =
1.1494    raeburn  2757:          &get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2758:                                   'requestcourses','inststatus',
1.1183    raeburn  2759:                                   'coursedefaults','usersessions',
1.1517    raeburn  2760:                                   'requestauthor','authordefaults',
                   2761:                                   'selfenrollment','coursecategories',
                   2762:                                   'ssl','autoenroll','trust',
                   2763:                                   'helpsettings','wafproxy',
1.1520    raeburn  2764:                                   'ltisec','toolsec','privacy'],$domain);
1.1305    raeburn  2765:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2766:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2767:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2768:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2769:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2770:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2771:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2772:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1492    raeburn  2773:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
                   2774:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1340    raeburn  2775:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2776:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2777:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484    raeburn  2778:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2779:     } else {
                   2780:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2781:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2782:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2783:     }
1.976     raeburn  2784:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2785:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2786:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2787:         } else {
                   2788:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2789:         }
1.1521    raeburn  2790:         my @usertools = ('aboutme','blog','webdav','portfolio','portaccess');
1.976     raeburn  2791:         foreach my $item (@usertools) {
                   2792:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2793:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2794:             }
                   2795:         }
1.1229    raeburn  2796:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2797:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2798:         }
1.976     raeburn  2799:     }
1.985     raeburn  2800:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2801:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2802:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2803:         }
                   2804:     }
1.1183    raeburn  2805:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2806:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2807:     }
1.1517    raeburn  2808:     if (ref($domconfig{'authordefaults'}) eq 'HASH') {
1.1527    raeburn  2809:         foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors','archive') {
1.1517    raeburn  2810:             if ($item eq 'editors') {
                   2811:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
                   2812:                     $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
                   2813:                 }
                   2814:             } else {
                   2815:                 $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
                   2816:             }
                   2817:         }
                   2818:     }
1.989     raeburn  2819:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2820:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2821:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2822:         }
                   2823:     }
1.1047    raeburn  2824:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2825:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2826:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476    raeburn  2827:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277    raeburn  2828:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2829:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2830:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2831:         }
1.1529    raeburn  2832:         if (ref($domconfig{'coursedefaults'}{'crseditors'}) eq 'ARRAY') {
                   2833:             $domdefaults{'crseditors'}=join(',',@{$domconfig{'coursedefaults'}{'crseditors'}});
                   2834:         }
1.1254    raeburn  2835:         foreach my $type (@coursetypes) {
                   2836:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2837:                 unless ($type eq 'community') {
                   2838:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2839:                 }
                   2840:             }
                   2841:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2842:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2843:             }
1.1514    raeburn  2844:             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
                   2845:                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
                   2846:             }
1.1277    raeburn  2847:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2848:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2849:                     $domdefaults{$type.'postsubtimeout'} = 
                   2850:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2851:                 }
                   2852:             }
1.1508    raeburn  2853:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
                   2854:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
                   2855:             } else {
                   2856:                 $domdefaults{$type.'domexttool'} = 1;
                   2857:             }
                   2858:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
                   2859:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
                   2860:             } else {
                   2861:                 $domdefaults{$type.'exttool'} = 0;
                   2862:             }
1.1520    raeburn  2863:             if (ref($domconfig{'coursedefaults'}{'crsauthor'}) eq 'HASH') {
                   2864:                 $domdefaults{$type.'crsauthor'} = $domconfig{'coursedefaults'}{'crsauthor'}{$type};
                   2865:             } else {
                   2866:                 $domdefaults{$type.'crsauthor'} = 1;
                   2867:             }
1.1230    raeburn  2868:         }
1.1286    raeburn  2869:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2870:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2871:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2872:                 if (@clonecodes) {
                   2873:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2874:                 }
                   2875:             }
                   2876:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2877:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2878:         }
1.1356    raeburn  2879:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2880:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480    raeburn  2881:         }
                   2882:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2883:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2884:         }
1.1047    raeburn  2885:     }
1.1073    raeburn  2886:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2887:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2888:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2889:         }
                   2890:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2891:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2892:         }
1.1279    raeburn  2893:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2894:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2895:         }
1.1440    raeburn  2896:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439    raeburn  2897:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2898:         }
1.1073    raeburn  2899:     }
1.1254    raeburn  2900:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2901:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2902:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2903:                             'approval','limit');
                   2904:             foreach my $type (@coursetypes) {
                   2905:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2906:                     my @mgrdc = ();
                   2907:                     foreach my $item (@settings) {
                   2908:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2909:                             push(@mgrdc,$item);
                   2910:                         }
                   2911:                     }
                   2912:                     if (@mgrdc) {
                   2913:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2914:                     }
                   2915:                 }
                   2916:             }
                   2917:         }
                   2918:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2919:             foreach my $type (@coursetypes) {
                   2920:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2921:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2922:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2923:                     }
                   2924:                 }
                   2925:             }
                   2926:         }
                   2927:     }
1.1258    raeburn  2928:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2929:         $domdefaults{'catauth'} = 'std';
                   2930:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2931:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2932:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2933:         }
                   2934:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2935:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2936:         }
                   2937:     }
1.1315    raeburn  2938:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2939:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2940:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2941:         }
1.1338    raeburn  2942:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2943:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2944:         }
                   2945:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2946:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2947:         }
                   2948:     }
1.1320    raeburn  2949:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2950:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2951:         foreach my $prefix (@prefixes) {
                   2952:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2953:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2954:             }
                   2955:         }
                   2956:     }
1.1314    raeburn  2957:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2958:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477    raeburn  2959:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314    raeburn  2960:     }
1.1332    raeburn  2961:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2962:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2963:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2964:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2965:         }
                   2966:     }
1.1434    raeburn  2967:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449    raeburn  2968:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434    raeburn  2969:             if ($domconfig{'wafproxy'}{$item}) {
                   2970:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2971:             }
                   2972:         }
1.1482    raeburn  2973:     }
                   2974:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2975:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2976:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2977:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2978:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2979:         }
                   2980:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2981:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
1.1504    raeburn  2982:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2983:             }
                   2984:         }
1.1523    raeburn  2985:         if (ref($domconfig{'ltisec'}{'suggested'}) eq 'HASH') {
                   2986:             my %suggestions = %{$domconfig{'ltisec'}{'suggested'}};
                   2987:             foreach my $item (keys(%{$domconfig{'ltisec'}{'suggested'}})) {
                   2988:                 unless (ref($domconfig{'ltisec'}{'suggested'}{$item}) eq 'HASH') {
                   2989:                     delete($suggestions{$item});
                   2990:                 }
                   2991:             }
                   2992:             if (keys(%suggestions)) {
                   2993:                 $domdefaults{'linkprotsuggested'} = \%suggestions;
                   2994:             }
                   2995:         }
1.1504    raeburn  2996:     }
                   2997:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   2998:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
                   2999:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
                   3000:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
                   3001:         }
                   3002:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
                   3003:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
                   3004:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
1.1482    raeburn  3005:             }
                   3006:         }
                   3007:     }
1.1512    raeburn  3008:     if (ref($domconfig{'privacy'}) eq 'HASH') {
                   3009:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
                   3010:             foreach my $domtype ('instdom','extdom') {
                   3011:                 if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
                   3012:                     foreach my $roletype ('domain','author','course','community') {
                   3013:                         if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
                   3014:                             $domdefaults{'userapprovals'} = 1;
                   3015:                             last;
                   3016:                         }
                   3017:                     }
                   3018:                 }
                   3019:                 last if ($domdefaults{'userapprovals'});
                   3020:             }
                   3021:         }
1.1534  ! raeburn  3022:         if (ref($domconfig{'privacy'}{'othdom'}) eq 'HASH') {
        !          3023:             $domdefaults{'privacyothdom'} = $domconfig{'privacy'}{'othdom'};
        !          3024:         }
1.1512    raeburn  3025:     }
1.1219    raeburn  3026:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  3027:     return %domdefaults;
                   3028: }
                   3029: 
1.1412    raeburn  3030: sub get_dom_cats {
                   3031:     my ($dom) = @_;
                   3032:     return unless (&domain($dom));
                   3033:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   3034:     unless (defined($cached)) {
                   3035:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   3036:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   3037:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   3038:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   3039:             } else {
                   3040:                 $cats = {};
                   3041:             }
                   3042:         } else {
                   3043:             $cats = {};
                   3044:         }
1.1494    raeburn  3045:         &do_cache_new('cats',$dom,$cats,3600);
1.1412    raeburn  3046:     }
1.1413    raeburn  3047:     return $cats;
                   3048: }
                   3049: 
                   3050: sub get_dom_instcats {
                   3051:     my ($dom) = @_;
                   3052:     return unless (&domain($dom));
                   3053:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   3054:     unless (defined($cached)) {
                   3055:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   3056:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   3057:         if ($totcodes > 0) {
                   3058:             my $caller = 'global';
                   3059:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   3060:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   3061:                 $instcats = {
1.1503    raeburn  3062:                                 totcodes => $totcodes,
1.1413    raeburn  3063:                                 codes => \%codes,
                   3064:                                 codetitles => \@codetitles,
                   3065:                                 cat_titles => \%cat_titles,
                   3066:                                 cat_order => \%cat_order,
                   3067:                             };
                   3068:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   3069:             }
                   3070:         }
                   3071:     }
                   3072:     return $instcats;
                   3073: }
                   3074: 
                   3075: sub retrieve_instcodes {
                   3076:     my ($coursecodes,$dom) = @_;
                   3077:     my $totcodes;
                   3078:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   3079:     foreach my $course (keys(%courses)) {
                   3080:         if (ref($courses{$course}) eq 'HASH') {
                   3081:             if ($courses{$course}{'inst_code'} ne '') {
                   3082:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   3083:                 $totcodes ++;
                   3084:             }
                   3085:         }
                   3086:     }
                   3087:     return $totcodes;
1.1412    raeburn  3088: }
                   3089: 
1.1311    raeburn  3090: sub course_portal_url {
1.1451    raeburn  3091:     my ($cnum,$cdom,$r) = @_;
1.1311    raeburn  3092:     my $chome = &homeserver($cnum,$cdom);
                   3093:     my $hostname = &hostname($chome);
                   3094:     my $protocol = $protocol{$chome};
                   3095:     $protocol = 'http' if ($protocol ne 'https');
                   3096:     my %domdefaults = &get_domain_defaults($cdom);
                   3097:     my $firsturl;
                   3098:     if ($domdefaults{'portal_def'}) {
                   3099:         $firsturl = $domdefaults{'portal_def'};
                   3100:     } else {
1.1494    raeburn  3101:         my $alias = &use_proxy_alias($r,$chome);
1.1451    raeburn  3102:         $hostname = $alias if ($alias ne '');
1.1311    raeburn  3103:         $firsturl = $protocol.'://'.$hostname;
                   3104:     }
                   3105:     return $firsturl;
                   3106: }
                   3107: 
1.1492    raeburn  3108: sub url_prefix {
                   3109:     my ($r,$dom,$home,$context) = @_;
                   3110:     my $prefix;
                   3111:     my %domdefs = &get_domain_defaults($dom);
                   3112:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
                   3113:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
                   3114:             $prefix = $1;
                   3115:         }
                   3116:     }
                   3117:     if ($prefix eq '') {
                   3118:         my $hostname = &hostname($home);
                   3119:         my $protocol = $protocol{$home};
                   3120:         $protocol = 'http' if ($protocol{$home} ne 'https');
                   3121:         my $alias = &use_proxy_alias($r,$home);
                   3122:         $hostname = $alias if ($alias ne '');
                   3123:         $prefix = $protocol.'://'.$hostname;
                   3124:     }
                   3125:     return $prefix;
                   3126: }
                   3127: 
1.1407    raeburn  3128: # --------------------------------------------- Get domain config for passwords
                   3129: 
                   3130: sub get_passwdconf {
                   3131:     my ($dom) = @_;
                   3132:     my (%passwdconf,$gotconf,$lookup);
                   3133:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   3134:     if (defined($cached)) {
                   3135:         if (ref($result) eq 'HASH') {
                   3136:             %passwdconf = %{$result};
                   3137:             $gotconf = 1;
                   3138:         }
                   3139:     }
                   3140:     unless ($gotconf) {
                   3141:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   3142:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   3143:             %passwdconf = %{$domconfig{'passwords'}};
                   3144:         }
                   3145:         my $cachetime = 24*60*60;
                   3146:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   3147:     }
                   3148:     return %passwdconf;
                   3149: }
                   3150: 
1.344     www      3151: # --------------------------------------------------- Assign a key to a student
                   3152: 
                   3153: sub assign_access_key {
1.364     www      3154: #
                   3155: # a valid key looks like uname:udom#comments
                   3156: # comments are being appended
                   3157: #
1.498     www      3158:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   3159:     $kdom=
1.620     albertel 3160:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      3161:     $knum=
1.620     albertel 3162:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      3163:     $cdom=
1.620     albertel 3164:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3165:     $cnum=
1.620     albertel 3166:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3167:     $udom=$env{'user.name'} unless (defined($udom));
                   3168:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      3169:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      3170:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 3171:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      3172:                                                   # assigned to this person
                   3173:                                                   # - this should not happen,
1.345     www      3174:                                                   # unless something went wrong
                   3175:                                                   # the first time around
                   3176: # ready to assign
1.364     www      3177:         $logentry=$1.'; '.$logentry;
1.496     www      3178:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      3179:                                                  $kdom,$knum) eq 'ok') {
1.345     www      3180: # key now belongs to user
1.346     www      3181: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      3182:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  3183:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      3184:                 return 'ok';
                   3185:             } else {
                   3186:                 return 
                   3187:   'error: Count not permanently assign key, will need to be re-entered later.';
                   3188: 	    }
                   3189:         } else {
                   3190:             return 'error: Could not assign key, try again later.';
                   3191:         }
1.364     www      3192:     } elsif (!$existing{$ckey}) {
1.345     www      3193: # the key does not exist
                   3194: 	return 'error: The key does not exist';
                   3195:     } else {
                   3196: # the key is somebody else's
                   3197: 	return 'error: The key is already in use';
                   3198:     }
1.344     www      3199: }
                   3200: 
1.364     www      3201: # ------------------------------------------ put an additional comment on a key
                   3202: 
                   3203: sub comment_access_key {
                   3204: #
                   3205: # a valid key looks like uname:udom#comments
                   3206: # comments are being appended
                   3207: #
                   3208:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   3209:     $cdom=
1.620     albertel 3210:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      3211:     $cnum=
1.620     albertel 3212:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      3213:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   3214:     if ($existing{$ckey}) {
                   3215:         $existing{$ckey}.='; '.$logentry;
                   3216: # ready to assign
1.367     www      3217:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      3218:                                                  $cdom,$cnum) eq 'ok') {
                   3219: 	    return 'ok';
                   3220:         } else {
                   3221: 	    return 'error: Count not store comment.';
                   3222:         }
                   3223:     } else {
                   3224: # the key does not exist
                   3225: 	return 'error: The key does not exist';
                   3226:     }
                   3227: }
                   3228: 
1.344     www      3229: # ------------------------------------------------------ Generate a set of keys
                   3230: 
                   3231: sub generate_access_keys {
1.364     www      3232:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      3233:     $cdom=
1.620     albertel 3234:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3235:     $cnum=
1.620     albertel 3236:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      3237:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      3238:     unless (($cdom) && ($cnum)) { return 0; }
                   3239:     if ($number>10000) { return 0; }
                   3240:     sleep(2); # make sure don't get same seed twice
                   3241:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   3242:     my $total=0;
                   3243:     for (my $i=1;$i<=$number;$i++) {
                   3244:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   3245:                   sprintf("%lx",int(100000*rand)).'-'.
                   3246:                   sprintf("%lx",int(100000*rand));
                   3247:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   3248:        $newkey=~s/0/h/g; # and also 0 and O
                   3249:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   3250:        if ($existing{$newkey}) {
                   3251:            $i--;
                   3252:        } else {
1.364     www      3253: 	  if (&put('accesskeys',
                   3254:               { $newkey => '# generated '.localtime().
1.620     albertel 3255:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      3256:                            '; '.$logentry },
                   3257: 		   $cdom,$cnum) eq 'ok') {
1.344     www      3258:               $total++;
                   3259: 	  }
                   3260:        }
                   3261:     }
1.620     albertel 3262:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      3263:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   3264:     return $total;
                   3265: }
                   3266: 
                   3267: # ------------------------------------------------------- Validate an accesskey
                   3268: 
                   3269: sub validate_access_key {
                   3270:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   3271:     $cdom=
1.620     albertel 3272:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3273:     $cnum=
1.620     albertel 3274:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3275:     $udom=$env{'user.domain'} unless (defined($udom));
                   3276:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      3277:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 3278:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      3279: }
                   3280: 
                   3281: # ------------------------------------- Find the section of student in a course
1.652     albertel 3282: sub devalidate_getsection_cache {
                   3283:     my ($udom,$unam,$courseid)=@_;
                   3284:     my $hashid="$udom:$unam:$courseid";
                   3285:     &devalidate_cache_new('getsection',$hashid);
                   3286: }
1.298     matthew  3287: 
1.815     albertel 3288: sub courseid_to_courseurl {
                   3289:     my ($courseid) = @_;
                   3290:     #already url style courseid
                   3291:     return $courseid if ($courseid =~ m{^/});
                   3292: 
                   3293:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3294: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3295: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3296: 	return "/$cdom/$cnum";
                   3297:     }
                   3298: 
1.1494    raeburn  3299:     my %courseinfo=&coursedescription($courseid);
1.815     albertel 3300:     if (exists($courseinfo{'num'})) {
                   3301: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3302:     }
                   3303: 
                   3304:     return undef;
                   3305: }
                   3306: 
1.298     matthew  3307: sub getsection {
                   3308:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3309:     my $cachetime=1800;
1.551     albertel 3310: 
                   3311:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3312:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3313:     if (defined($cached)) { return $result; }
                   3314: 
1.298     matthew  3315:     my %Pending; 
                   3316:     my %Expired;
                   3317:     #
                   3318:     # Each role can either have not started yet (pending), be active, 
                   3319:     #    or have expired.
                   3320:     #
                   3321:     # If there is an active role, we are done.
                   3322:     #
                   3323:     # If there is more than one role which has not started yet, 
                   3324:     #     choose the one which will start sooner
                   3325:     # If there is one role which has not started yet, return it.
                   3326:     #
                   3327:     # If there is more than one expired role, choose the one which ended last.
                   3328:     # If there is a role which has expired, return it.
                   3329:     #
1.815     albertel 3330:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3331:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3332:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3333:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3334:         my $section=$1;
                   3335:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3336:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3337:         my $now=time;
1.548     albertel 3338:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3339:             $Expired{$end}=$section;
                   3340:             next;
                   3341:         }
1.548     albertel 3342:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3343:             $Pending{$start}=$section;
                   3344:             next;
                   3345:         }
1.599     albertel 3346:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3347:     }
                   3348:     #
                   3349:     # Presumedly there will be few matching roles from the above
                   3350:     # loop and the sorting time will be negligible.
                   3351:     if (scalar(keys(%Pending))) {
                   3352:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3353:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3354:     } 
                   3355:     if (scalar(keys(%Expired))) {
                   3356:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3357:         my $time = pop(@sorted);
1.599     albertel 3358:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3359:     }
1.599     albertel 3360:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3361: }
1.70      www      3362: 
1.599     albertel 3363: sub save_cache {
                   3364:     &purge_remembered();
1.722     albertel 3365:     #&Apache::loncommon::validate_page();
1.620     albertel 3366:     undef(%env);
1.780     albertel 3367:     undef($env_loaded);
1.599     albertel 3368: }
1.452     albertel 3369: 
1.599     albertel 3370: my $to_remember=-1;
                   3371: my %remembered;
                   3372: my %accessed;
                   3373: my $kicks=0;
                   3374: my $hits=0;
1.849     albertel 3375: sub make_key {
                   3376:     my ($name,$id) = @_;
1.872     albertel 3377:     if (length($id) > 65 
                   3378: 	&& length(&escape($id)) > 200) {
                   3379: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3380:     }
1.849     albertel 3381:     return &escape($name.':'.$id);
                   3382: }
                   3383: 
1.599     albertel 3384: sub devalidate_cache_new {
                   3385:     my ($name,$id,$debug) = @_;
                   3386:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3387:     my $remembered_id=$name.':'.$id;
1.849     albertel 3388:     $id=&make_key($name,$id);
1.599     albertel 3389:     $memcache->delete($id);
1.1319    damieng  3390:     delete($remembered{$remembered_id});
                   3391:     delete($accessed{$remembered_id});
1.599     albertel 3392: }
                   3393: 
                   3394: sub is_cached_new {
                   3395:     my ($name,$id,$debug) = @_;
1.1319    damieng  3396:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3397:     if (exists($remembered{$remembered_id})) {
                   3398: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3399: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3400: 	$hits++;
1.1319    damieng  3401: 	return ($remembered{$remembered_id},1);
1.599     albertel 3402:     }
1.1319    damieng  3403:     $id=&make_key($name,$id);
1.599     albertel 3404:     my $value = $memcache->get($id);
                   3405:     if (!(defined($value))) {
                   3406: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3407: 	return (undef,undef);
1.416     albertel 3408:     }
1.599     albertel 3409:     if ($value eq '__undef__') {
                   3410: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3411: 	$value=undef;
                   3412:     }
1.1319    damieng  3413:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3414:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3415:     return ($value,1);
                   3416: }
                   3417: 
                   3418: sub do_cache_new {
                   3419:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3420:     my $remembered_id=$name.':'.$id;
1.849     albertel 3421:     $id=&make_key($name,$id);
1.599     albertel 3422:     my $setvalue=$value;
                   3423:     if (!defined($setvalue)) {
                   3424: 	$setvalue='__undef__';
                   3425:     }
1.623     albertel 3426:     if (!defined($time) ) {
                   3427: 	$time=600;
                   3428:     }
1.599     albertel 3429:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3430:     my $result = $memcache->set($id,$setvalue,$time);
                   3431:     if (! $result) {
1.872     albertel 3432: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3433: 	$memcache->disconnect_all();
1.872     albertel 3434:     }
1.600     albertel 3435:     # need to make a copy of $value
1.1319    damieng  3436:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3437:     return $value;
                   3438: }
                   3439: 
                   3440: sub make_room {
1.1319    damieng  3441:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3442: 
1.1319    damieng  3443:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3444:                                     : $value;
1.599     albertel 3445:     if ($to_remember<0) { return; }
1.1319    damieng  3446:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3447:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3448:     my $to_kick;
                   3449:     my $max_time=0;
                   3450:     foreach my $other (keys(%accessed)) {
                   3451: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3452: 	    $to_kick=$other;
                   3453: 	    $max_time=&tv_interval($accessed{$other});
                   3454: 	}
                   3455:     }
                   3456:     delete($remembered{$to_kick});
                   3457:     delete($accessed{$to_kick});
                   3458:     $kicks++;
                   3459:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3460:     return;
                   3461: }
                   3462: 
1.599     albertel 3463: sub purge_remembered {
1.604     albertel 3464:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3465:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3466:     undef(%remembered);
                   3467:     undef(%accessed);
1.428     albertel 3468: }
1.70      www      3469: # ------------------------------------- Read an entry from a user's environment
                   3470: 
                   3471: sub userenvironment {
                   3472:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3473:     my $items;
                   3474:     foreach my $item (@what) {
                   3475:         $items.=&escape($item).'&';
                   3476:     }
                   3477:     $items=~s/\&$//;
1.70      www      3478:     my %returnhash=();
1.1009    raeburn  3479:     my $uhome = &homeserver($unam,$udom);
                   3480:     unless ($uhome eq 'no_host') {
                   3481:         my @answer=split(/\&/, 
                   3482:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3483:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3484:             return %returnhash;
                   3485:         }
1.1009    raeburn  3486:         my $i;
                   3487:         for ($i=0;$i<=$#what;$i++) {
                   3488: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3489:         }
1.70      www      3490:     }
                   3491:     return %returnhash;
1.1       albertel 3492: }
                   3493: 
1.617     albertel 3494: # ---------------------------------------------------------- Get a studentphoto
                   3495: sub studentphoto {
                   3496:     my ($udom,$unam,$ext) = @_;
1.1494    raeburn  3497:     my $home=&homeserver($unam,$udom);
1.706     raeburn  3498:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3499:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3500:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3501:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3502:             } else {
                   3503:                 my ($result,$perm_reqd)=
1.1494    raeburn  3504: 		    &auto_photo_permission($unam,$udom);
1.706     raeburn  3505:                 if ($result eq 'ok') {
                   3506:                     if (!($perm_reqd eq 'yes')) {
                   3507:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3508:                     }
                   3509:                 }
                   3510:             }
                   3511:         }
                   3512:     } else {
                   3513:         my ($result,$perm_reqd) = 
1.1494    raeburn  3514: 	    &auto_photo_permission($unam,$udom);
1.706     raeburn  3515:         if ($result eq 'ok') {
                   3516:             if (!($perm_reqd eq 'yes')) {
                   3517:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3518:             }
                   3519:         }
                   3520:     }
                   3521:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3522: }
                   3523: 
                   3524: sub retrievestudentphoto {
                   3525:     my ($udom,$unam,$ext,$type) = @_;
1.1494    raeburn  3526:     my $home=&homeserver($unam,$udom);
                   3527:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
1.706     raeburn  3528:     if ($ret eq 'ok') {
                   3529:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3530:         if ($type eq 'thumbnail') {
                   3531:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3532:         }
1.1494    raeburn  3533:         my $tokenurl=&tokenwrapper($url);
1.706     raeburn  3534:         return $tokenurl;
                   3535:     } else {
                   3536:         if ($type eq 'thumbnail') {
                   3537:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3538:         } else { 
                   3539:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3540:         }
1.617     albertel 3541:     }
                   3542: }
                   3543: 
1.263     www      3544: # -------------------------------------------------------------------- New chat
                   3545: 
                   3546: sub chatsend {
1.724     raeburn  3547:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3548:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3549:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3550:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3551:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3552: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3553: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3554: }
                   3555: 
                   3556: # ------------------------------------------ Find current version of a resource
                   3557: 
                   3558: sub getversion {
                   3559:     my $fname=&clutter(shift);
1.1189    raeburn  3560:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3561:     return &currentversion(&filelocation('',$fname));
                   3562: }
                   3563: 
                   3564: sub currentversion {
                   3565:     my $fname=shift;
                   3566:     my $author=$fname;
                   3567:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3568:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3569:     my $home=&homeserver($uname,$udom);
1.292     www      3570:     if ($home eq 'no_host') { 
                   3571:         return -1; 
                   3572:     }
1.1112    www      3573:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3574:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3575: 	return -1;
                   3576:     }
1.1112    www      3577:     return $answer;
1.263     www      3578: }
                   3579: 
1.1111    www      3580: #
                   3581: # Return special version number of resource if set by override, empty otherwise
                   3582: #
                   3583: sub usedversion {
                   3584:     my $fname=shift;
                   3585:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3586:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3587:     if ($urlversion) { return $urlversion; }
                   3588:     return '';
                   3589: }
                   3590: 
1.1       albertel 3591: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3592: 
1.1       albertel 3593: sub subscribe {
                   3594:     my $fname=shift;
1.761     raeburn  3595:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3596:     $fname=~s/[\n\r]//g;
1.1       albertel 3597:     my $author=$fname;
                   3598:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3599:     my ($udom,$uname)=split(/\//,$author);
                   3600:     my $home=homeserver($uname,$udom);
1.335     albertel 3601:     if ($home eq 'no_host') {
                   3602:         return 'not_found';
1.1       albertel 3603:     }
                   3604:     my $answer=reply("sub:$fname",$home);
1.64      www      3605:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3606: 	$answer.=' by '.$home;
                   3607:     }
1.1       albertel 3608:     return $answer;
                   3609: }
                   3610:     
1.8       www      3611: # -------------------------------------------------------------- Replicate file
                   3612: 
                   3613: sub repcopy {
                   3614:     my $filename=shift;
1.23      www      3615:     $filename=~s/\/+/\//g;
1.1142    raeburn  3616:     my $londocroot = $perlvar{'lonDocRoot'};
                   3617:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3618:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3619:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3620: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3621: 	return &repcopy_userfile($filename);
                   3622:     }
1.532     albertel 3623:     $filename=~s/[\n\r]//g;
1.8       www      3624:     my $transname="$filename.in.transfer";
1.828     www      3625: # FIXME: this should flock
1.607     raeburn  3626:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3627:     my $remoteurl=subscribe($filename);
1.64      www      3628:     if ($remoteurl =~ /^con_lost by/) {
                   3629: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3630:            return 'unavailable';
1.8       www      3631:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3632: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3633: 	   return 'not_found';
1.64      www      3634:     } elsif ($remoteurl =~ /^rejected by/) {
                   3635: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3636:            return 'forbidden';
1.20      www      3637:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3638:            return 'ok';
1.8       www      3639:     } else {
1.290     www      3640:         my $author=$filename;
                   3641:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3642:         my ($udom,$uname)=split(/\//,$author);
                   3643:         my $home=homeserver($uname,$udom);
                   3644:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3645:            my @parts=split(/\//,$filename);
                   3646:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3647:            if ($path ne "$londocroot/res") {
1.8       www      3648:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3649: 	       return 'bad_request';
1.8       www      3650:            }
                   3651:            my $count;
                   3652:            for ($count=5;$count<$#parts;$count++) {
                   3653:                $path.="/$parts[$count]";
                   3654:                if ((-e $path)!=1) {
                   3655: 		   mkdir($path,0777);
                   3656:                }
                   3657:            }
                   3658:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3659:            my $response;
                   3660:            if ($remoteurl =~ m{/raw/}) {
                   3661:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3662:            } else {
                   3663:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3664:            }
1.8       www      3665:            if ($response->is_error()) {
                   3666: 	       unlink($transname);
                   3667:                my $message=$response->status_line;
1.672     albertel 3668:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3669:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3670:                return 'unavailable';
1.8       www      3671:            } else {
1.16      www      3672: 	       if ($remoteurl!~/\.meta$/) {
                   3673:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3674:                   my $mresponse;
                   3675:                   if ($remoteurl =~ m{/raw/}) {
                   3676:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3677:                   } else {
                   3678:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3679:                   }
1.16      www      3680:                   if ($mresponse->is_error()) {
                   3681: 		      unlink($filename.'.meta');
                   3682:                       &logthis(
1.672     albertel 3683:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3684:                   }
                   3685: 	       }
1.8       www      3686:                rename($transname,$filename);
1.607     raeburn  3687:                return 'ok';
1.8       www      3688:            }
1.290     www      3689:        }
1.8       www      3690:     }
1.330     www      3691: }
                   3692: 
1.1422    raeburn  3693: # ------------------------------------------------- Unsubscribe from a resource
                   3694: 
                   3695: sub unsubscribe {
                   3696:     my ($fname) = @_;
                   3697:     my $answer;
                   3698:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3699:     $fname=~s/[\n\r]//g;
                   3700:     my $author=$fname;
                   3701:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3702:     my ($udom,$uname)=split(/\//,$author);
                   3703:     my $home=homeserver($uname,$udom);
                   3704:     if ($home eq 'no_host') {
                   3705:         $answer = 'no_host';
                   3706:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3707:         $answer = 'home';
                   3708:     } else {
                   3709:         my $defdom = $perlvar{'lonDefDomain'};
                   3710:         if (&will_trust('content',$defdom,$udom)) {
                   3711:             $answer = reply("unsub:$fname",$home);
                   3712:         } else {
                   3713:             $answer = 'untrusted';
                   3714:         }
                   3715:     }
                   3716:     return $answer;
                   3717: }
                   3718: 
1.330     www      3719: # ------------------------------------------------ Get server side include body
                   3720: sub ssi_body {
1.381     albertel 3721:     my ($filelink,%form)=@_;
1.606     matthew  3722:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3723:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3724:     }
1.953     www      3725:     my $output='';
                   3726:     my $response;
1.980     raeburn  3727:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3728:        ($output,$response)=&externalssi($filelink);
1.953     www      3729:     } else {
1.1004    droeschl 3730:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3731:        $filelink .= 'inhibitmenu=yes';
1.953     www      3732:        ($output,$response)=&ssi($filelink,%form);
                   3733:     }
1.778     albertel 3734:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3735:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3736:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3737:     if (wantarray) {
                   3738:         return ($output, $response);
                   3739:     } else {
                   3740:         return $output;
                   3741:     }
1.8       www      3742: }
                   3743: 
1.15      www      3744: # --------------------------------------------------------- Server Side Include
                   3745: 
1.782     albertel 3746: sub absolute_url {
1.1447    raeburn  3747:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3748:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3749:     if ($host_name eq '') {
                   3750: 	$host_name = $ENV{'SERVER_NAME'};
                   3751:     }
1.1447    raeburn  3752:     if ($unalias) {
                   3753:         my $alias = &get_proxy_alias();
                   3754:         if ($alias eq $host_name) {
                   3755:             my $lonhost = $perlvar{'lonHostID'};
                   3756:             my $hostname = &hostname($lonhost);
                   3757:             my $lcproto; 
                   3758:             if (($keep_proto) || ($hostname eq '')) {
                   3759:                 $lcproto = $protocol;
                   3760:             } else {
                   3761:                 $lcproto = $protocol{$lonhost};
                   3762:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3763:                 $lcproto .= '://';
                   3764:             }
                   3765:             unless ($hostname eq '') {
                   3766:                 return $lcproto.$hostname;
                   3767:             }
                   3768:         }
                   3769:     }
1.782     albertel 3770:     return $protocol.$host_name;
                   3771: }
                   3772: 
1.942     foxr     3773: #
                   3774: #   Server side include.
                   3775: # Parameters:
                   3776: #  fn     Possibly encrypted resource name/id.
                   3777: #  form   Hash that describes how the rendering should be done
                   3778: #         and other things.
1.944     foxr     3779: # Returns:
1.950     raeburn  3780: #   Scalar context: The content of the response.
                   3781: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3782: #     
1.15      www      3783: sub ssi {
                   3784: 
1.944     foxr     3785:     my ($fn,%form)=@_;
1.1447    raeburn  3786:     my ($host,$request,$response);
                   3787:     $host = &absolute_url('',1);
1.711     albertel 3788: 
                   3789:     $form{'no_update_last_known'}=1;
1.895     albertel 3790:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3791:     if (%form) {
1.1447    raeburn  3792:       $request=new HTTP::Request('POST',$host.$fn);
1.1272    droeschl 3793:       $request->content(join('&',map { 
                   3794:             my $name = escape($_);
                   3795:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3796:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3797:             : &escape($form{$_}) );    
                   3798:         } keys(%form)));
1.23      www      3799:     } else {
1.1447    raeburn  3800:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3801:     }
                   3802: 
1.15      www      3803:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3804:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3805:     my $islocal;
                   3806:     if (($env{'request.course.id'}) &&
                   3807:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3808:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3809:         ($form{'grade_symb'} ne '') &&
1.1494    raeburn  3810:         (&allowed('mgr',$env{'request.course.id'}.
                   3811:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1385    raeburn  3812:         $islocal = 1;
                   3813:     }
1.1447    raeburn  3814:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
                   3815:                                              '','','',$islocal);
1.1182    foxr     3816: 
1.944     foxr     3817:     if (wantarray) {
1.1345    raeburn  3818: 	return ($response->content, $response);
1.944     foxr     3819:     } else {
1.1345    raeburn  3820: 	return $response->content;
1.942     foxr     3821:     }
1.324     www      3822: }
                   3823: 
                   3824: sub externalssi {
                   3825:     my ($url)=@_;
                   3826:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3827:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3828:     if (wantarray) {
                   3829:         return ($response->content, $response);
                   3830:     } else {
                   3831:         return $response->content;
                   3832:     }
1.15      www      3833: }
1.254     www      3834: 
1.1354    raeburn  3835: 
                   3836: # If the local copy of a replicated resource is outdated, trigger a  
                   3837: # connection from the homeserver to flush the delayed queue. If no update 
                   3838: # happens, remove local copies of outdated resource (and corresponding
                   3839: # metadata file).
                   3840: 
1.1352    raeburn  3841: sub remove_stale_resfile {
                   3842:     my ($url) = @_;
1.1354    raeburn  3843:     my $removed;
1.1352    raeburn  3844:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3845:         my $audom = $1;
                   3846:         my $auname = $2;
1.1353    raeburn  3847:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3848:             my $homeserver = &homeserver($auname,$audom);
                   3849:             unless (($homeserver eq 'no_host') ||
                   3850:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3851:                 my $fname = &filelocation('',$url);
                   3852:                 if (-e $fname) {
                   3853:                     my $hostname = &hostname($homeserver);
                   3854:                     if ($hostname) {
1.1397    raeburn  3855:                         my $protocol = $protocol{$homeserver};
                   3856:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3857:                         my $uri = &declutter($url);
                   3858:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3859:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3860:                         if ($response->is_success()) {
                   3861:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3862:                             my $locmodtime = (stat($fname))[9];
                   3863:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3864:                                 my $stale;
                   3865:                                 my $answer = &reply('pong',$homeserver);
                   3866:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3867:                                     sleep(0.2);
                   3868:                                     $locmodtime = (stat($fname))[9];
                   3869:                                     if ($locmodtime < $remmodtime) {
                   3870:                                         my $posstransfer = $fname.'.in.transfer';
                   3871:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3872:                                             $removed = 1;
                   3873:                                         } else {
                   3874:                                             $stale = 1;
                   3875:                                         }
                   3876:                                     } else {
                   3877:                                         $removed = 1;
                   3878:                                     }
                   3879:                                 } else {
                   3880:                                     $stale = 1;
                   3881:                                 }
                   3882:                                 if ($stale) {
1.1421    raeburn  3883:                                     if (unlink($fname)) {
                   3884:                                         if ($uri!~/\.meta$/) {
                   3885:                                             if (-e $fname.'.meta') {
                   3886:                                                 unlink($fname.'.meta');
                   3887:                                             }
                   3888:                                         }
1.1422    raeburn  3889:                                         my $unsubresult = &unsubscribe($fname);
                   3890:                                         unless ($unsubresult eq 'ok') {
                   3891:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3892:                                         }
1.1421    raeburn  3893:                                         $removed = 1;
1.1354    raeburn  3894:                                     }
1.1352    raeburn  3895:                                 }
                   3896:                             }
                   3897:                         }
                   3898:                     }
                   3899:                 }
                   3900:             }
                   3901:         }
                   3902:     }
1.1354    raeburn  3903:     return $removed;
1.1352    raeburn  3904: }
                   3905: 
1.492     albertel 3906: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3907: 
                   3908: sub allowuploaded {
                   3909:     my ($srcurl,$url)=@_;
                   3910:     $url=&clutter(&declutter($url));
                   3911:     my $dir=$url;
                   3912:     $dir=~s/\/[^\/]+$//;
                   3913:     my %httpref=();
                   3914:     my $httpurl=&hreflocation('',$url);
                   3915:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3916:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3917: }
1.477     raeburn  3918: 
1.1193    raeburn  3919: #
                   3920: # Determine if the current user should be able to edit a particular resource,
                   3921: # when viewing in course context.
                   3922: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3923: #     Functions.
                   3924: # (b) When displaying folder contents in course editor, used to determine if
                   3925: #     "Edit" link will be displayed alongside resource.
                   3926: #
1.1196    raeburn  3927: #  input: six args -- filename (decluttered), course number, course domain,
                   3928: #                   url, symb (if registered) and group (if this is a group
                   3929: #                   item -- e.g., bulletin board, group page etc.).
                   3930: #  output: array of five scalars -- 
1.1193    raeburn  3931: #          $cfile -- url for file editing if editable on current server
                   3932: #          $home -- homeserver of resource (i.e., for author if published,
                   3933: #                                           or course if uploaded.).
                   3934: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3935: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3936: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3937: #
                   3938: 
                   3939: sub can_edit_resource {
1.1194    raeburn  3940:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3941:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3942: #
                   3943: # For aboutme pages user can only edit his/her own.
                   3944: #
1.1199    raeburn  3945:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3946:         my ($sdom,$sname) = ($1,$2);
                   3947:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3948:             $home = $env{'user.home'};
                   3949:             $cfile = $resurl;
                   3950:             if ($env{'form.forceedit'}) {
                   3951:                 $forceview = 1;
                   3952:             } else {
                   3953:                 $forceedit = 1;
                   3954:             }
                   3955:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3956:         } else {
                   3957:             return;
                   3958:         }
                   3959:     }
                   3960: 
1.1517    raeburn  3961: #
                   3962: # For /adm/viewcoauthors can only edit if author or co-author who is manager.
                   3963: #
                   3964: 
                   3965:     if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
                   3966:         if (((&allowed('cca',"$cdom/$cnum")) ||
                   3967:              (&allowed('caa',"$cdom/$cnum"))) ||
                   3968:              ((&allowed('vca',"$cdom/$cnum") ||
                   3969:                &allowed('vaa',"$cdom/$cnum")) &&
                   3970:               ($env{"environment.internal.manager./$cdom/$cnum"}))) {
                   3971:             $home = $env{'user.home'};
                   3972:             $cfile = $resurl;
                   3973:             if ($env{'form.forceedit'}) {
                   3974:                 $forceview = 1;
                   3975:             } else {
                   3976:                 $forceedit = 1;
                   3977:             }
                   3978:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3979:         } else {
                   3980:             return;
                   3981:         }
                   3982:     }
                   3983: 
1.1194    raeburn  3984:     if ($env{'request.course.id'}) {
1.1494    raeburn  3985:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
1.1194    raeburn  3986:         if ($group ne '') {
                   3987: # if this is a group homepage or group bulletin board, check group privs
                   3988:             my $allowed = 0;
1.1197    raeburn  3989:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3990:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3991:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3992:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3993:                     $allowed = 1;
                   3994:                 }
1.1197    raeburn  3995:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3996:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3997:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3998:                     $allowed = 1;
                   3999:                 }
                   4000:             }
                   4001:             if ($allowed) {
                   4002:                 $home=&homeserver($cnum,$cdom);
                   4003:                 if ($env{'form.forceedit'}) {
                   4004:                     $forceview = 1;
                   4005:                 } else {
                   4006:                     $forceedit = 1;
                   4007:                 }
                   4008:                 $cfile = $resurl;
                   4009:             } else {
                   4010:                 return;
                   4011:             }
                   4012:         } else {
1.1208    raeburn  4013:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
1.1494    raeburn  4014:                 unless (&allowed('opa',$env{'request.course.id'})) {
1.1208    raeburn  4015:                     return;
                   4016:                 }
                   4017:             } elsif (!$crsedit) {
1.1507    raeburn  4018:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
1.1194    raeburn  4019: #
                   4020: # No edit allowed where CC has switched to student role.
                   4021: #
1.1507    raeburn  4022:                     return;
                   4023:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
                   4024:                          ($resurl =~ m{^/res/lib/templates/})) {
                   4025:                     return;
                   4026:                 }
1.1194    raeburn  4027:             }
                   4028:         }
                   4029:     }
                   4030: 
1.1193    raeburn  4031:     if ($file ne '') {
                   4032:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  4033:             if (&is_course_upload($file,$cnum,$cdom)) {
                   4034:                 $uploaded = 1;
                   4035:                 $incourse = 1;
1.1193    raeburn  4036:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   4037:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  4038:                     if ($env{'form.forceedit'}) {
                   4039:                         $forceview = 1;
                   4040:                     } else {
                   4041:                         $forceedit = 1;
                   4042:                     }
1.1194    raeburn  4043:                 }
                   4044:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   4045:                 $incourse = 1;
                   4046:                 if ($env{'form.forceedit'}) {
                   4047:                     $forceview = 1;
                   4048:                 } else {
                   4049:                     $forceedit = 1;
                   4050:                 }
                   4051:                 $cfile = $resurl;
1.1507    raeburn  4052:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
1.1194    raeburn  4053:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   4054:                     $incourse = 1;
                   4055:                     if ($env{'form.forceedit'}) {
                   4056:                         $forceview = 1;
                   4057:                     } else {
                   4058:                         $forceedit = 1;
                   4059:                     }
                   4060:                     $cfile = $resurl;
1.1199    raeburn  4061:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  4062:                     $incourse = 1;
                   4063:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  4064:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  4065:                     $incourse = 1;
1.1199    raeburn  4066:                     if ($env{'form.forceedit'}) {
                   4067:                         $forceview = 1;
                   4068:                     } else {
                   4069:                         $forceedit = 1;
                   4070:                     }
                   4071:                     $cfile = $resurl;
1.1419    raeburn  4072:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   4073:                     my ($map,$id,$res) = &decode_symb($symb);
                   4074:                     if ($map =~ /\.page$/) {
                   4075:                         $incourse = 1;
                   4076:                         if ($env{'form.forceedit'}) {
                   4077:                             $forceview = 1;
                   4078:                             $cfile = $map;
                   4079:                         } else {
                   4080:                             $forceedit = 1;
                   4081:                             $cfile =  '/adm/wrapper'.$resurl;
                   4082:                         }
                   4083:                     }
1.1343    raeburn  4084:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  4085:                     $incourse = 1;
                   4086:                     if ($env{'form.forceedit'}) {
                   4087:                         $forceview = 1;
                   4088:                     } else {
                   4089:                         $forceedit = 1;
                   4090:                     }
                   4091:                     $cfile = $resurl;
1.1208    raeburn  4092:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   4093:                     $incourse = 1;
                   4094:                     if ($env{'form.forceedit'}) {
                   4095:                         $forceview = 1;
                   4096:                     } else {
                   4097:                         $forceedit = 1;
                   4098:                     }
                   4099:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  4100:                 }
                   4101:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   4102:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   4103:                 if (&is_on_map($template)) { 
                   4104:                     $incourse = 1;
                   4105:                     $forceview = 1;
                   4106:                     $cfile = $template;
1.1193    raeburn  4107:                 }
1.1199    raeburn  4108:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  4109:                 $incourse = 1;
                   4110:                 if ($env{'form.forceedit'}) {
                   4111:                     $forceview = 1;
                   4112:                 } else {
                   4113:                     $forceedit = 1;
                   4114:                 }
                   4115:                 $cfile = $resurl;
1.1343    raeburn  4116:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  4117:                 $incourse = 1;
                   4118:                 if ($env{'form.forceedit'}) {
                   4119:                     $forceview = 1;
                   4120:                 } else {
                   4121:                     $forceedit = 1;
                   4122:                 }
                   4123:                 $cfile = $resurl;
1.1199    raeburn  4124:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   4125:                 $incourse = 1;
                   4126:                 $forceview = 1;
                   4127:                 if ($symb) {
                   4128:                     my ($map,$id,$res)=&decode_symb($symb);
                   4129:                     $env{'request.symb'} = $symb;
                   4130:                     $cfile = &clutter($res);
                   4131:                 } else {
                   4132:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  4133:                     my $escfile = &unescape($cfile);
1.1343    raeburn  4134:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  4135:                         $cfile = '/adm/wrapper'.$escfile;
                   4136:                     } else {
                   4137:                         $escfile =~ s{^http://}{};
                   4138:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   4139:                     }
1.1199    raeburn  4140:                 }
1.1234    raeburn  4141:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   4142:                 if ($env{'form.forceedit'}) {
                   4143:                     $forceview = 1;
                   4144:                 } else {
                   4145:                     $forceedit = 1;
                   4146:                 }
                   4147:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  4148:             }
                   4149:         }
1.1194    raeburn  4150:         if ($uploaded || $incourse) {
                   4151:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  4152:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  4153:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   4154:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   4155:             # Check that the user has permission to edit this resource
                   4156:             my $setpriv = 1;
                   4157:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   4158:             if (defined($cfudom)) {
                   4159:                 $home=&homeserver($cfuname,$cfudom);
                   4160:                 $cfile=$file;
                   4161:             }
                   4162:         }
1.1194    raeburn  4163:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   4164:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  4165:             my @ids=&current_machine_ids();
                   4166:             unless (grep(/^\Q$home\E$/,@ids)) {
                   4167:                 $switchserver=1;
                   4168:             }
                   4169:         }
                   4170:     }
1.1194    raeburn  4171:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  4172: }
                   4173: 
                   4174: sub is_course_upload {
                   4175:     my ($file,$cnum,$cdom) = @_;
                   4176:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   4177:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  4178:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   4179:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  4180:         return 1;
                   4181:     }
                   4182:     return;
                   4183: }
                   4184: 
1.1194    raeburn  4185: sub in_course {
1.1195    raeburn  4186:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   4187:     if ($hideprivileged) {
                   4188:         my $skipuser;
1.1219    raeburn  4189:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   4190:         my @possdoms = ($cdom);  
                   4191:         if ($coursehash{'checkforpriv'}) { 
                   4192:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   4193:         }
                   4194:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  4195:             $skipuser = 1;
                   4196:             if ($coursehash{'nothideprivileged'}) {
                   4197:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4198:                     my $user;
                   4199:                     if ($item =~ /:/) {
                   4200:                         $user = $item;
                   4201:                     } else {
                   4202:                         $user = join(':',split(/[\@]/,$item));
                   4203:                     }
                   4204:                     if ($user eq $uname.':'.$udom) {
                   4205:                         undef($skipuser);
                   4206:                         last;
                   4207:                     }
                   4208:                 }
                   4209:             }
                   4210:             if ($skipuser) {
                   4211:                 return 0;
                   4212:             }
                   4213:         }
                   4214:     }
1.1194    raeburn  4215:     $type ||= 'any';
                   4216:     if (!defined($cdom) || !defined($cnum)) {
                   4217:         my $cid  = $env{'request.course.id'};
                   4218:         $cdom = $env{'course.'.$cid.'.domain'};
                   4219:         $cnum = $env{'course.'.$cid.'.num'};
                   4220:     }
                   4221:     my $typesref;
1.1195    raeburn  4222:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  4223:         $typesref = ['active','previous','future'];
                   4224:     } elsif ($type eq 'previous' || $type eq 'future') {
                   4225:         $typesref = [$type];
                   4226:     }
                   4227:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   4228:                               $typesref,undef,[$cdom]);
                   4229:     my ($tmp) = keys(%roles);
                   4230:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   4231:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   4232:     if (@course_roles > 0) {
                   4233:         return 1;
                   4234:     }
                   4235:     return 0;
                   4236: }
                   4237: 
1.478     albertel 4238: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 4239: # input: action, courseID, current domain, intended
1.637     raeburn  4240: #        path to file, source of file, instruction to parse file for objects,
                   4241: #        ref to hash for embedded objects,
                   4242: #        ref to hash for codebase of java objects.
1.1095    raeburn  4243: #        reference to scalar to accommodate mime type determined
                   4244: #          from File::MMagic if $parser = parse.
1.637     raeburn  4245: #
1.485     raeburn  4246: # output: url to file (if action was uploaddoc), 
                   4247: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  4248: #
1.478     albertel 4249: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   4250: # course.
1.477     raeburn  4251: #
1.478     albertel 4252: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4253: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   4254: #          course's home server.
1.477     raeburn  4255: #
1.478     albertel 4256: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   4257: #          be copied from $source (current location) to 
                   4258: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4259: #         and will then be copied to
                   4260: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   4261: #         course's home server.
1.485     raeburn  4262: #
1.481     raeburn  4263: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 4264: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  4265: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4266: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   4267: #         in course's home server.
1.637     raeburn  4268: #
1.477     raeburn  4269: 
                   4270: sub process_coursefile {
1.1095    raeburn  4271:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   4272:         $mimetype)=@_;
1.477     raeburn  4273:     my $fetchresult;
1.638     albertel 4274:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  4275:     if ($action eq 'propagate') {
1.638     albertel 4276:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   4277: 			     $home);
1.481     raeburn  4278:     } else {
1.477     raeburn  4279:         my $fpath = '';
                   4280:         my $fname = $file;
1.478     albertel 4281:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  4282:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  4283:         my $filepath = &build_filepath($fpath);
1.481     raeburn  4284:         if ($action eq 'copy') {
                   4285:             if ($source eq '') {
                   4286:                 $fetchresult = 'no source file';
                   4287:                 return $fetchresult;
                   4288:             } else {
                   4289:                 my $destination = $filepath.'/'.$fname;
                   4290:                 rename($source,$destination);
                   4291:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4292:                                  $home);
1.481     raeburn  4293:             }
                   4294:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  4295:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 4296:             print $fh $env{'form.'.$source};
1.481     raeburn  4297:             close($fh);
1.637     raeburn  4298:             if ($parser eq 'parse') {
1.1024    raeburn  4299:                 my $mm = new File::MMagic;
1.1095    raeburn  4300:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   4301:                 if ($type eq 'text/html') {
1.1024    raeburn  4302:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   4303:                     unless ($parse_result eq 'ok') {
                   4304:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   4305:                     }
1.637     raeburn  4306:                 }
1.1095    raeburn  4307:                 if (ref($mimetype)) {
                   4308:                     $$mimetype = $type;
                   4309:                 } 
1.637     raeburn  4310:             }
1.477     raeburn  4311:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4312:                                  $home);
1.481     raeburn  4313:             if ($fetchresult eq 'ok') {
                   4314:                 return '/uploaded/'.$fpath.'/'.$fname;
                   4315:             } else {
                   4316:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4317:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  4318:                 return '/adm/notfound.html';
                   4319:             }
1.477     raeburn  4320:         }
                   4321:     }
1.485     raeburn  4322:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4323:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4324:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4325:     }
                   4326:     return $fetchresult;
                   4327: }
                   4328: 
1.637     raeburn  4329: sub build_filepath {
                   4330:     my ($fpath) = @_;
                   4331:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4332:     unless ($fpath eq '') {
                   4333:         my @parts=split('/',$fpath);
                   4334:         foreach my $part (@parts) {
                   4335:             $filepath.= '/'.$part;
                   4336:             if ((-e $filepath)!=1) {
                   4337:                 mkdir($filepath,0777);
                   4338:             }
                   4339:         }
                   4340:     }
                   4341:     return $filepath;
                   4342: }
                   4343: 
                   4344: sub store_edited_file {
1.638     albertel 4345:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4346:     my $file = $primary_url;
                   4347:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4348:     my $fpath = '';
                   4349:     my $fname = $file;
                   4350:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4351:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4352:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4353:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4354:     print $fh $content;
                   4355:     close($fh);
1.638     albertel 4356:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4357:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4358: 			  $home);
1.637     raeburn  4359:     if ($$fetchresult eq 'ok') {
                   4360:         return '/uploaded/'.$fpath.'/'.$fname;
                   4361:     } else {
1.638     albertel 4362:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4363: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4364:         return '/adm/notfound.html';
                   4365:     }
                   4366: }
                   4367: 
1.531     albertel 4368: sub clean_filename {
1.831     albertel 4369:     my ($fname,$args)=@_;
1.315     www      4370: # Replace Windows backslashes by forward slashes
1.257     www      4371:     $fname=~s/\\/\//g;
1.831     albertel 4372:     if (!$args->{'keep_path'}) {
                   4373:         # Get rid of everything but the actual filename
                   4374: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4375:     }
1.315     www      4376: # Replace spaces by underscores
                   4377:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4378: # Transliterate non-ascii text to ascii
                   4379:     my $lang = &Apache::lonlocal::current_language();
                   4380:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4381: # Replace all other weird characters by nothing
1.831     albertel 4382:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4383: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4384: # numbers
                   4385:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443    raeburn  4386: # Replace three or more adjacent underscores with one for consistency 
                   4387: # with loncfile::filename_check() so complete url can be extracted by
                   4388: # lonnet::decode_symb()
                   4389:     $fname=~s/_{3,}/_/g;
1.531     albertel 4390:     return $fname;
                   4391: }
1.1406    raeburn  4392: 
1.1051    raeburn  4393: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4394: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4395: # image with the same aspect ratio as the original, but with dimensions which do 
                   4396: # not exceed $resizewidth and $resizeheight.
                   4397:  
1.984     neumanie 4398: sub resizeImage {
1.1051    raeburn  4399:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4400:     my $ima = Image::Magick->new;
                   4401:     my $resized;
                   4402:     if (-e $img_path) {
                   4403:         $ima->Read($img_path);
                   4404:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4405:             my $width = $ima->Get('width');
                   4406:             my $height = $ima->Get('height');
                   4407:             if ($width > $resizewidth) {
                   4408: 	        my $factor = $width/$resizewidth;
                   4409:                 my $newheight = $height/$factor;
                   4410:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4411:                 $resized = 1;
                   4412:             }
                   4413:         }
                   4414:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4415:             my $width = $ima->Get('width');
                   4416:             my $height = $ima->Get('height');
                   4417:             if ($height > $resizeheight) {
                   4418:                 my $factor = $height/$resizeheight;
                   4419:                 my $newwidth = $width/$factor;
                   4420:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4421:                 $resized = 1;
                   4422:             }
                   4423:         }
                   4424:         if ($resized) {
                   4425:             $ima->Write($img_path);
                   4426:         }
                   4427:     }
                   4428:     return;
1.977     amueller 4429: }
                   4430: 
1.608     albertel 4431: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4432: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4433: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4434: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1504    raeburn  4435: #                                    canceloverwrite, scantron, toollogo  or ''.
1.1090    raeburn  4436: #                   if 'coursedoc': upload to the current course
                   4437: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4438: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4439: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4440: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4441: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4442: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4443: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4444: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4445: #        $allfiles - reference to hash for embedded objects
                   4446: #        $codebase - reference to hash for codebase of java objects
1.1504    raeburn  4447: #        $destuname - username for permanent storage of uploaded file
                   4448: #        $destudom - domain for permanaent storage of uploaded file
1.860     raeburn  4449: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4450: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4451: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4452: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4453: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4454: #                    from File::MMagic.
1.858     raeburn  4455: # 
1.686     albertel 4456: # output: url of file in userspace, or error: <message> 
                   4457: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4458: 
1.531     albertel 4459: sub userfileupload {
1.1090    raeburn  4460:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4461:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4462:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4463:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4464:     $fname=&clean_filename($fname);
1.1090    raeburn  4465:     # See if there is anything left
1.257     www      4466:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4467:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4468:     if ($fname =~ /^\./) {
                   4469:         my ($s,$usec) = &gettimeofday();
                   4470:         while (length($usec) < 6) {
                   4471:             $usec = '0'.$usec;
                   4472:         }
                   4473:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4474:     }
1.1090    raeburn  4475:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4476:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4477:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4478:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4479:         my $now = time;
1.1090    raeburn  4480:         my $filepath;
1.1095    raeburn  4481:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4482:              $filepath = 'tmp/helprequests/'.$now;
                   4483:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4484:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4485:                          '_'.$env{'user.domain'}.'/pending';
                   4486:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4487:             my ($docuname,$docudom);
1.1350    raeburn  4488:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4489:                 $docudom = $destudom;
                   4490:             } else {
                   4491:                 $docudom = $env{'user.domain'};
                   4492:             }
1.1350    raeburn  4493:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4494:                 $docuname = $destuname;
                   4495:             } else {
                   4496:                 $docuname = $env{'user.name'};
                   4497:             }
                   4498:             if (exists($env{'form.group'})) {
                   4499:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4500:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4501:             }
                   4502:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4503:             if ($context eq 'canceloverwrite') {
                   4504:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4505:                 if (-e  $tempfile) {
                   4506:                     my @info = stat($tempfile);
                   4507:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4508:                         unlink($tempfile);
                   4509:                     }
                   4510:                 }
                   4511:                 return;
1.523     raeburn  4512:             }
                   4513:         }
1.1090    raeburn  4514:         # Create the directory if not present
1.741     raeburn  4515:         my @parts=split(/\//,$filepath);
                   4516:         my $fullpath = $perlvar{'lonDaemons'};
                   4517:         for (my $i=0;$i<@parts;$i++) {
                   4518:             $fullpath .= '/'.$parts[$i];
                   4519:             if ((-e $fullpath)!=1) {
                   4520:                 mkdir($fullpath,0777);
                   4521:             }
                   4522:         }
1.1359    raeburn  4523:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4524:         print $fh $env{'form.'.$formname};
                   4525:         close($fh);
1.1090    raeburn  4526:         if ($context eq 'existingfile') {
                   4527:             my @info = stat($fullpath.'/'.$fname);
                   4528:             return ($fullpath.'/'.$fname,$info[9]);
                   4529:         } else {
                   4530:             return $fullpath.'/'.$fname;
                   4531:         }
1.523     raeburn  4532:     }
1.995     raeburn  4533:     if ($subdir eq 'scantron') {
                   4534:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4535:     } else {
1.995     raeburn  4536:         $fname="$subdir/$fname";
                   4537:     }
1.1090    raeburn  4538:     if ($context eq 'coursedoc') {
1.638     albertel 4539: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4540: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4541:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4542:             return &finishuserfileupload($docuname,$docudom,
                   4543: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4544: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4545:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4546:         } else {
1.1218    raeburn  4547:             if ($env{'form.folder'}) {
                   4548:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4549:             }
1.638     albertel 4550:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4551: 				       $fname,$formname,$parser,
1.1095    raeburn  4552: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4553:         }
1.719     banghart 4554:     } elsif (defined($destuname)) {
                   4555:         my $docuname=$destuname;
                   4556:         my $docudom=$destudom;
1.860     raeburn  4557: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4558: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4559:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4560:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4561:     } else {
1.638     albertel 4562:         my $docuname=$env{'user.name'};
                   4563:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4564:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4565:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4566:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4567:         }
1.860     raeburn  4568: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4569: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4570:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4571:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4572:     }
1.271     www      4573: }
                   4574: 
                   4575: sub finishuserfileupload {
1.860     raeburn  4576:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4577:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4578:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4579:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4580:   
1.860     raeburn  4581:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4582:     $file=$fname;
                   4583:     if ($fname=~m|/|) {
                   4584:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4585: 	$path.=$fnamepath.'/';
                   4586:     }
1.259     www      4587:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4588:     my $count;
                   4589:     for ($count=4;$count<=$#parts;$count++) {
                   4590:         $filepath.="/$parts[$count]";
                   4591:         if ((-e $filepath)!=1) {
                   4592: 	    mkdir($filepath,0777);
                   4593:         }
                   4594:     }
1.984     neumanie 4595: 
1.258     www      4596: # Save the file
                   4597:     {
1.1359    raeburn  4598: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4599: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4600: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4601: 	    return '/adm/notfound.html';
                   4602: 	}
1.1090    raeburn  4603:         if ($context eq 'overwrite') {
1.1117    foxr     4604:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4605:             my $target = $filepath.'/'.$file;
                   4606:             if (-e $source) {
                   4607:                 my @info = stat($source);
                   4608:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4609:                     unless (&File::Copy::move($source,$target)) {
                   4610:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4611:                         return "Moving from $source failed";
                   4612:                     }
                   4613:                 } else {
                   4614:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4615:                 }
                   4616:             } else {
                   4617:                 return "Temporary file: $source missing";
                   4618:             }
                   4619:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4620: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4621: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4622: 	    return '/adm/notfound.html';
                   4623: 	}
1.570     albertel 4624: 	close(FH);
1.1051    raeburn  4625:         if ($resizewidth && $resizeheight) {
                   4626:             my $mm = new File::MMagic;
                   4627:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4628:             if ($mime_type =~ m{^image/}) {
                   4629: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4630:             }  
1.977     amueller 4631: 	}
1.258     www      4632:     }
1.1152    raeburn  4633:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4634:         if (ref($mimetype)) {
                   4635:             if ($$mimetype eq '') {
                   4636:                 my $mm = new File::MMagic;
                   4637:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4638:                 $$mimetype = $type;
                   4639:             }
                   4640:         }
                   4641:     }
1.1401    raeburn  4642:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4643:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4644:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4645:                                                        $allfiles,$codebase);
                   4646:             unless ($parse_result eq 'ok') {
                   4647:                 &logthis('Failed to parse '.$filepath.$file.
                   4648: 	   	         ' for embedded media: '.$parse_result); 
                   4649:             }
1.637     raeburn  4650:         }
1.1401    raeburn  4651:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4652:         my $format = $env{'form.scantron_format'};
                   4653:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4654:     }
1.860     raeburn  4655:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4656:         my $input = $filepath.'/'.$file;
                   4657:         my $output = $filepath.'/'.'tn-'.$file;
1.1504    raeburn  4658:         my $makethumb; 
1.860     raeburn  4659:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1504    raeburn  4660:         if ($context eq 'toollogo') {
                   4661:             my ($fullwidth,$fullheight) = &check_dimensions($input);
                   4662:             if ($fullwidth ne '' && $fullheight ne '') {
                   4663:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
                   4664:                     $makethumb = 1;
                   4665:                 }
                   4666:             }
                   4667:         } else {
                   4668:             $makethumb = 1;
                   4669:         }
                   4670:         if ($makethumb) {
                   4671:             my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4672:             system({$args[0]} @args);
                   4673:             if (-e $filepath.'/'.'tn-'.$file) {
                   4674:                 $fetchthumb  = 1; 
                   4675:             }
1.860     raeburn  4676:         }
                   4677:     }
1.858     raeburn  4678:  
1.259     www      4679: # Notify homeserver to grep it
                   4680: #
1.984     neumanie 4681:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4682:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4683:     if ($fetchresult eq 'ok') {
1.860     raeburn  4684:         if ($fetchthumb) {
                   4685:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4686:             if ($thumbresult ne 'ok') {
                   4687:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4688:                          $docuhome.': '.$thumbresult);
                   4689:             }
                   4690:         }
1.259     www      4691: #
1.258     www      4692: # Return the URL to it
1.494     albertel 4693:         return '/uploaded/'.$path.$file;
1.263     www      4694:     } else {
1.494     albertel 4695:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4696: 		 ': '.$fetchresult);
1.263     www      4697:         return '/adm/notfound.html';
1.858     raeburn  4698:     }
1.493     albertel 4699: }
                   4700: 
1.637     raeburn  4701: sub extract_embedded_items {
1.961     raeburn  4702:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4703:     my @state = ();
1.1164    raeburn  4704:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4705:     my %javafiles = (
                   4706:                       codebase => '',
                   4707:                       code => '',
                   4708:                       archive => ''
                   4709:                     );
                   4710:     my %mediafiles = (
                   4711:                       src => '',
                   4712:                       movie => '',
                   4713:                      );
1.648     raeburn  4714:     my $p;
                   4715:     if ($content) {
                   4716:         $p = HTML::LCParser->new($content);
                   4717:     } else {
1.961     raeburn  4718:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4719:     }
1.641     albertel 4720:     while (my $t=$p->get_token()) {
1.640     albertel 4721: 	if ($t->[0] eq 'S') {
                   4722: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4723: 	    push(@state, $tagname);
1.648     raeburn  4724:             if (lc($tagname) eq 'allow') {
                   4725:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4726:             }
1.640     albertel 4727: 	    if (lc($tagname) eq 'img') {
                   4728: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4729: 	    }
1.886     albertel 4730: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4731:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4732:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4733:                 }
1.886     albertel 4734: 	    }
1.645     raeburn  4735:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4736:                 my $src;
1.645     raeburn  4737:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4738:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4739:                 } else {
1.1164    raeburn  4740:                     if ($attr->{'src'} ne '') {
                   4741:                         $src = $attr->{'src'};
                   4742:                         &add_filetype($allfiles,$src,'src');
                   4743:                     }
                   4744:                 }
                   4745:                 my $text = $p->get_trimmed_text();
                   4746:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4747:                     my @swfargs = split(/,/,$1);
                   4748:                     foreach my $item (@swfargs) {
                   4749:                         $item =~ s/["']//g;
                   4750:                         $item =~ s/^\s+//;
                   4751:                         $item =~ s/\s+$//;
                   4752:                     }
                   4753:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4754:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4755:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4756:                         } else {
                   4757:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4758:                         }
                   4759:                     }
1.645     raeburn  4760:                 }
                   4761:             }
                   4762:             if (lc($tagname) eq 'link') {
                   4763:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4764:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4765:                 }
                   4766:             }
1.640     albertel 4767: 	    if (lc($tagname) eq 'object' ||
                   4768: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4769: 		foreach my $item (keys(%javafiles)) {
                   4770: 		    $javafiles{$item} = '';
                   4771: 		}
1.1164    raeburn  4772:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4773:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4774:                 }
1.640     albertel 4775: 	    }
                   4776: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4777: 		my $name = lc($attr->{'name'});
                   4778: 		foreach my $item (keys(%javafiles)) {
                   4779: 		    if ($name eq $item) {
                   4780: 			$javafiles{$item} = $attr->{'value'};
                   4781: 			last;
                   4782: 		    }
                   4783: 		}
1.1164    raeburn  4784:                 my $pathfrom;
1.640     albertel 4785: 		foreach my $item (keys(%mediafiles)) {
                   4786: 		    if ($name eq $item) {
1.1164    raeburn  4787:                         $pathfrom = $attr->{'value'};
                   4788:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4789: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4790: 			last;
                   4791: 		    }
                   4792: 		}
1.1164    raeburn  4793:                 if ($name eq 'flashvars') {
                   4794:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4795:                 }
                   4796:                 if ($pathfrom ne '') {
                   4797:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4798:                                          $pathfrom);
                   4799:                 }
1.640     albertel 4800: 	    }
                   4801: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4802: 		foreach my $item (keys(%javafiles)) {
                   4803: 		    if ($attr->{$item}) {
                   4804: 			$javafiles{$item} = $attr->{$item};
                   4805: 			last;
                   4806: 		    }
                   4807: 		}
                   4808: 		foreach my $item (keys(%mediafiles)) {
                   4809: 		    if ($attr->{$item}) {
                   4810: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4811: 			last;
                   4812: 		    }
                   4813: 		}
1.1164    raeburn  4814:                 if (lc($tagname) eq 'embed') {
                   4815:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4816:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4817:                                              $attr->{'src'});
                   4818:                     }
                   4819:                 }
1.640     albertel 4820: 	    }
1.1243    raeburn  4821:             if (lc($tagname) eq 'iframe') {
                   4822:                 my $src = $attr->{'src'} ;
                   4823:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4824:                     &add_filetype($allfiles,$src,'src');
                   4825:                 } elsif ($src =~ m{^/}) {
                   4826:                     if ($env{'request.course.id'}) {
                   4827:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4828:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4829:                         my $url = &hreflocation('',$fullpath);
                   4830:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4831:                             my $relpath = $1;
                   4832:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4833:                                 &add_filetype($allfiles,$1,'src');
                   4834:                             }
                   4835:                         }
                   4836:                     }
                   4837:                 }
                   4838:             }
1.1164    raeburn  4839:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4840:                 pop(@state);
1.1164    raeburn  4841:             }
1.640     albertel 4842: 	} elsif ($t->[0] eq 'E') {
                   4843: 	    my ($tagname) = ($t->[1]);
                   4844: 	    if ($javafiles{'codebase'} ne '') {
                   4845: 		$javafiles{'codebase'} .= '/';
                   4846: 	    }  
                   4847: 	    if (lc($tagname) eq 'applet' ||
                   4848: 		lc($tagname) eq 'object' ||
                   4849: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4850: 		) {
                   4851: 		foreach my $item (keys(%javafiles)) {
                   4852: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4853: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4854: 			&add_filetype($allfiles,$file,$item);
                   4855: 		    }
                   4856: 		}
                   4857: 	    } 
                   4858: 	    pop @state;
                   4859: 	}
                   4860:     }
1.1164    raeburn  4861:     foreach my $id (sort(keys(%flashvars))) {
                   4862:         if ($shockwave{$id} ne '') {
                   4863:             my @pairs = split(/\&/,$flashvars{$id});
                   4864:             foreach my $pair (@pairs) {
                   4865:                 my ($key,$value) = split(/\=/,$pair);
                   4866:                 if ($key eq 'thumb') {
                   4867:                     &add_filetype($allfiles,$value,$key);
                   4868:                 } elsif ($key eq 'content') {
                   4869:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4870:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4871:                     if ($ext ne '') {
                   4872:                         &add_filetype($allfiles,$path.$value,$ext);
                   4873:                     }
                   4874:                 }
                   4875:             }
                   4876:         }
                   4877:     }
1.637     raeburn  4878:     return 'ok';
                   4879: }
                   4880: 
1.639     albertel 4881: sub add_filetype {
                   4882:     my ($allfiles,$file,$type)=@_;
                   4883:     if (exists($allfiles->{$file})) {
                   4884: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4885: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4886: 	}
                   4887:     } else {
                   4888: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4889:     }
                   4890: }
                   4891: 
1.1164    raeburn  4892: sub embedded_dependency {
                   4893:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4894:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4895:         if (($identifier ne '') &&
                   4896:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4897:             ($pathfrom ne '')) {
                   4898:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4899:             foreach my $dep (@{$related->{$identifier}}) {
                   4900:                 &add_filetype($allfiles,$path.$dep,'object');
                   4901:             }
                   4902:         }
                   4903:     }
                   4904:     return;
                   4905: }
                   4906: 
1.1504    raeburn  4907: sub check_dimensions {
                   4908:     my ($inputfile) = @_;
                   4909:     my ($fullwidth,$fullheight);
                   4910:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
                   4911:         my $mm = new File::MMagic;
                   4912:         my $mime_type = $mm->checktype_filename($inputfile);
                   4913:         if ($mime_type =~ m{^image/}) {
                   4914:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
                   4915:                 my $imageinfo = <PIPE>;
                   4916:                 if (!close(PIPE)) {
                   4917:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
                   4918:                 }
                   4919:                 chomp($imageinfo);
                   4920:                 my ($fullsize) =
                   4921:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
                   4922:                 if ($fullsize) {
                   4923:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
                   4924:                 }
                   4925:             }
                   4926:         }
                   4927:     }
                   4928:     return ($fullwidth,$fullheight);
                   4929: }
                   4930: 
1.1401    raeburn  4931: sub bubblesheet_converter {
                   4932:     my ($cdom,$fullpath,$config,$format) = @_;
                   4933:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4934:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4935:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4936:         my (%csvcols,%csvoptions);
                   4937:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4938:             %csvcols = %{$config->{'fields'}};
                   4939:         }
                   4940:         if (ref($config->{'options'}) eq 'HASH') {
                   4941:             %csvoptions = %{$config->{'options'}};
                   4942:         }
1.1401    raeburn  4943:         my %csvbynum = reverse(%csvcols);
                   4944:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4945:         if (keys(%scantronconf)) {
                   4946:             my %bynum = (
                   4947:                           $scantronconf{CODEstart} => 'CODEstart',
                   4948:                           $scantronconf{IDstart}   => 'IDstart',
                   4949:                           $scantronconf{PaperID}   => 'PaperID',
                   4950:                           $scantronconf{FirstName} => 'FirstName',
                   4951:                           $scantronconf{LastName}  => 'LastName',
                   4952:                           $scantronconf{Qstart}    => 'Qstart',
                   4953:                         );
                   4954:             my @ordered;
                   4955:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4956:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4957:             }
                   4958:             my %mapstart = (
                   4959:                               CODEstart => 'CODE',
                   4960:                               IDstart   => 'ID',
                   4961:                               PaperID   => 'PaperID',
                   4962:                               FirstName => 'FirstName',
                   4963:                               LastName  => 'LastName',
                   4964:                               Qstart    => 'FirstQuestion',
                   4965:                            );
                   4966:             my %maplength = (
                   4967:                               CODEstart => 'CODElength',
                   4968:                               IDstart   => 'IDlength',
                   4969:                               PaperID   => 'PaperIDlength',
                   4970:                               FirstName => 'FirstNamelength',
                   4971:                               LastName  => 'LastNamelength',
                   4972:             );
                   4973:             if (open(my $fh,'<',$fullpath)) {
                   4974:                 my $output;
1.1403    raeburn  4975:                 my %lettdig = &letter_to_digits();
                   4976:                 my %diglett = reverse(%lettdig);
                   4977:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4978:                 my $num = 0;
1.1401    raeburn  4979:                 while (my $line=<$fh>) {
1.1404    raeburn  4980:                     $num ++;
                   4981:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4982:                     $line =~ s{[\r\n]+$}{};
                   4983:                     my %found;
1.1475    raeburn  4984:                     my @values = split(/,/,$line,-1);
1.1401    raeburn  4985:                     my ($qstart,$record);
                   4986:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4987:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4988:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4989:                             if ($values[$i] eq '') {
                   4990:                                 $values[$i] = $scantronconf{'Qoff'};
                   4991:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4992:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4993:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4994:                                 }
                   4995:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4996:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4997:                                     $values[$i] = $diglett{$values[$i]};
                   4998:                                 }
                   4999:                             } else {
                   5000:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   5001:                                     my $digit;
                   5002:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   5003:                                         $digit = $lettdig{uc($values[$i])}-1;
                   5004:                                         if ($values[$i] eq 'J') {
                   5005:                                             $digit += $numletts;
                   5006:                                         }
                   5007:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   5008:                                         $digit = $values[$i]-1;
                   5009:                                         if ($values[$i] eq '0') {
                   5010:                                             $digit += $numletts;
                   5011:                                         }
                   5012:                                     }
                   5013:                                     my $qval='';
                   5014:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   5015:                                         if ($j == $digit) {
                   5016:                                             $qval .= $scantronconf{'Qon'};
                   5017:                                         } else {
                   5018:                                             $qval .= $scantronconf{'Qoff'};
                   5019:                                         }
                   5020:                                     }
                   5021:                                     $values[$i] = $qval;
                   5022:                                 }
                   5023:                             }
                   5024:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   5025:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   5026:                             }
                   5027:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   5028:                             if ($numblank > 0) {
                   5029:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   5030:                             }
1.1401    raeburn  5031:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   5032:                                 $qstart = $i;
1.1403    raeburn  5033:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  5034:                             } else {
1.1403    raeburn  5035:                                 $found{'FirstQuestion'} .= $values[$i];
                   5036:                             }
                   5037:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  5038:                             if ($csvoptions{'rem'}) {
                   5039:                                 $values[$i] =~ s/^\s+//;
                   5040:                             }
                   5041:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  5042:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   5043:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  5044:                                 }
                   5045:                             }
                   5046:                             $found{$csvbynum{$i}} = $values[$i];
                   5047:                         }
                   5048:                     }
                   5049:                     foreach my $item (@ordered) {
                   5050:                         my $currlength = 1+length($record);
                   5051:                         my $numspaces = $scantronconf{$item} - $currlength;
                   5052:                         if ($numspaces > 0) {
                   5053:                             $record .= (' ' x $numspaces);
                   5054:                         }
                   5055:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   5056:                             unless ($item eq 'Qstart') {
                   5057:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   5058:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   5059:                                 }
                   5060:                             }
                   5061:                             $record .= $found{$mapstart{$item}};
                   5062:                         }
                   5063:                     }
                   5064:                     $output .= "$record\n";
                   5065:                 }
                   5066:                 close($fh);
                   5067:                 if ($output) {
                   5068:                     if (open(my $fh,'>',$fullpath)) {
                   5069:                         print $fh $output;
                   5070:                         close($fh);
                   5071:                     }
                   5072:                 }
                   5073:             }
                   5074:         }
                   5075:         return;
                   5076:     }
                   5077: }
                   5078: 
1.1403    raeburn  5079: sub letter_to_digits {
                   5080:     my %lettdig = (
                   5081:                     A => 1,
                   5082:                     B => 2,
                   5083:                     C => 3,
                   5084:                     D => 4,
                   5085:                     E => 5,
                   5086:                     F => 6,
                   5087:                     G => 7,
                   5088:                     H => 8,
                   5089:                     I => 9,
                   5090:                     J => 0,
                   5091:                   );
                   5092:     return %lettdig;
                   5093: }
                   5094: 
1.1401    raeburn  5095: sub get_scantron_config {
                   5096:     my ($which,$cdom) = @_;
                   5097:     my @lines = &get_scantronformat_file($cdom);
                   5098:     my %config;
                   5099:     #FIXME probably should move to XML it has already gotten a bit much now
                   5100:     foreach my $line (@lines) {
                   5101:         my ($name,$descrip)=split(/:/,$line);
                   5102:         if ($name ne $which ) { next; }
                   5103:         chomp($line);
                   5104:         my @config=split(/:/,$line);
                   5105:         $config{'name'}=$config[0];
                   5106:         $config{'description'}=$config[1];
                   5107:         $config{'CODElocation'}=$config[2];
                   5108:         $config{'CODEstart'}=$config[3];
                   5109:         $config{'CODElength'}=$config[4];
                   5110:         $config{'IDstart'}=$config[5];
                   5111:         $config{'IDlength'}=$config[6];
                   5112:         $config{'Qstart'}=$config[7];
                   5113:         $config{'Qlength'}=$config[8];
                   5114:         $config{'Qoff'}=$config[9];
                   5115:         $config{'Qon'}=$config[10];
                   5116:         $config{'PaperID'}=$config[11];
                   5117:         $config{'PaperIDlength'}=$config[12];
                   5118:         $config{'FirstName'}=$config[13];
                   5119:         $config{'FirstNamelength'}=$config[14];
                   5120:         $config{'LastName'}=$config[15];
                   5121:         $config{'LastNamelength'}=$config[16];
                   5122:         $config{'BubblesPerRow'}=$config[17];
                   5123:         last;
                   5124:     }
                   5125:     return %config;
                   5126: }
                   5127: 
                   5128: sub get_scantronformat_file {
                   5129:     my ($cdom) = @_;
                   5130:     if ($cdom eq '') {
                   5131:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5132:     }
                   5133:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   5134:     my $gottab = 0;
                   5135:     my @lines;
                   5136:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5137:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5138:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5139:             if ($formatfile ne '-1') {
                   5140:                 @lines = split("\n",$formatfile,-1);
                   5141:                 $gottab = 1;
                   5142:             }
                   5143:         }
                   5144:     }
                   5145:     if (!$gottab) {
                   5146:         my $confname = $cdom.'-domainconfig';
                   5147:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5148:         my $formatfile = &getfile($default);
                   5149:         if ($formatfile ne '-1') {
                   5150:             @lines = split("\n",$formatfile,-1);
                   5151:             $gottab = 1;
                   5152:         }
                   5153:     }
                   5154:     if (!$gottab) {
                   5155:         my @domains = &current_machine_domains();
                   5156:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5157:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   5158:                 @lines = <$fh>;
                   5159:                 close($fh);
1.1403    raeburn  5160:             }
1.1401    raeburn  5161:         } else {
                   5162:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   5163:                 @lines = <$fh>;
                   5164:                 close($fh);
                   5165:             }
                   5166:         }
1.1488    raeburn  5167:         chomp(@lines);
1.1401    raeburn  5168:     }
                   5169:     return @lines;
                   5170: }
                   5171: 
1.493     albertel 5172: sub removeuploadedurl {
1.984     neumanie 5173:     my ($url)=@_;	
                   5174:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 5175:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 5176: }
                   5177: 
                   5178: sub removeuserfile {
                   5179:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 5180:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  5181:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 5182:     if ($result eq 'ok') {	
1.798     raeburn  5183:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   5184:             my $metafile = $fname.'.meta';
                   5185:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 5186: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 5187:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  5188:             my $sqlresult = 
1.823     albertel 5189:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  5190:                                         'portfolio_metadata',$group,
                   5191:                                         'delete');
1.798     raeburn  5192:         }
                   5193:     }
                   5194:     return $result;
1.257     www      5195: }
1.15      www      5196: 
1.530     albertel 5197: sub mkdiruserfile {
                   5198:     my ($docuname,$docudom,$dir)=@_;
                   5199:     my $home=&homeserver($docuname,$docudom);
                   5200:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   5201: }
                   5202: 
1.531     albertel 5203: sub renameuserfile {
                   5204:     my ($docuname,$docudom,$old,$new)=@_;
                   5205:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  5206:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   5207:                         &escape("$old").':'.&escape("$new"),$home);
                   5208:     if ($result eq 'ok') {
                   5209:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   5210:             my $oldmeta = $old.'.meta';
                   5211:             my $newmeta = $new.'.meta';
                   5212:             my $metaresult = 
                   5213:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 5214: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   5215:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  5216:             my $sqlresult = 
1.823     albertel 5217:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  5218:                                         'portfolio_metadata',$group,
                   5219:                                         'delete');
1.798     raeburn  5220:         }
                   5221:     }
                   5222:     return $result;
1.531     albertel 5223: }
                   5224: 
1.14      www      5225: # ------------------------------------------------------------------------- Log
                   5226: 
                   5227: sub log {
                   5228:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      5229:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      5230: }
                   5231: 
                   5232: # ------------------------------------------------------------------ Course Log
1.352     www      5233: #
                   5234: # This routine flushes several buffers of non-mission-critical nature
                   5235: #
1.157     www      5236: 
                   5237: sub flushcourselogs {
1.352     www      5238:     &logthis('Flushing log buffers');
                   5239: #
                   5240: # course logs
                   5241: # This is a log of all transactions in a course, which can be used
                   5242: # for data mining purposes
                   5243: #
                   5244: # It also collects the courseid database, which lists last transaction
                   5245: # times and course titles for all courseids
                   5246: #
                   5247:     my %courseidbuffer=();
1.921     raeburn  5248:     foreach my $crsid (keys(%courselogs)) {
1.352     www      5249:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      5250: 		          &escape($courselogs{$crsid}),
                   5251: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      5252: 	    delete $courselogs{$crsid};
                   5253:         } else {
                   5254:             &logthis('Failed to flush log buffer for '.$crsid);
                   5255:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 5256:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      5257:                         " exceeded maximum size, deleting.</font>");
                   5258:                delete $courselogs{$crsid};
                   5259:             }
1.352     www      5260:         }
1.920     raeburn  5261:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  5262:             'description' => $coursedescrbuf{$crsid},
                   5263:             'inst_code'    => $courseinstcodebuf{$crsid},
                   5264:             'type'        => $coursetypebuf{$crsid},
                   5265:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  5266:         };
1.191     harris41 5267:     }
1.352     www      5268: #
                   5269: # Write course id database (reverse lookup) to homeserver of courses 
                   5270: # Is used in pickcourse
                   5271: #
1.840     albertel 5272:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  5273:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  5274:                                     $courseidbuffer{$crs_home},
                   5275:                                     $crs_home,'timeonly');
1.352     www      5276:     }
                   5277: #
                   5278: # File accesses
                   5279: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   5280: #
1.449     matthew  5281:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  5282:         if ($entry =~ /___count$/) {
                   5283:             my ($dom,$name);
1.807     albertel 5284:             ($dom,$name,undef)=
1.811     albertel 5285: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  5286:             if (! defined($dom) || $dom eq '' || 
                   5287:                 ! defined($name) || $name eq '') {
1.620     albertel 5288:                 my $cid = $env{'request.course.id'};
1.1472    raeburn  5289: #
                   5290: # FIXME 11/29/2021
                   5291: # Typo in rev. 1.458 (2003/12/09)??
                   5292: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   5293: #
1.1509    raeburn  5294: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1472    raeburn  5295: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   5296: # in a nohist_accesscount.db file for the user rather than the course.
                   5297: #
                   5298: # That said there is a lot of noise in the data being stored.
                   5299: # So counts for prtspool/  and adm/ etc. are recorded.
                   5300: #
                   5301: # A review of which items ending '___count' are written to %accesshash should likely be 
                   5302: # made before deciding whether to set these to 'course.' instead of 'request.'
                   5303: #
                   5304: # Under the current scheme each user receives a nohist_accesscount.db file listing 
                   5305: # accesses for things which are not published resources, regardless of course, and
                   5306: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   5307: # anyone in the course for things which are not published resources.
                   5308: #
                   5309: # For an author, nohist_accesscount.db ends up having records for other items
                   5310: # mixed up with the legitimate access counts for the author's published resources.
                   5311: #
1.620     albertel 5312:                 $dom  = $env{'request.'.$cid.'.domain'};
                   5313:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  5314:             }
1.450     matthew  5315:             my $value = $accesshash{$entry};
                   5316:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   5317:             my %temphash=($url => $value);
1.449     matthew  5318:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   5319:             if ($result eq 'ok') {
                   5320:                 delete $accesshash{$entry};
                   5321:             }
                   5322:         } else {
1.811     albertel 5323:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      5324:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  5325:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  5326:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   5327:                 delete $accesshash{$entry};
                   5328:             }
1.185     www      5329:         }
1.191     harris41 5330:     }
1.352     www      5331: #
                   5332: # Roles
                   5333: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   5334: #
1.800     albertel 5335:     foreach my $entry (keys(%userrolehash)) {
1.351     www      5336:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      5337: 	    split(/\:/,$entry);
1.1494    raeburn  5338:         if (&put('nohist_userroles',
1.351     www      5339:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      5340:                 $rudom,$runame) eq 'ok') {
                   5341: 	    delete $userrolehash{$entry};
                   5342:         }
                   5343:     }
1.662     raeburn  5344: #
1.1334    raeburn  5345: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5346: #
                   5347:     my %domrolebuffer = ();
1.1000    raeburn  5348:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5349:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5350:         if ($domrolebuffer{$rudom}) {
                   5351:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5352:                       '='.&escape($domainrolehash{$entry});
                   5353:         } else {
                   5354:             $domrolebuffer{$rudom}.=&escape($entry).
                   5355:                       '='.&escape($domainrolehash{$entry});
                   5356:         }
                   5357:         delete $domainrolehash{$entry};
                   5358:     }
                   5359:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  5360: 	my %servers;
                   5361: 	if (defined(&domain($dom,'primary'))) {
                   5362: 	    my $primary=&domain($dom,'primary');
                   5363: 	    my $hostname=&hostname($primary);
                   5364: 	    $servers{$primary} = $hostname;
                   5365: 	} else { 
                   5366: 	    %servers = &get_servers($dom,'library');
                   5367: 	}
1.841     albertel 5368: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  5369: 	    if (&reply('domroleput:'.$dom.':'.
                   5370: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5371: 		last;
                   5372: 	    } else {  
1.841     albertel 5373: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5374: 	    }
1.662     raeburn  5375:         }
                   5376:     }
1.186     www      5377:     $dumpcount++;
1.157     www      5378: }
                   5379: 
                   5380: sub courselog {
                   5381:     my $what=shift;
1.158     www      5382:     $what=time.':'.$what;
1.620     albertel 5383:     unless ($env{'request.course.id'}) { return ''; }
                   5384:     $coursedombuf{$env{'request.course.id'}}=
                   5385:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5386:     $coursenumbuf{$env{'request.course.id'}}=
                   5387:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5388:     $coursehombuf{$env{'request.course.id'}}=
                   5389:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5390:     $coursedescrbuf{$env{'request.course.id'}}=
                   5391:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5392:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5393:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5394:     $courseownerbuf{$env{'request.course.id'}}=
                   5395:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5396:     $coursetypebuf{$env{'request.course.id'}}=
                   5397:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5398:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5399: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5400:     } else {
1.620     albertel 5401: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5402:     }
1.620     albertel 5403:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5404: 	&flushcourselogs();
                   5405:     }
1.158     www      5406: }
                   5407: 
                   5408: sub courseacclog {
                   5409:     my $fnsymb=shift;
1.620     albertel 5410:     unless ($env{'request.course.id'}) { return ''; }
                   5411:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5412:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5413:         $what.=':POST';
1.583     matthew  5414:         # FIXME: Probably ought to escape things....
1.800     albertel 5415: 	foreach my $key (keys(%env)) {
                   5416:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5417:                 my $formitem = $1;
                   5418:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5419:                     $what.=':'.$formitem.'='.$env{$key};
                   5420:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5421:                     if ($formitem eq 'proctorpassword') {
1.1433    raeburn  5422:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5423:                     } else {
                   5424:                         $what.=':'.$formitem.'='.$env{$key};
                   5425:                     }
1.975     raeburn  5426:                 }
1.158     www      5427:             }
1.191     harris41 5428:         }
1.583     matthew  5429:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5430:         # FIXME: We should not be depending on a form parameter that someone
                   5431:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5432:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5433:             $what.= ':POST';
                   5434:             # FIXME: Probably ought to escape things....
                   5435:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5436:                                  'crsdiscuss') {
1.620     albertel 5437:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5438:             }
                   5439:         }
1.158     www      5440:     }
                   5441:     &courselog($what);
1.149     www      5442: }
                   5443: 
1.185     www      5444: sub countacc {
                   5445:     my $url=&declutter(shift);
1.458     matthew  5446:     return if (! defined($url) || $url eq '');
1.620     albertel 5447:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5448: #
                   5449: # Mark that this url was used in this course
                   5450: #
1.620     albertel 5451:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5452: #
                   5453: # Increase the access count for this resource in this child process
                   5454: #
1.281     www      5455:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5456:     $accesshash{$key}++;
1.185     www      5457: }
1.349     www      5458: 
1.361     www      5459: sub linklog {
                   5460:     my ($from,$to)=@_;
                   5461:     $from=&declutter($from);
                   5462:     $to=&declutter($to);
                   5463:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5464:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5465: }
1.1160    www      5466: 
                   5467: sub statslog {
                   5468:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5469:     if ($users<2) { return; }
                   5470:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5471:             'course'       => $env{'request.course.id'},
                   5472:             'sections'     => '"all"',
                   5473:             'num_students' => $users,
                   5474:             'part'         => $part,
                   5475:             'symb'         => $symb,
                   5476:             'mean_tries'   => $av_attempts,
                   5477:             'deg_of_diff'  => $degdiff});
                   5478:     foreach my $key (keys(%dynstore)) {
                   5479:         $accesshash{$key}=$dynstore{$key};
                   5480:     }
                   5481: }
1.361     www      5482:   
1.349     www      5483: sub userrolelog {
                   5484:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5485:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5486:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5487:        $userrolehash
                   5488:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5489:                     =$tend.':'.$tstart;
1.662     raeburn  5490:     }
1.1169    droeschl 5491:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5492:        $userrolehash
                   5493:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5494:                     =$tend.':'.$tstart;
                   5495:     }
1.1334    raeburn  5496:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5497:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5498:        $domainrolehash
                   5499:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5500:                     = $tend.':'.$tstart;
                   5501:     }
1.351     www      5502: }
                   5503: 
1.957     raeburn  5504: sub courserolelog {
1.1512    raeburn  5505:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
                   5506:         $context,$othdomby,$requester)=@_;
1.1184    raeburn  5507:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5508:         my $cdom = $1;
                   5509:         my $cnum = $2;
                   5510:         my $sec = $3;
                   5511:         my $namespace = 'rolelog';
                   5512:         my %storehash = (
                   5513:                            role    => $trole,
                   5514:                            start   => $tstart,
                   5515:                            end     => $tend,
                   5516:                            selfenroll => $selfenroll,
                   5517:                            context    => $context,
                   5518:                         );
1.1512    raeburn  5519:         if ($othdomby) {
                   5520:             if ($othdomby eq 'othdombydc') {
                   5521:                 $storehash{'approval'} = 'domain';
                   5522:             } elsif ($othdomby eq 'othdombyuser') {
                   5523:                 $storehash{'approval'} = 'user'; 
                   5524:             }
                   5525:             if ($requester ne '') {
                   5526:                 $storehash{'requester'} = $requester;
                   5527:             }
                   5528:         }
1.1184    raeburn  5529:         if ($trole eq 'gr') {
                   5530:             $namespace = 'groupslog';
                   5531:             $storehash{'group'} = $sec;
                   5532:         } else {
                   5533:             $storehash{'section'} = $sec;
1.1516    raeburn  5534:             my ($curruserdomstr,$newuserdomstr);
1.1515    raeburn  5535:             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
                   5536:                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
1.1516    raeburn  5537:             } else {
1.1515    raeburn  5538:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
                   5539:                 $curruserdomstr = $courseinfo{'internal.userdomains'};
                   5540:             }
1.1516    raeburn  5541:             if ($curruserdomstr ne '') {
                   5542:                 my @udoms = split(/,/,$curruserdomstr);
1.1515    raeburn  5543:                 unless (grep(/^\Q$domain\E/,@udoms)) {
                   5544:                     push(@udoms,$domain);
                   5545:                     $newuserdomstr = join(',',sort(@udoms));
                   5546:                 }
                   5547:             } else {
                   5548:                 $newuserdomstr = $domain;
                   5549:             }
                   5550:             if ($newuserdomstr ne '') {
                   5551:                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
                   5552:                                      $cdom,$cnum);
                   5553:                 if ($putresult eq 'ok') {
                   5554:                     unless (($selfenroll) || ($context eq 'selfenroll')) { 
                   5555:                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
                   5556:                             ($context eq 'automated') || ($context eq 'domain')) {
                   5557:                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
                   5558:                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   5559:                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
                   5560:                         }
                   5561:                     }
                   5562:                 }
                   5563:             }
1.1184    raeburn  5564:         }
1.1188    raeburn  5565:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5566:                    $domain,$cnum,$cdom);
1.1184    raeburn  5567:         if (($trole ne 'st') || ($sec ne '')) {
                   5568:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5569:         }
                   5570:     }
                   5571:     return;
                   5572: }
                   5573: 
1.1184    raeburn  5574: sub domainrolelog {
1.1512    raeburn  5575:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
                   5576:         $context,$othdomby,$requester)=@_;
1.1184    raeburn  5577:     if ($area =~ m{^/($match_domain)/$}) {
                   5578:         my $cdom = $1;
1.1494    raeburn  5579:         my $domconfiguser = &get_domainconfiguser($cdom);
1.1184    raeburn  5580:         my $namespace = 'rolelog';
                   5581:         my %storehash = (
                   5582:                            role    => $trole,
                   5583:                            start   => $tstart,
                   5584:                            end     => $tend,
                   5585:                            context => $context,
                   5586:                         );
1.1512    raeburn  5587:         if ($othdomby) {
                   5588:             if ($othdomby eq 'othdombydc') {
                   5589:                 $storehash{'approval'} = 'domain';
                   5590:             } elsif ($othdomby eq 'othdombyuser') {
                   5591:                 $storehash{'approval'} = 'user';
                   5592:             }
                   5593:             if ($requester ne '') {
                   5594:                 $storehash{'requester'} = $requester;
                   5595:             }
                   5596:         }
1.1188    raeburn  5597:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5598:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5599:     }
                   5600:     return;
                   5601: 
                   5602: }
                   5603: 
                   5604: sub coauthorrolelog {
1.1512    raeburn  5605:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
                   5606:         $context,$othdomby,$requester)=@_;
1.1184    raeburn  5607:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5608:         my $audom = $1;
                   5609:         my $auname = $2;
                   5610:         my $namespace = 'rolelog';
                   5611:         my %storehash = (
                   5612:                            role    => $trole,
                   5613:                            start   => $tstart,
                   5614:                            end     => $tend,
                   5615:                            context => $context,
                   5616:                         );
1.1512    raeburn  5617:         if ($othdomby) {
                   5618:             if ($othdomby eq 'othdombydc') {
                   5619:                 $storehash{'approval'} = 'domain';
                   5620:             } elsif ($othdomby eq 'othdombyuser') {
                   5621:                 $storehash{'approval'} = 'user';
                   5622:             }
                   5623:             if ($requester ne '') {
                   5624:                 $storehash{'requester'} = $requester;
                   5625:             }
                   5626:         }
1.1188    raeburn  5627:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5628:                    $domain,$auname,$audom);
1.1184    raeburn  5629:     }
                   5630:     return;
                   5631: }
                   5632: 
1.1527    raeburn  5633: sub authorarchivelog {
                   5634:     my ($hashref,$size,$filesdest,$action) = @_;
                   5635:     my $lonprtdir = $Apache::lonnet::perlvar{'lonPrtDir'};
                   5636:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   5637:     $filesdest =~ s{^\Q$lonprtdir/\E}{};
                   5638:     if ($filesdest =~ m{^($match_username)_($match_domain)_archive_(\d+_\d+_\d+(|[.\w]+))$}) {
                   5639:         my ($auname,$audom,$id) = ($1,$2,$3);
                   5640:         if (ref($hashref) eq 'HASH') {
                   5641:             my $namespace = 'archivelog';
                   5642:             my $dir;
                   5643:             if ($hashref->{dir} =~ m{^\Q$londocroot/priv/$audom/$auname\E(.*)$}) {
                   5644:                 $dir = $1;
                   5645:             }
                   5646:             my $delflag = 0;
                   5647:             my %storehash = (
                   5648:                               id      => $id,
                   5649:                               dir     => $dir,
                   5650:                               files   => $hashref->{numfiles},
                   5651:                               subdirs => $hashref->{numdirs},
                   5652:                               bytes   => $hashref->{bytes},
                   5653:                               size    => $size,
                   5654:                               action  => $action,
                   5655:                             );
                   5656:             if ($action eq 'delete') {
                   5657:                 $delflag = 1;
                   5658:             }
                   5659:             &write_log('author',$namespace,\%storehash,$delflag,$auname,
                   5660:                        $audom,$auname,$audom);
                   5661:         }
                   5662:     }
                   5663:     return;
                   5664: }
                   5665: 
1.351     www      5666: sub get_course_adv_roles {
1.948     raeburn  5667:     my ($cid,$codes) = @_;
1.620     albertel 5668:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5669:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5670:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5671:     my %nothide=();
1.800     albertel 5672:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5673:         if ($user !~ /:/) {
                   5674: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5675:         } else {
                   5676:             $nothide{$user}=1;
                   5677:         }
1.470     www      5678:     }
1.1219    raeburn  5679:     my @possdoms = ($coursehash{'domain'});
                   5680:     if ($coursehash{'checkforpriv'}) {
                   5681:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5682:     }
1.351     www      5683:     my %returnhash=();
                   5684:     my %dumphash=
                   5685:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5686:     my $now=time;
1.997     raeburn  5687:     my %privileged;
1.1000    raeburn  5688:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5689: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5690:         if (($tstart) && ($tstart<0)) { next; }
                   5691:         if (($tend) && ($tend<$now)) { next; }
                   5692:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5693:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5694: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5695:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5696:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5697: 	if ($role eq 'cr') { next; }
1.948     raeburn  5698:         if ($codes) {
                   5699:             if ($section) { $role .= ':'.$section; }
                   5700:             if ($returnhash{$role}) {
                   5701:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5702:             } else {
                   5703:                 $returnhash{$role}=$username.':'.$domain;
                   5704:             }
1.351     www      5705:         } else {
1.988     raeburn  5706:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5707:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5708:             if ($returnhash{$key}) {
                   5709: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5710:             } else {
                   5711:                 $returnhash{$key}=$username.':'.$domain;
                   5712:             }
1.351     www      5713:         }
1.948     raeburn  5714:     }
1.400     www      5715:     return %returnhash;
                   5716: }
                   5717: 
                   5718: sub get_my_roles {
1.937     raeburn  5719:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5720:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5721:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5722:     my (%dumphash,%nothide);
1.1086    raeburn  5723:     if ($context eq 'userroles') {
1.1166    raeburn  5724:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5725:     } else {
1.1219    raeburn  5726:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5727:         if ($hidepriv) {
                   5728:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5729:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5730:                 if ($user !~ /:/) {
                   5731:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5732:                 } else {
                   5733:                     $nothide{$user} = 1;
                   5734:                 }
                   5735:             }
                   5736:         }
1.858     raeburn  5737:     }
1.400     www      5738:     my %returnhash=();
                   5739:     my $now=time;
1.999     raeburn  5740:     my %privileged;
1.800     albertel 5741:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5742:         my ($role,$tend,$tstart);
                   5743:         if ($context eq 'userroles') {
1.1149    raeburn  5744:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5745: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5746:         } else {
                   5747:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5748:         }
1.400     www      5749:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5750:         my $status = 'active';
1.939     raeburn  5751:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5752:             $status = 'previous';
                   5753:         } 
                   5754:         if (($tstart) && ($now<$tstart)) {
                   5755:             $status = 'future';
                   5756:         }
                   5757:         if (ref($types) eq 'ARRAY') {
                   5758:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5759:                 next;
                   5760:             } 
                   5761:         } else {
                   5762:             if ($status ne 'active') {
                   5763:                 next;
                   5764:             }
                   5765:         }
1.867     raeburn  5766:         my ($rolecode,$username,$domain,$section,$area);
                   5767:         if ($context eq 'userroles') {
1.1186    raeburn  5768:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5769:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5770:         } else {
                   5771:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5772:         }
1.832     raeburn  5773:         if (ref($roledoms) eq 'ARRAY') {
                   5774:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5775:                 next;
                   5776:             }
                   5777:         }
                   5778:         if (ref($roles) eq 'ARRAY') {
                   5779:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5780:                 if ($role =~ /^cr\//) {
                   5781:                     if (!grep(/^cr$/,@{$roles})) {
                   5782:                         next;
                   5783:                     }
1.1104    raeburn  5784:                 } elsif ($role =~ /^gr\//) {
                   5785:                     if (!grep(/^gr$/,@{$roles})) {
                   5786:                         next;
                   5787:                     }
1.922     raeburn  5788:                 } else {
                   5789:                     next;
                   5790:                 }
1.832     raeburn  5791:             }
1.867     raeburn  5792:         }
1.937     raeburn  5793:         if ($hidepriv) {
1.1219    raeburn  5794:             my @privroles = ('dc','su');
1.999     raeburn  5795:             if ($context eq 'userroles') {
1.1219    raeburn  5796:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5797:             } else {
1.1219    raeburn  5798:                 my $possdoms = [$domain];
                   5799:                 if (ref($roledoms) eq 'ARRAY') {
                   5800:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5801:                 }
1.1219    raeburn  5802:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5803:                     if (!$nothide{$username.':'.$domain}) {
                   5804:                         next;
                   5805:                     }
                   5806:                 }
1.937     raeburn  5807:             }
                   5808:         }
1.933     raeburn  5809:         if ($withsec) {
                   5810:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5811:                 $tstart.':'.$tend;
                   5812:         } else {
                   5813:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5814:         }
1.832     raeburn  5815:     }
1.373     www      5816:     return %returnhash;
1.399     www      5817: }
                   5818: 
1.1333    raeburn  5819: sub get_all_adhocroles {
                   5820:     my ($dom) = @_;
                   5821:     my @roles_by_num = ();
                   5822:     my %domdefaults = &get_domain_defaults($dom);
                   5823:     my (%description,%access_in_dom,%access_info);
                   5824:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5825:         my $count = 0;
                   5826:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5827:         my %ordered;
                   5828:         foreach my $role (sort(keys(%domcurrent))) {
                   5829:             my ($order,$desc,$access_in_dom);
                   5830:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5831:                 $order = $domcurrent{$role}{'order'};
                   5832:                 $desc = $domcurrent{$role}{'desc'};
                   5833:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5834:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5835:             }
                   5836:             if ($order eq '') {
                   5837:                 $order = $count;
                   5838:             }
                   5839:             $ordered{$order} = $role;
                   5840:             if ($desc ne '') {
                   5841:                 $description{$role} = $desc;
                   5842:             } else {
                   5843:                 $description{$role}= $role;
                   5844:             }
                   5845:             $count++;
                   5846:         }
                   5847:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5848:             push(@roles_by_num,$ordered{$item});
                   5849:         }
                   5850:     }
                   5851:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5852: }
                   5853: 
1.1332    raeburn  5854: sub get_my_adhocroles {
1.1333    raeburn  5855:     my ($cid,$checkreg) = @_;
                   5856:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5857:     if ($env{'request.course.id'} eq $cid) {
                   5858:         $cdom = $env{'course.'.$cid.'.domain'};
                   5859:         $cnum = $env{'course.'.$cid.'.num'};
                   5860:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5861:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5862:         $cdom = $1;
                   5863:         $cnum = $2;
1.1494    raeburn  5864:         %info = &get('environment',['internal.coursecode'],
                   5865:                      $cdom,$cnum);
1.1333    raeburn  5866:     }
                   5867:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5868:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5869:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5870:         if ($rosterhash{$user} ne '') {
                   5871:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5872:             return ([],{}) if ($type eq 'auto');
                   5873:         }
                   5874:     }
                   5875:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5876:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5877:             my $then=$env{'user.login.time'};
                   5878:             my $update=$env{'user.update.time'};
1.1335    raeburn  5879:             if (!$update) {
                   5880:                 $update = $then;
                   5881:             }
                   5882:             my @liveroles;
1.1334    raeburn  5883:             foreach my $role ('dh','da') {
                   5884:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5885:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5886:                     my $limit = $update;
                   5887:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5888:                         $limit = $then;
                   5889:                     }
1.1335    raeburn  5890:                     my $activerole = 1;
                   5891:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5892:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5893:                     if ($activerole) {
                   5894:                         push(@liveroles,$role);
                   5895:                     }
1.1334    raeburn  5896:                 }
1.1332    raeburn  5897:             }
1.1335    raeburn  5898:             if (@liveroles) {
1.1332    raeburn  5899:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5900:                     my ($accessref,$accessinfo,%access_in_dom);
                   5901:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5902:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5903:                         if (@{$roles_by_num}) {
1.1332    raeburn  5904:                             my %settings;
                   5905:                             if ($env{'request.course.id'} eq $cid) {
                   5906:                                 foreach my $envkey (keys(%env)) {
                   5907:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5908:                                         $settings{$1} = $env{$envkey};
                   5909:                                     }
                   5910:                                 }
                   5911:                             } else {
                   5912:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5913:                             }
                   5914:                             my %setincrs;
                   5915:                             if ($settings{'internal.adhocaccess'}) {
                   5916:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5917:                             }
                   5918:                             my @statuses;
                   5919:                             if ($env{'environment.inststatus'}) {
                   5920:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5921:                             }
                   5922:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5923:                             if (ref($accessref) eq 'HASH') {
                   5924:                                 %access_in_dom = %{$accessref};
                   5925:                             }
                   5926:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5927:                                 my ($curraccess,@okstatus,@personnel);
                   5928:                                 if ($setincrs{$role}) {
                   5929:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5930:                                     if ($curraccess eq 'status') {
                   5931:                                         @okstatus = split(/\&/,$rest);
                   5932:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5933:                                         @personnel = split(/\&/,$rest);
                   5934:                                     }
                   5935:                                 } else {
                   5936:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5937:                                     if (ref($accessinfo) eq 'HASH') {
                   5938:                                         if ($curraccess eq 'status') {
                   5939:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5940:                                                 @okstatus = @{$accessinfo->{$role}};
                   5941:                                             }
                   5942:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5943:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5944:                                                 @personnel = @{$accessinfo->{$role}};
                   5945:                                             }
1.1332    raeburn  5946:                                         }
                   5947:                                     }
                   5948:                                 }
                   5949:                                 if ($curraccess eq 'none') {
                   5950:                                     next;
                   5951:                                 } elsif ($curraccess eq 'all') {
                   5952:                                     push(@possroles,$role);
1.1336    raeburn  5953:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5954:                                     if (grep(/^dh$/,@liveroles)) {
                   5955:                                         push(@possroles,$role);
                   5956:                                     } else {
                   5957:                                         next;
                   5958:                                     }
1.1336    raeburn  5959:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5960:                                     if (grep(/^da$/,@liveroles)) {
                   5961:                                         push(@possroles,$role);
                   5962:                                     } else {
                   5963:                                         next;
                   5964:                                     }
1.1332    raeburn  5965:                                 } elsif ($curraccess eq 'status') {
                   5966:                                     if (@okstatus) {
                   5967:                                         if (!@statuses) {
                   5968:                                             if (grep(/^default$/,@okstatus)) {
                   5969:                                                 push(@possroles,$role);
                   5970:                                             }
                   5971:                                         } else {
                   5972:                                             foreach my $status (@okstatus) {
                   5973:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5974:                                                     push(@possroles,$role);
                   5975:                                                     last;
                   5976:                                                 }
                   5977:                                             }
                   5978:                                         }
                   5979:                                     }
                   5980:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5981:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5982:                                         if ($curraccess eq 'exc') {
                   5983:                                             push(@possroles,$role);
                   5984:                                         }
                   5985:                                     } elsif ($curraccess eq 'inc') {
                   5986:                                         push(@possroles,$role);
                   5987:                                     }
                   5988:                                 }
                   5989:                             }
                   5990:                         }
                   5991:                     }
                   5992:                 }
                   5993:             }
                   5994:         }
                   5995:     }
1.1333    raeburn  5996:     unless (ref($description) eq 'HASH') {
                   5997:         if (ref($roles_by_num) eq 'ARRAY') {
                   5998:             my %desc;
                   5999:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   6000:             $description = \%desc;
                   6001:         } else {
                   6002:             $description = {};
                   6003:         }
                   6004:     }
                   6005:     return (\@possroles,$description);
1.1332    raeburn  6006: }
                   6007: 
1.399     www      6008: # ----------------------------------------------------- Frontpage Announcements
                   6009: #
                   6010: #
                   6011: 
                   6012: sub postannounce {
                   6013:     my ($server,$text)=@_;
1.844     albertel 6014:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      6015:     unless ($text=~/\w/) { $text=''; }
                   6016:     return &reply('setannounce:'.&escape($text),$server);
                   6017: }
                   6018: 
                   6019: sub getannounce {
1.448     albertel 6020: 
1.1359    raeburn  6021:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      6022: 	my $announcement='';
1.800     albertel 6023: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 6024: 	close($fh);
1.399     www      6025: 	if ($announcement=~/\w/) { 
                   6026: 	    return 
                   6027:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 6028:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      6029: 	} else {
                   6030: 	    return '';
                   6031: 	}
                   6032:     } else {
                   6033: 	return '';
                   6034:     }
1.351     www      6035: }
1.353     www      6036: 
                   6037: # ---------------------------------------------------------- Course ID routines
                   6038: # Deal with domain's nohist_courseid.db files
                   6039: #
                   6040: 
                   6041: sub courseidput {
1.921     raeburn  6042:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  6043:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  6044:     my $outcome;
                   6045:     if ($caller eq 'timeonly') {
                   6046:         my $cids = '';
                   6047:         foreach my $item (keys(%$storehash)) {
                   6048:             $cids.=&escape($item).'&';
                   6049:         }
                   6050:         $cids=~s/\&$//;
                   6051:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   6052:                           $coursehome);       
                   6053:     } else {
                   6054:         my $items = '';
                   6055:         foreach my $item (keys(%$storehash)) {
                   6056:             $items.= &escape($item).'='.
                   6057:                      &freeze_escape($$storehash{$item}).'&';
                   6058:         }
                   6059:         $items=~s/\&$//;
                   6060:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   6061:                           $coursehome);
1.918     raeburn  6062:     }
                   6063:     if ($outcome eq 'unknown_cmd') {
                   6064:         my $what;
                   6065:         foreach my $cid (keys(%$storehash)) {
                   6066:             $what .= &escape($cid).'=';
1.921     raeburn  6067:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  6068:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  6069:             }
                   6070:             $what =~ s/\:$/&/;
                   6071:         }
                   6072:         $what =~ s/\&$//;  
                   6073:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   6074:     } else {
                   6075:         return $outcome;
                   6076:     }
1.353     www      6077: }
                   6078: 
                   6079: sub courseiddump {
1.921     raeburn  6080:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  6081:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  6082:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  6083:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  6084:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  6085:     my $as_hash = 1;
                   6086:     my %returnhash;
                   6087:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 6088:     my %libserv = &all_library();
                   6089:     foreach my $tryserver (keys(%libserv)) {
                   6090:         if ( (  $hostidflag == 1 
                   6091: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   6092: 	     || (!defined($hostidflag)) ) {
                   6093: 
1.918     raeburn  6094: 	    if (($domfilter eq '') ||
                   6095: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 6096:                 my $rep;
                   6097:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   6098:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   6099:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   6100:                                 &escape($descfilter), &escape($instcodefilter), 
                   6101:                                 &escape($ownerfilter), &escape($coursefilter),
                   6102:                                 &escape($typefilter), &escape($regexp_ok), 
                   6103:                                 $as_hash, &escape($selfenrollonly), 
                   6104:                                 &escape($catfilter), $showhidden, $caller, 
                   6105:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   6106:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  6107:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   6108:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 6109:                 } else {
                   6110:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   6111:                              $sincefilter.':'.&escape($descfilter).':'.
                   6112:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   6113:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   6114:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   6115:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   6116:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   6117:                              &escape($cc_clone).':'.$cloneonly.':'.
                   6118:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  6119:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   6120:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 6121:                 }
                   6122:                      
1.918     raeburn  6123:                 my @pairs=split(/\&/,$rep);
                   6124:                 foreach my $item (@pairs) {
                   6125:                     my ($key,$value)=split(/\=/,$item,2);
                   6126:                     $key = &unescape($key);
                   6127:                     next if ($key =~ /^error: 2 /);
                   6128:                     my $result = &thaw_unescape($value);
                   6129:                     if (ref($result) eq 'HASH') {
                   6130:                         $returnhash{$key}=$result;
                   6131:                     } else {
1.921     raeburn  6132:                         my @responses = split(/:/,$value);
                   6133:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  6134:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  6135:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  6136:                         }
1.1008    raeburn  6137:                     }
1.353     www      6138:                 }
                   6139:             }
                   6140:         }
                   6141:     }
                   6142:     return %returnhash;
                   6143: }
                   6144: 
1.1055    raeburn  6145: sub courselastaccess {
                   6146:     my ($cdom,$cnum,$hostidref) = @_;
                   6147:     my %returnhash;
                   6148:     if ($cdom && $cnum) {
                   6149:         my $chome = &homeserver($cnum,$cdom);
                   6150:         if ($chome ne 'no_host') {
                   6151:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   6152:             &extract_lastaccess(\%returnhash,$rep);
                   6153:         }
                   6154:     } else {
                   6155:         if (!$cdom) { $cdom=''; }
                   6156:         my %libserv = &all_library();
                   6157:         foreach my $tryserver (keys(%libserv)) {
                   6158:             if (ref($hostidref) eq 'ARRAY') {
                   6159:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   6160:             } 
                   6161:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   6162:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   6163:                 &extract_lastaccess(\%returnhash,$rep);
                   6164:             }
                   6165:         }
                   6166:     }
                   6167:     return %returnhash;
                   6168: }
                   6169: 
                   6170: sub extract_lastaccess {
                   6171:     my ($returnhash,$rep) = @_;
                   6172:     if (ref($returnhash) eq 'HASH') {
1.1531    raeburn  6173:         unless ($rep eq 'unknown_cmd' || $rep eq 'no_such_host' || 
1.1055    raeburn  6174:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   6175:                  $rep eq '') {
                   6176:             my @pairs=split(/\&/,$rep);
                   6177:             foreach my $item (@pairs) {
                   6178:                 my ($key,$value)=split(/\=/,$item,2);
                   6179:                 $key = &unescape($key);
                   6180:                 next if ($key =~ /^error: 2 /);
                   6181:                 $returnhash->{$key} = &thaw_unescape($value);
                   6182:             }
                   6183:         }
                   6184:     }
                   6185:     return;
                   6186: }
                   6187: 
1.658     raeburn  6188: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  6189: 
                   6190: sub dcmailput {
1.685     raeburn  6191:     my ($domain,$msgid,$message,$server)=@_;
1.1494    raeburn  6192:     my $status = &critical(
1.740     www      6193:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   6194:        &escape($message),$server);
1.662     raeburn  6195:     return $status;
                   6196: }
                   6197: 
1.658     raeburn  6198: sub dcmaildump {
                   6199:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  6200:     my %returnhash=();
1.846     albertel 6201: 
                   6202:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  6203:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   6204:                                                          &escape($enddate).':';
                   6205: 	my @esc_senders=map { &escape($_)} @$senders;
                   6206: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 6207: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 6208:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  6209:             if (($key) && ($value)) {
                   6210:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  6211:             }
                   6212:         }
                   6213:     }
                   6214:     return %returnhash;
                   6215: }
1.662     raeburn  6216: # ---------------------------------------------------------- Domain roles
                   6217: 
                   6218: sub get_domain_roles {
                   6219:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  6220:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  6221:         $startdate = '.';
                   6222:     }
1.1018    raeburn  6223:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  6224:         $enddate = '.';
                   6225:     }
1.922     raeburn  6226:     my $rolelist;
                   6227:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  6228:         $rolelist = join('&',@{$roles});
1.922     raeburn  6229:     }
1.662     raeburn  6230:     my %personnel = ();
1.841     albertel 6231: 
                   6232:     my %servers = &get_servers($dom,'library');
                   6233:     foreach my $tryserver (keys(%servers)) {
                   6234: 	%{$personnel{$tryserver}}=();
                   6235: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   6236: 					    &escape($startdate).':'.
                   6237: 					    &escape($enddate).':'.
                   6238: 					    &escape($rolelist), $tryserver))) {
                   6239: 	    my ($key,$value) = split(/\=/,$line,2);
                   6240: 	    if (($key) && ($value)) {
                   6241: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   6242: 	    }
                   6243: 	}
1.662     raeburn  6244:     }
                   6245:     return %personnel;
                   6246: }
1.658     raeburn  6247: 
1.1332    raeburn  6248: sub get_active_domroles {
                   6249:     my ($dom,$roles) = @_;
                   6250:     return () unless (ref($roles) eq 'ARRAY');
                   6251:     my $now = time;
                   6252:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   6253:     my %domroles;
                   6254:     foreach my $server (keys(%dompersonnel)) {
                   6255:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   6256:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   6257:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   6258:         }
                   6259:     }
                   6260:     return %domroles;
                   6261: }
                   6262: 
1.1057    www      6263: # ----------------------------------------------------------- Interval timing 
1.149     www      6264: 
1.1153    www      6265: {
                   6266: # Caches needed for speedup of navmaps
                   6267: # We don't want to cache this for very long at all (5 seconds at most)
                   6268: # 
                   6269: # The user for whom we cache
                   6270: my $cachedkey='';
                   6271: # The cached times for this user
                   6272: my %cachedtimes=();
                   6273: # When this was last done
1.1282    raeburn  6274: my $cachedtime='';
1.1153    www      6275: 
                   6276: sub load_all_first_access {
1.1308    raeburn  6277:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      6278:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  6279:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   6280:         (!$ignorecache)) {
1.1154    raeburn  6281:         return;
                   6282:     }
                   6283:     $cachedtime=time;
                   6284:     $cachedkey=$uname.':'.$udom;
                   6285:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      6286: }
                   6287: 
1.504     albertel 6288: sub get_first_access {
1.1308    raeburn  6289:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 6290:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 6291:     if ($argsymb) { $symb=$argsymb; }
                   6292:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  6293:     if ($argmap) { $map = $argmap; }
1.926     albertel 6294:     if ($type eq 'course') {
                   6295: 	$res='course';
                   6296:     } elsif ($type eq 'map') {
1.588     albertel 6297: 	$res=&symbread($map);
                   6298:     } else {
                   6299: 	$res=$symb;
                   6300:     }
1.1308    raeburn  6301:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      6302:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 6303: }
                   6304: 
                   6305: sub set_first_access {
1.1162    raeburn  6306:     my ($type,$interval)=@_;
1.790     albertel 6307:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 6308:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 6309:     if ($type eq 'course') {
                   6310: 	$res='course';
                   6311:     } elsif ($type eq 'map') {
1.588     albertel 6312: 	$res=&symbread($map);
                   6313:     } else {
                   6314: 	$res=$symb;
                   6315:     }
1.1153    www      6316:     $cachedkey='';
1.1162    raeburn  6317:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  6318:     if ($firstaccess) {
                   6319:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  6320:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   6321:                  "in $courseid");
1.1386    raeburn  6322:         return 'already_set';
                   6323:     } else {
1.1162    raeburn  6324:         my $start = time;
                   6325: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   6326:                           $udom,$uname);
                   6327:         if ($putres eq 'ok') {
                   6328:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   6329:                  $udom,$uname); 
                   6330:             &appenv(
                   6331:                      {
                   6332:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   6333:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   6334:                      }
                   6335:                   );
1.1365    raeburn  6336:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   6337:                 $cachedtimes{"$courseid\0$res"} = $start;
                   6338:             }
1.1386    raeburn  6339:         } elsif ($putres ne 'refused') {
                   6340:             &logthis("Result: $putres when attempting to set first access time ".
                   6341:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  6342:         }
                   6343:         return $putres;
1.505     albertel 6344:     }
                   6345:     return 'already_set';
1.504     albertel 6346: }
1.1153    www      6347: }
1.1282    raeburn  6348: 
1.110     www      6349: # --------------------------------------------- Set Expire Date for Spreadsheet
                   6350: 
                   6351: sub expirespread {
                   6352:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 6353:     my $cid=$env{'request.course.id'}; 
1.110     www      6354:     if ($cid) {
                   6355:        my $now=time;
                   6356:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6357:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6358:                             $env{'course.'.$cid.'.num'}.
1.110     www      6359: 	        	    ':nohist_expirationdates:'.
                   6360:                             &escape($key).'='.$now,
1.620     albertel 6361:                             $env{'course.'.$cid.'.home'})
1.110     www      6362:     }
                   6363:     return 'ok';
1.14      www      6364: }
                   6365: 
1.109     www      6366: # ----------------------------------------------------- Devalidate Spreadsheets
                   6367: 
                   6368: sub devalidate {
1.325     www      6369:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6370:     my $cid=$env{'request.course.id'}; 
1.109     www      6371:     if ($cid) {
1.391     matthew  6372:         # delete the stored spreadsheets for
                   6373:         # - the student level sheet of this user in course's homespace
                   6374:         # - the assessment level sheet for this resource 
                   6375:         #   for this user in user's homespace
1.553     albertel 6376: 	# - current conditional state info
1.325     www      6377: 	my $key=$uname.':'.$udom.':';
1.109     www      6378:         my $status=
1.299     matthew  6379: 	    &del('nohist_calculatedsheets',
1.391     matthew  6380: 		 [$key.'studentcalc:'],
1.620     albertel 6381: 		 $env{'course.'.$cid.'.domain'},
                   6382: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6383: 		.' '.
                   6384: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6385: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6386:         unless ($status eq 'ok ok') {
                   6387:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6388:                     $uname.' at '.$udom.' for '.
1.109     www      6389: 		    $symb.': '.$status);
1.133     albertel 6390:         }
1.553     albertel 6391: 	&delenv('user.state.'.$cid);
1.109     www      6392:     }
                   6393: }
                   6394: 
1.265     albertel 6395: sub get_scalar {
                   6396:     my ($string,$end) = @_;
                   6397:     my $value;
                   6398:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6399: 	$value = $1;
                   6400:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6401: 	$value = $1;
                   6402:     }
                   6403:     return &unescape($value);
                   6404: }
                   6405: 
                   6406: sub array2str {
                   6407:   my (@array) = @_;
                   6408:   my $result=&arrayref2str(\@array);
                   6409:   $result=~s/^__ARRAY_REF__//;
                   6410:   $result=~s/__END_ARRAY_REF__$//;
                   6411:   return $result;
                   6412: }
                   6413: 
1.204     albertel 6414: sub arrayref2str {
                   6415:   my ($arrayref) = @_;
1.265     albertel 6416:   my $result='__ARRAY_REF__';
1.204     albertel 6417:   foreach my $elem (@$arrayref) {
1.265     albertel 6418:     if(ref($elem) eq 'ARRAY') {
                   6419:       $result.=&arrayref2str($elem).'&';
                   6420:     } elsif(ref($elem) eq 'HASH') {
                   6421:       $result.=&hashref2str($elem).'&';
                   6422:     } elsif(ref($elem)) {
                   6423:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6424:     } else {
                   6425:       $result.=&escape($elem).'&';
                   6426:     }
                   6427:   }
                   6428:   $result=~s/\&$//;
1.265     albertel 6429:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6430:   return $result;
                   6431: }
                   6432: 
1.168     albertel 6433: sub hash2str {
1.204     albertel 6434:   my (%hash) = @_;
                   6435:   my $result=&hashref2str(\%hash);
1.265     albertel 6436:   $result=~s/^__HASH_REF__//;
                   6437:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6438:   return $result;
                   6439: }
                   6440: 
                   6441: sub hashref2str {
                   6442:   my ($hashref)=@_;
1.265     albertel 6443:   my $result='__HASH_REF__';
1.800     albertel 6444:   foreach my $key (sort(keys(%$hashref))) {
                   6445:     if (ref($key) eq 'ARRAY') {
                   6446:       $result.=&arrayref2str($key).'=';
                   6447:     } elsif (ref($key) eq 'HASH') {
                   6448:       $result.=&hashref2str($key).'=';
                   6449:     } elsif (ref($key)) {
1.265     albertel 6450:       $result.='=';
1.800     albertel 6451:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6452:     } else {
1.1132    raeburn  6453: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6454:     }
                   6455: 
1.800     albertel 6456:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6457:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6458:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6459:       $result.=&hashref2str($hashref->{$key}).'&';
                   6460:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6461:        $result.='&';
1.800     albertel 6462:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6463:     } else {
1.800     albertel 6464:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6465:     }
                   6466:   }
1.168     albertel 6467:   $result=~s/\&$//;
1.265     albertel 6468:   $result .= '__END_HASH_REF__';
1.168     albertel 6469:   return $result;
                   6470: }
                   6471: 
                   6472: sub str2hash {
1.265     albertel 6473:     my ($string)=@_;
                   6474:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6475:     return %$hash;
                   6476: }
                   6477: 
                   6478: sub str2hashref {
1.168     albertel 6479:   my ($string) = @_;
1.265     albertel 6480: 
                   6481:   my %hash;
                   6482: 
                   6483:   if($string !~ /^__HASH_REF__/) {
                   6484:       if (! ($string eq '' || !defined($string))) {
                   6485: 	  $hash{'error'}='Not hash reference';
                   6486:       }
                   6487:       return (\%hash, $string);
                   6488:   }
                   6489: 
                   6490:   $string =~ s/^__HASH_REF__//;
                   6491: 
                   6492:   while($string !~ /^__END_HASH_REF__/) {
                   6493:       #key
                   6494:       my $key='';
                   6495:       if($string =~ /^__HASH_REF__/) {
                   6496:           ($key, $string)=&str2hashref($string);
                   6497:           if(defined($key->{'error'})) {
                   6498:               $hash{'error'}='Bad data';
                   6499:               return (\%hash, $string);
                   6500:           }
                   6501:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6502:           ($key, $string)=&str2arrayref($string);
                   6503:           if($key->[0] eq 'Array reference error') {
                   6504:               $hash{'error'}='Bad data';
                   6505:               return (\%hash, $string);
                   6506:           }
                   6507:       } else {
                   6508:           $string =~ s/^(.*?)=//;
1.267     albertel 6509: 	  $key=&unescape($1);
1.265     albertel 6510:       }
                   6511:       $string =~ s/^=//;
                   6512: 
                   6513:       #value
                   6514:       my $value='';
                   6515:       if($string =~ /^__HASH_REF__/) {
                   6516:           ($value, $string)=&str2hashref($string);
                   6517:           if(defined($value->{'error'})) {
                   6518:               $hash{'error'}='Bad data';
                   6519:               return (\%hash, $string);
                   6520:           }
                   6521:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6522:           ($value, $string)=&str2arrayref($string);
                   6523:           if($value->[0] eq 'Array reference error') {
                   6524:               $hash{'error'}='Bad data';
                   6525:               return (\%hash, $string);
                   6526:           }
                   6527:       } else {
                   6528: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6529:       }
                   6530:       $string =~ s/^&//;
                   6531: 
                   6532:       $hash{$key}=$value;
1.204     albertel 6533:   }
1.265     albertel 6534: 
                   6535:   $string =~ s/^__END_HASH_REF__//;
                   6536: 
                   6537:   return (\%hash, $string);
1.204     albertel 6538: }
                   6539: 
                   6540: sub str2array {
1.265     albertel 6541:     my ($string)=@_;
                   6542:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6543:     return @$array;
                   6544: }
                   6545: 
                   6546: sub str2arrayref {
1.204     albertel 6547:   my ($string) = @_;
1.265     albertel 6548:   my @array;
                   6549: 
                   6550:   if($string !~ /^__ARRAY_REF__/) {
                   6551:       if (! ($string eq '' || !defined($string))) {
                   6552: 	  $array[0]='Array reference error';
                   6553:       }
                   6554:       return (\@array, $string);
                   6555:   }
                   6556: 
                   6557:   $string =~ s/^__ARRAY_REF__//;
                   6558: 
                   6559:   while($string !~ /^__END_ARRAY_REF__/) {
                   6560:       my $value='';
                   6561:       if($string =~ /^__HASH_REF__/) {
                   6562:           ($value, $string)=&str2hashref($string);
                   6563:           if(defined($value->{'error'})) {
                   6564:               $array[0] ='Array reference error';
                   6565:               return (\@array, $string);
                   6566:           }
                   6567:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6568:           ($value, $string)=&str2arrayref($string);
                   6569:           if($value->[0] eq 'Array reference error') {
                   6570:               $array[0] ='Array reference error';
                   6571:               return (\@array, $string);
                   6572:           }
                   6573:       } else {
                   6574: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6575:       }
                   6576:       $string =~ s/^&//;
                   6577: 
                   6578:       push(@array, $value);
1.191     harris41 6579:   }
1.265     albertel 6580: 
                   6581:   $string =~ s/^__END_ARRAY_REF__//;
                   6582: 
                   6583:   return (\@array, $string);
1.168     albertel 6584: }
                   6585: 
1.167     albertel 6586: # -------------------------------------------------------------------Temp Store
                   6587: 
1.168     albertel 6588: sub tmpreset {
                   6589:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6590:   if (!$symb) {
                   6591:     $symb=&symbread();
1.620     albertel 6592:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6593:   }
                   6594:   $symb=escape($symb);
                   6595: 
1.620     albertel 6596:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6597:   $namespace=~s/\//\_/g;
                   6598:   $namespace=~s/\W//g;
                   6599: 
1.620     albertel 6600:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6601:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6602:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6603:       $stuname=&get_requestor_ip();
1.591     albertel 6604:   }
1.1117    foxr     6605:   my $path=LONCAPA::tempdir();
1.168     albertel 6606:   my %hash;
                   6607:   if (tie(%hash,'GDBM_File',
                   6608: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6609: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6610:     foreach my $key (keys(%hash)) {
1.180     albertel 6611:       if ($key=~ /:$symb/) {
1.168     albertel 6612: 	delete($hash{$key});
                   6613:       }
                   6614:     }
                   6615:   }
                   6616: }
                   6617: 
1.167     albertel 6618: sub tmpstore {
1.168     albertel 6619:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6620: 
                   6621:   if (!$symb) {
                   6622:     $symb=&symbread();
1.620     albertel 6623:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6624:   }
                   6625:   $symb=escape($symb);
                   6626: 
                   6627:   if (!$namespace) {
                   6628:     # I don't think we would ever want to store this for a course.
                   6629:     # it seems this will only be used if we don't have a course.
1.620     albertel 6630:     #$namespace=$env{'request.course.id'};
1.168     albertel 6631:     #if (!$namespace) {
1.620     albertel 6632:       $namespace=$env{'request.state'};
1.168     albertel 6633:     #}
                   6634:   }
                   6635:   $namespace=~s/\//\_/g;
                   6636:   $namespace=~s/\W//g;
1.620     albertel 6637:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6638:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6639:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6640:       $stuname=&get_requestor_ip();
1.591     albertel 6641:   }
1.168     albertel 6642:   my $now=time;
                   6643:   my %hash;
1.1117    foxr     6644:   my $path=LONCAPA::tempdir();
1.168     albertel 6645:   if (tie(%hash,'GDBM_File',
                   6646: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6647: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6648:     $hash{"version:$symb"}++;
                   6649:     my $version=$hash{"version:$symb"};
                   6650:     my $allkeys=''; 
                   6651:     foreach my $key (keys(%$storehash)) {
                   6652:       $allkeys.=$key.':';
1.591     albertel 6653:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6654:     }
                   6655:     $hash{"$version:$symb:timestamp"}=$now;
                   6656:     $allkeys.='timestamp';
                   6657:     $hash{"$version:keys:$symb"}=$allkeys;
                   6658:     if (untie(%hash)) {
                   6659:       return 'ok';
                   6660:     } else {
                   6661:       return "error:$!";
                   6662:     }
                   6663:   } else {
                   6664:     return "error:$!";
                   6665:   }
                   6666: }
1.167     albertel 6667: 
1.168     albertel 6668: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6669: 
1.168     albertel 6670: sub tmprestore {
                   6671:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6672: 
1.168     albertel 6673:   if (!$symb) {
                   6674:     $symb=&symbread();
1.620     albertel 6675:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6676:   }
                   6677:   $symb=escape($symb);
                   6678: 
1.620     albertel 6679:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6680: 
1.620     albertel 6681:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6682:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6683:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6684:       $stuname=&get_requestor_ip();
1.591     albertel 6685:   }
1.168     albertel 6686:   my %returnhash;
                   6687:   $namespace=~s/\//\_/g;
                   6688:   $namespace=~s/\W//g;
                   6689:   my %hash;
1.1117    foxr     6690:   my $path=LONCAPA::tempdir();
1.168     albertel 6691:   if (tie(%hash,'GDBM_File',
                   6692: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6693: 	  &GDBM_READER(),0640)) {
1.168     albertel 6694:     my $version=$hash{"version:$symb"};
                   6695:     $returnhash{'version'}=$version;
                   6696:     my $scope;
                   6697:     for ($scope=1;$scope<=$version;$scope++) {
                   6698:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6699:       my @keys=split(/:/,$vkeys);
                   6700:       my $key;
                   6701:       $returnhash{"$scope:keys"}=$vkeys;
                   6702:       foreach $key (@keys) {
1.591     albertel 6703: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6704: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6705:       }
                   6706:     }
1.168     albertel 6707:     if (!(untie(%hash))) {
                   6708:       return "error:$!";
                   6709:     }
                   6710:   } else {
                   6711:     return "error:$!";
                   6712:   }
                   6713:   return %returnhash;
1.167     albertel 6714: }
                   6715: 
1.9       www      6716: # ----------------------------------------------------------------------- Store
                   6717: 
                   6718: sub store {
1.1269    raeburn  6719:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6720:     my $home='';
                   6721: 
1.168     albertel 6722:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6723: 
1.213     www      6724:     $symb=&symbclean($symb);
1.122     albertel 6725:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6726: 
1.620     albertel 6727:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6728:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6729: 
                   6730:     &devalidate($symb,$stuname,$domain);
1.109     www      6731: 
                   6732:     $symb=escape($symb);
1.187     www      6733:     if (!$namespace) { 
1.620     albertel 6734:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6735:           return ''; 
                   6736:        } 
                   6737:     }
1.620     albertel 6738:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6739: 
1.1434    raeburn  6740:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6741:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6742: 
1.12      www      6743:     my $namevalue='';
1.800     albertel 6744:     foreach my $key (keys(%$storehash)) {
                   6745:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6746:     }
1.12      www      6747:     $namevalue=~s/\&$//;
1.187     www      6748:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6749:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6750: }
                   6751: 
1.47      www      6752: # -------------------------------------------------------------- Critical Store
                   6753: 
                   6754: sub cstore {
1.1533    raeburn  6755:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6756:     my $home='';
                   6757: 
1.168     albertel 6758:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6759: 
1.1530    raeburn  6760:     unless (($symb eq '_feedback') || ($symb eq '_discussion')) {
                   6761:         $symb=&symbclean($symb);
                   6762:     }
1.122     albertel 6763:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6764: 
1.620     albertel 6765:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6766:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6767: 
1.1530    raeburn  6768:     unless (($symb eq '_feedback') || ($symb eq '_discussion')) {
                   6769:         &devalidate($symb,$stuname,$domain);
                   6770:     }
1.109     www      6771: 
                   6772:     $symb=escape($symb);
1.187     www      6773:     if (!$namespace) { 
1.620     albertel 6774:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6775:           return ''; 
                   6776:        } 
                   6777:     }
1.620     albertel 6778:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6779: 
1.1533    raeburn  6780:     $$storehash{'ip'} = &get_requestor_ip();
1.447     www      6781:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6782: 
1.47      www      6783:     my $namevalue='';
1.800     albertel 6784:     foreach my $key (keys(%$storehash)) {
                   6785:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6786:     }
1.47      www      6787:     $namevalue=~s/\&$//;
1.1533    raeburn  6788:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6789:     return critical
1.1269    raeburn  6790:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6791: }
                   6792: 
1.9       www      6793: # --------------------------------------------------------------------- Restore
                   6794: 
                   6795: sub restore {
1.124     www      6796:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6797:     my $home='';
                   6798: 
1.168     albertel 6799:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6800: 
1.122     albertel 6801:     if (!$symb) {
1.1224    raeburn  6802:         return if ($namespace eq 'courserequests');
                   6803:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6804:     } else {
1.1224    raeburn  6805:         unless ($namespace eq 'courserequests') {
                   6806:             $symb=&escape(&symbclean($symb));
                   6807:         }
1.122     albertel 6808:     }
1.188     www      6809:     if (!$namespace) { 
1.620     albertel 6810:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6811:           return ''; 
                   6812:        } 
                   6813:     }
1.620     albertel 6814:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6815:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6816:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6817:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6818: 
1.12      www      6819:     my %returnhash=();
1.800     albertel 6820:     foreach my $line (split(/\&/,$answer)) {
                   6821: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6822:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6823:     }
1.75      www      6824:     my $version;
                   6825:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6826:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6827:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6828:        }
1.75      www      6829:     }
1.13      www      6830:     return %returnhash;
1.34      www      6831: }
                   6832: 
                   6833: # ---------------------------------------------------------- Course Description
1.1118    foxr     6834: #
                   6835: #  
1.34      www      6836: 
                   6837: sub coursedescription {
1.731     albertel 6838:     my ($courseid,$args)=@_;
1.34      www      6839:     $courseid=~s/^\///;
1.49      www      6840:     $courseid=~s/\_/\//g;
1.34      www      6841:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6842:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6843:     my $normalid=$cdomain.'_'.$cnum;
                   6844:     # need to always cache even if we get errors otherwise we keep 
                   6845:     # trying and trying and trying to get the course description.
                   6846:     my %envhash=();
                   6847:     my %returnhash=();
1.731     albertel 6848:     
                   6849:     my $expiretime=600;
                   6850:     if ($env{'request.course.id'} eq $normalid) {
                   6851: 	$expiretime=120;
                   6852:     }
                   6853: 
                   6854:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6855:     if (!$args->{'freshen_cache'}
                   6856: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6857: 	foreach my $key (keys(%env)) {
                   6858: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6859: 	    my ($setting) = $1;
                   6860: 	    $returnhash{$setting} = $env{$key};
                   6861: 	}
                   6862: 	return %returnhash;
                   6863:     }
                   6864: 
1.1118    foxr     6865:     # get the data again
                   6866: 
1.731     albertel 6867:     if (!$args->{'one_time'}) {
                   6868: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6869:     }
1.811     albertel 6870: 
1.34      www      6871:     if ($chome ne 'no_host') {
1.302     albertel 6872:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6873:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6874: 	   my $username = $env{'user.name'}; # Defult username
                   6875: 	   if(defined $args->{'user'}) {
                   6876: 	       $username = $args->{'user'};
                   6877: 	   }
1.129     albertel 6878:            $returnhash{'home'}= $chome;
                   6879: 	   $returnhash{'domain'} = $cdomain;
                   6880: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6881:            if (!defined($returnhash{'type'})) {
                   6882:                $returnhash{'type'} = 'Course';
                   6883:            }
1.130     albertel 6884:            while (my ($name,$value) = each %returnhash) {
1.53      www      6885:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6886:            }
1.270     www      6887:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6888:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6889: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6890:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6891:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6892:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6893:        }
                   6894:     }
1.731     albertel 6895:     if (!$args->{'one_time'}) {
1.949     raeburn  6896: 	&appenv(\%envhash);
1.731     albertel 6897:     }
1.302     albertel 6898:     return %returnhash;
1.461     www      6899: }
                   6900: 
1.1080    raeburn  6901: sub update_released_required {
                   6902:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6903:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6904:         $cid = $env{'request.course.id'};
                   6905:         $cdom = $env{'course.'.$cid.'.domain'};
                   6906:         $cnum = $env{'course.'.$cid.'.num'};
                   6907:         $chome = $env{'course.'.$cid.'.home'};
                   6908:     }
                   6909:     if ($needsrelease) {
                   6910:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6911:         my $needsupdate;
                   6912:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6913:             $needsupdate = 1;
                   6914:         } else {
                   6915:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6916:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6917:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6918:                 $needsupdate = 1;
                   6919:             }
                   6920:         }
                   6921:         if ($needsupdate) {
                   6922:             my %needshash = (
                   6923:                              'internal.releaserequired' => $needsrelease,
                   6924:                             );
                   6925:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6926:             if ($putresult eq 'ok') {
                   6927:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6928:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6929:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6930:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6931:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6932:                 }
                   6933:             }
                   6934:         }
                   6935:     }
                   6936:     return;
                   6937: }
                   6938: 
1.461     www      6939: # -------------------------------------------------See if a user is privileged
                   6940: 
                   6941: sub privileged {
1.1219    raeburn  6942:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6943:     my $now = time;
1.1219    raeburn  6944:     my $roles;
                   6945:     if (ref($possroles) eq 'ARRAY') {
                   6946:         $roles = $possroles; 
                   6947:     } else {
                   6948:         $roles = ['dc','su'];
                   6949:     }
                   6950:     if (ref($possdomains) eq 'ARRAY') {
                   6951:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6952:         foreach my $dom (@{$possdomains}) {
                   6953:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6954:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6955:                 foreach my $role (@{$roles}) {
                   6956:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6957:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6958:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6959:                             return 1 unless (($end && $end < $now) ||
                   6960:                                              ($start && $start > $now));
                   6961:                         }
                   6962:                     }
                   6963:                 }
                   6964:             }
                   6965:         }
                   6966:     } else {
                   6967:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6968:         my $now = time;
1.1170    droeschl 6969: 
1.1275    musolffc 6970:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6971:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6972:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6973:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6974:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6975:             }
1.1219    raeburn  6976:         }
                   6977:     }
                   6978:     return 0;
                   6979: }
1.1170    droeschl 6980: 
1.1219    raeburn  6981: sub privileged_by_domain {
                   6982:     my ($domains,$roles) = @_;
                   6983:     my %privileged = ();
                   6984:     my $cachetime = 60*60*24;
                   6985:     my $now = time;
                   6986:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6987:         return %privileged;
                   6988:     }
                   6989:     foreach my $dom (@{$domains}) {
                   6990:         next if (ref($privileged{$dom}) eq 'HASH');
                   6991:         my $needroles;
                   6992:         foreach my $role (@{$roles}) {
                   6993:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6994:             if (defined($cached)) {
                   6995:                 if (ref($result) eq 'HASH') {
                   6996:                     $privileged{$dom}{$role} = $result;
                   6997:                 }
                   6998:             } else {
                   6999:                 $needroles = 1;
                   7000:             }
                   7001:         }
                   7002:         if ($needroles) {
                   7003:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   7004:             $privileged{$dom} = {};
                   7005:             foreach my $server (keys(%dompersonnel)) {
                   7006:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   7007:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   7008:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   7009:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   7010:                         next if ($end && $end < $now);
                   7011:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   7012:                             $dompersonnel{$server}{$item};
                   7013:                     }
                   7014:                 }
                   7015:             }
                   7016:             if (ref($privileged{$dom}) eq 'HASH') {
                   7017:                 foreach my $role (@{$roles}) {
                   7018:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   7019:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   7020:                     } else {
                   7021:                         my %hash = ();
                   7022:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   7023:                     }
                   7024:                 }
                   7025:             }
                   7026:         }
                   7027:     }
                   7028:     return %privileged;
1.9       www      7029: }
1.1       albertel 7030: 
1.103     harris41 7031: # -------------------------------------------------------- Get user privileges
1.11      www      7032: 
                   7033: sub rolesinit {
1.1169    droeschl 7034:     my ($domain, $username) = @_;
                   7035:     my %userroles = ('user.login.time' => time);
                   7036:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   7037: 
                   7038:     # firstaccess and timerinterval are related to timed maps/resources. 
                   7039:     # also, blocking can be triggered by an activating timer
                   7040:     # it's saved in the user's %env.
                   7041:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   7042:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   7043:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
1.1517    raeburn  7044:         %timerintchk, %timerintenv, %coauthorenv);
1.1169    droeschl 7045: 
1.1162    raeburn  7046:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 7047:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  7048:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   7049:     }
1.1169    droeschl 7050: 
1.1162    raeburn  7051:     foreach my $key (keys(%timerinterval)) {
                   7052:         my ($cid,$rest) = split(/\0/,$key);
                   7053:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   7054:     }
1.1169    droeschl 7055: 
1.11      www      7056:     my %allroles=();
1.1162    raeburn  7057:     my %allgroups=();
1.1517    raeburn  7058:     my %gotcoauconfig=();
1.1524    raeburn  7059:     my %domdefaults=();
1.11      www      7060: 
1.1274    raeburn  7061:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 7062:         my $role = $rolesdump{$area};
                   7063:         $area =~ s/\_\w\w$//;
                   7064: 
                   7065:         my ($trole, $tend, $tstart, $group_privs);
                   7066: 
                   7067:         if ($role =~ /^cr/) {
                   7068:         # Custom role, defined by a user 
                   7069:         # e.g., user.role.cr/msu/smith/mynewrole
                   7070:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   7071:                 $trole = $1;
                   7072:                 ($tend, $tstart) = split('_', $2);
                   7073:             } else {
                   7074:                 $trole = $role;
                   7075:             }
                   7076:         } elsif ($role =~ m|^gr/|) {
                   7077:         # Role of member in a group, defined within a course/community
                   7078:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   7079:             ($trole, $tend, $tstart) = split(/_/, $role);
                   7080:             next if $tstart eq '-1';
                   7081:             ($trole, $group_privs) = split(/\//, $trole);
                   7082:             $group_privs = &unescape($group_privs);
                   7083:         } else {
                   7084:         # Just a normal role, defined in roles.tab
                   7085:             ($trole, $tend, $tstart) = split(/_/,$role);
                   7086:         }
                   7087: 
                   7088:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   7089:                  $username);
                   7090:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   7091: 
                   7092:         # role expired or not available yet?
                   7093:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   7094:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   7095: 
                   7096:         next if $area eq '' or $trole eq '';
                   7097: 
                   7098:         my $spec = "$trole.$area";
                   7099:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   7100: 
                   7101:         if ($trole =~ /^cr\//) {
                   7102:         # Custom role, defined by a user
                   7103:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7104:         } elsif ($trole eq 'gr') {
                   7105:         # Role of a member in a group, defined within a course/community
                   7106:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   7107:             next;
                   7108:         } else {
                   7109:         # Normal role, defined in roles.tab
                   7110:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.1517    raeburn  7111:             if (($trole eq 'ca') || ($trole eq 'aa')) {
                   7112:                 (undef,my ($audom,$auname)) = split(/\//,$area);
                   7113:                 unless ($gotcoauconfig{$area}) {
                   7114:                     my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
                   7115:                     my %info = &userenvironment($audom,$auname,@ca_settings);
                   7116:                     $gotcoauconfig{$area} = 1;
                   7117:                     foreach my $item (@ca_settings) {
                   7118:                         if (exists($info{$item})) {
1.1519    raeburn  7119:                             my $name = $item;
                   7120:                             if ($item eq 'authoreditors') {
                   7121:                                 $name = 'editors';
1.1524    raeburn  7122:                                 unless ($info{'authoreditors'}) {
                   7123:                                     my %domdefs;
                   7124:                                     if (ref($domdefaults{$audom}) eq 'HASH') {
                   7125:                                         %domdefs = %{$domdefaults{$audom}};
                   7126:                                     } else {
                   7127:                                         %domdefs = &get_domain_defaults($audom);
                   7128:                                         $domdefaults{$audom} = \%domdefs;
                   7129:                                     }
                   7130:                                     if ($domdefs{$name} ne '') {
                   7131:                                         $info{'authoreditors'} = $domdefs{$name};
                   7132:                                     } else {
                   7133:                                         $info{'authoreditors'} = 'edit,xml';
                   7134:                                     }
                   7135:                                 }
1.1519    raeburn  7136:                             }
                   7137:                             $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
1.1517    raeburn  7138:                         }
                   7139:                     }
                   7140:                 }
                   7141:             }
1.1169    droeschl 7142:         }
                   7143: 
                   7144:         my $cid = $tdomain.'_'.$trest;
                   7145:         unless ($firstaccchk{$cid}) {
                   7146:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   7147:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   7148:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   7149:                         $coursetimerstarts{$cid}{$item}; 
                   7150:                 }
                   7151:             }
                   7152:             $firstaccchk{$cid} = 1;
                   7153:         }
                   7154:         unless ($timerintchk{$cid}) {
                   7155:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   7156:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   7157:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   7158:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  7159:                 }
1.12      www      7160:             }
1.1169    droeschl 7161:             $timerintchk{$cid} = 1;
1.191     harris41 7162:         }
1.11      www      7163:     }
1.1169    droeschl 7164: 
1.1341    raeburn  7165:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   7166:                                                           \%allroles, \%allgroups);
1.1169    droeschl 7167:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  7168:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 7169: 
1.1517    raeburn  7170:     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
1.11      www      7171: }
                   7172: 
1.567     raeburn  7173: sub set_arearole {
1.1215    raeburn  7174:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   7175:     unless ($nolog) {
1.567     raeburn  7176: # log the associated role with the area
1.1215    raeburn  7177:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   7178:     }
1.743     albertel 7179:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  7180: }
                   7181: 
                   7182: sub custom_roleprivs {
                   7183:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   7184:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  7185:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 7186:     if (&hostname($homsvr) ne '') {
1.567     raeburn  7187:         my ($rdummy,$roledef)=
                   7188:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   7189:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   7190:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   7191:             if (defined($syspriv)) {
1.1043    raeburn  7192:                 if ($trest =~ /^$match_community$/) {
                   7193:                     $syspriv =~ s/bre\&S//; 
                   7194:                 }
1.567     raeburn  7195:                 $$allroles{'cm./'}.=':'.$syspriv;
                   7196:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   7197:             }
                   7198:             if ($tdomain ne '') {
                   7199:                 if (defined($dompriv)) {
                   7200:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   7201:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   7202:                 }
                   7203:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  7204:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   7205:                         my $rolename = $1;
                   7206:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   7207:                     }
1.567     raeburn  7208:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   7209:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   7210:                 }
                   7211:             }
                   7212:         }
                   7213:     }
                   7214: }
                   7215: 
1.1332    raeburn  7216: sub course_adhocrole_privs {
                   7217:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   7218:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   7219:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   7220:         my (%currprivs,%storeprivs);
                   7221:         foreach my $item (split(/:/,$coursepriv)) {
                   7222:             my ($priv,$restrict) = split(/\&/,$item);
                   7223:             $currprivs{$priv} = $restrict;
                   7224:         }
                   7225:         my (%possadd,%possremove,%full);
                   7226:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   7227:             my ($priv,$restrict)=split(/\&/,$item);
                   7228:             $full{$priv} = $restrict;
                   7229:         }
                   7230:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490    raeburn  7231:             next if ($item eq '');
                   7232:             my ($rule,$rest) = split(/=/,$item);
                   7233:             next unless (($rule eq 'off') || ($rule eq 'on'));
                   7234:             foreach my $priv (split(/:/,$rest)) {
                   7235:                 if ($priv ne '') {
                   7236:                     if ($rule eq 'off') {
                   7237:                         $possremove{$priv} = 1;
                   7238:                     } else {
                   7239:                         $possadd{$priv} = 1;
                   7240:                     }
                   7241:                 }
                   7242:             }
                   7243:         }
                   7244:         foreach my $priv (sort(keys(%full))) {
                   7245:             if (exists($currprivs{$priv})) {
                   7246:                 unless (exists($possremove{$priv})) {
                   7247:                     $storeprivs{$priv} = $currprivs{$priv};
                   7248:                 }
                   7249:             } elsif (exists($possadd{$priv})) {
                   7250:                 $storeprivs{$priv} = $full{$priv};
                   7251:             }
                   7252:         }
                   7253:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   7254:     }
                   7255:     return $coursepriv;
1.1332    raeburn  7256: }
                   7257: 
1.678     raeburn  7258: sub group_roleprivs {
                   7259:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   7260:     my $access = 1;
                   7261:     my $now = time;
                   7262:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   7263:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   7264:     if ($access) {
1.811     albertel 7265:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  7266:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   7267:     }
                   7268: }
1.567     raeburn  7269: 
                   7270: sub standard_roleprivs {
                   7271:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   7272:     if (defined($pr{$trole.':s'})) {
                   7273:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   7274:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   7275:     }
                   7276:     if ($tdomain ne '') {
                   7277:         if (defined($pr{$trole.':d'})) {
                   7278:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   7279:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   7280:         }
                   7281:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   7282:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   7283:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   7284:         }
                   7285:     }
                   7286: }
                   7287: 
                   7288: sub set_userprivs {
1.1064    raeburn  7289:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  7290:     my $author=0;
                   7291:     my $adv=0;
1.1341    raeburn  7292:     my $rar=0;
1.678     raeburn  7293:     my %grouproles = ();
                   7294:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  7295:         my @groupkeys; 
1.1000    raeburn  7296:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  7297:             push(@groupkeys,$role);
                   7298:         }
                   7299:         if (ref($groups_roles) eq 'HASH') {
                   7300:             foreach my $key (keys(%{$groups_roles})) {
                   7301:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   7302:                     push(@groupkeys,$key);
                   7303:                 }
                   7304:             }
                   7305:         }
                   7306:         if (@groupkeys > 0) {
                   7307:             foreach my $role (@groupkeys) {
                   7308:                 my ($trole,$area,$sec,$extendedarea);
                   7309:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   7310:                     $trole = $1;
                   7311:                     $area = $2;
                   7312:                     $sec = $3;
                   7313:                     $extendedarea = $area.$sec;
                   7314:                     if (exists($$allgroups{$area})) {
                   7315:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   7316:                             my $spec = $trole.'.'.$extendedarea;
                   7317:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  7318:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  7319:                         }
1.678     raeburn  7320:                     }
                   7321:                 }
                   7322:             }
                   7323:         }
                   7324:     }
1.800     albertel 7325:     foreach my $group (keys(%grouproles)) {
                   7326:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  7327:     }
1.800     albertel 7328:     foreach my $role (keys(%{$allroles})) {
                   7329:         my %thesepriv;
1.941     raeburn  7330:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 7331:         foreach my $item (split(/:/,$$allroles{$role})) {
                   7332:             if ($item ne '') {
                   7333:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  7334:                 if ($restrictions eq '') {
                   7335:                     $thesepriv{$privilege}='F';
                   7336:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   7337:                     $thesepriv{$privilege}.=$restrictions;
                   7338:                 }
                   7339:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  7340:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  7341:             }
                   7342:         }
                   7343:         my $thesestr='';
1.1104    raeburn  7344:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 7345: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   7346: 	}
                   7347:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  7348:     }
1.1341    raeburn  7349:     return ($author,$adv,$rar);
1.567     raeburn  7350: }
                   7351: 
1.994     raeburn  7352: sub role_status {
1.1104    raeburn  7353:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  7354:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  7355:         my ($one,$two) = split(m{\./},$rolekey,2);
                   7356:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  7357:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  7358:             $$where = '/'.$two;
1.994     raeburn  7359:             $$trolecode=$$role.'.'.$$where;
                   7360:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   7361:             $$tstatus='is';
1.1104    raeburn  7362:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  7363:                 $$tstatus='future';
1.1034    raeburn  7364:                 if ($$tstart<$now) {
                   7365:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  7366:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  7367:                             my (%allroles,%allgroups,$group_privs,
                   7368:                                 %groups_roles,@rolecodes);
1.1002    raeburn  7369:                             my %userroles = (
                   7370:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   7371:                             );
1.1064    raeburn  7372:                             @rolecodes = ('cm'); 
1.1002    raeburn  7373:                             my $spec=$$role.'.'.$$where;
                   7374:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   7375:                             if ($$role =~ /^cr\//) {
                   7376:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  7377:                                 push(@rolecodes,'cr');
1.1002    raeburn  7378:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  7379:                                 push(@rolecodes,$$role);
1.1002    raeburn  7380:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   7381:                                                     $env{'user.name'});
1.1064    raeburn  7382:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  7383:                                 (undef,my $group_privs) = split(/\//,$trole);
                   7384:                                 $group_privs = &unescape($group_privs);
                   7385:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  7386:                                 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  7387:                                 &get_groups_roles($tdomain,$trest,
                   7388:                                                   \%course_roles,\@rolecodes,
                   7389:                                                   \%groups_roles);
1.1002    raeburn  7390:                             } else {
1.1064    raeburn  7391:                                 push(@rolecodes,$$role);
1.1002    raeburn  7392:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7393:                             }
1.1341    raeburn  7394:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7395:                                                                    \%groups_roles);
1.1064    raeburn  7396:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  7397:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7398:                         }
                   7399:                     }
1.1034    raeburn  7400:                     $$tstatus = 'is';
1.1002    raeburn  7401:                 }
1.994     raeburn  7402:             }
                   7403:             if ($$tend) {
1.1104    raeburn  7404:                 if ($$tend<$update) {
1.994     raeburn  7405:                     $$tstatus='expired';
                   7406:                 } elsif ($$tend<$now) {
                   7407:                     $$tstatus='will_not';
                   7408:                 }
                   7409:             }
                   7410:         }
                   7411:     }
                   7412: }
                   7413: 
1.1104    raeburn  7414: sub get_groups_roles {
                   7415:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7416:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7417:                   (ref($rolecodes) eq 'ARRAY') && 
                   7418:                   (ref($groups_roles) eq 'HASH')); 
                   7419:     if (keys(%{$cdom_courseroles}) > 0) {
                   7420:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7421:         if ($cdom ne '' && $cnum ne '') {
                   7422:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7423:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7424:                     my $crsrole = $1;
                   7425:                     my $crssec = $2;
                   7426:                     if ($crsrole =~ /^cr/) {
                   7427:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7428:                             push(@{$rolecodes},'cr');
                   7429:                         }
                   7430:                     } else {
                   7431:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7432:                             push(@{$rolecodes},$crsrole);
                   7433:                         }
                   7434:                     }
                   7435:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7436:                     if ($crssec ne '') {
                   7437:                         $rolekey .= "/$crssec";
                   7438:                     }
                   7439:                     $rolekey .= './';
                   7440:                     $groups_roles->{$rolekey} = $rolecodes;
                   7441:                 }
                   7442:             }
                   7443:         }
                   7444:     }
                   7445:     return;
                   7446: }
                   7447: 
                   7448: sub delete_env_groupprivs {
                   7449:     my ($where,$courseroles,$possroles) = @_;
                   7450:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7451:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7452:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7453:         %{$courseroles->{$udom}} =
                   7454:             &get_my_roles('','','userroles',['active'],
                   7455:                           $possroles,[$udom],1);
                   7456:     }
                   7457:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7458:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7459:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7460:             my $area = '/'.$cdom.'/'.$cnum;
                   7461:             my $privkey = "user.priv.$crsrole.$area";
                   7462:             if ($crssec ne '') {
                   7463:                 $privkey .= '/'.$crssec;
                   7464:             }
                   7465:             $privkey .= ".$area/$group";
                   7466:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7467:         }
                   7468:     }
                   7469:     return;
                   7470: }
                   7471: 
1.994     raeburn  7472: sub check_adhoc_privs {
1.1329    raeburn  7473:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7474:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  7475:     if ($sec) {
                   7476:         $cckey .= '/'.$sec;
                   7477:     } 
1.1185    raeburn  7478:     my $setprivs;
1.994     raeburn  7479:     if ($env{$cckey}) {
                   7480:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7481:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7482:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  7483:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7484:             $setprivs = 1;
1.994     raeburn  7485:         }
                   7486:     } else {
1.1330    raeburn  7487:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7488:         $setprivs = 1;
1.994     raeburn  7489:     }
1.1185    raeburn  7490:     return $setprivs;
1.994     raeburn  7491: }
                   7492: 
                   7493: sub set_adhoc_privileges {
1.1326    raeburn  7494: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  7495:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7496:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  7497:     if ($sec ne '') {
                   7498:         $area .= '/'.$sec;
                   7499:     }
1.994     raeburn  7500:     my $spec = $role.'.'.$area;
                   7501:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  7502:                                   $env{'user.name'},1);
1.1326    raeburn  7503:     my %rolehash = ();
1.1332    raeburn  7504:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7505:         my $rolename = $1;
1.1326    raeburn  7506:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  7507:         my %domdef = &get_domain_defaults($dcdom);
                   7508:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7509:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7510:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7511:             }
                   7512:         }
1.1326    raeburn  7513:     } else {
                   7514:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7515:     }
1.1341    raeburn  7516:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7517:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  7518:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  7519:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7520:             ($caller eq 'tiny')) {
1.1088    raeburn  7521:         &appenv( {'request.role'        => $spec,
                   7522:                   'request.role.domain' => $dcdom,
1.1332    raeburn  7523:                   'request.course.sec'  => $sec,
1.1088    raeburn  7524:                  }
                   7525:                );
                   7526:         my $tadv=0;
                   7527:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7528:         &appenv({'request.role.adv'    => $tadv});
                   7529:     }
1.994     raeburn  7530: }
                   7531: 
1.12      www      7532: # --------------------------------------------------------------- get interface
                   7533: 
                   7534: sub get {
1.131     albertel 7535:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7536:    my $items='';
1.800     albertel 7537:    foreach my $item (@$storearr) {
                   7538:        $items.=&escape($item).'&';
1.191     harris41 7539:    }
1.12      www      7540:    $items=~s/\&$//;
1.620     albertel 7541:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7542:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7543:    my $uhome=&homeserver($uname,$udomain);
                   7544: 
1.133     albertel 7545:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7546:    my @pairs=split(/\&/,$rep);
1.273     albertel 7547:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7548:      return @pairs;
                   7549:    }
1.15      www      7550:    my %returnhash=();
1.42      www      7551:    my $i=0;
1.800     albertel 7552:    foreach my $item (@$storearr) {
                   7553:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7554:       $i++;
1.191     harris41 7555:    }
1.15      www      7556:    return %returnhash;
1.27      www      7557: }
                   7558: 
                   7559: # --------------------------------------------------------------- del interface
                   7560: 
                   7561: sub del {
1.133     albertel 7562:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7563:    my $items='';
1.800     albertel 7564:    foreach my $item (@$storearr) {
                   7565:        $items.=&escape($item).'&';
1.191     harris41 7566:    }
1.984     neumanie 7567: 
1.27      www      7568:    $items=~s/\&$//;
1.620     albertel 7569:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7570:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7571:    my $uhome=&homeserver($uname,$udomain);
                   7572:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7573: }
                   7574: 
                   7575: # -------------------------------------------------------------- dump interface
                   7576: 
1.1180    droeschl 7577: sub unserialize {
                   7578:     my ($rep, $escapedkeys) = @_;
                   7579: 
                   7580:     return {} if $rep =~ /^error/;
                   7581: 
                   7582:     my %returnhash=();
1.1252    raeburn  7583: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7584: 	    my ($key, $value) = split(/=/, $item, 2);
                   7585: 	    $key = unescape($key) unless $escapedkeys;
                   7586: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7587: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7588: 	}
                   7589:     #return %returnhash;
                   7590:     return \%returnhash;
                   7591: }        
                   7592: 
                   7593: # see Lond::dump_with_regexp
                   7594: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7595: sub dump {
1.1462    raeburn  7596:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7597:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7598:     if (!$uname) { $uname=$env{'user.name'}; }
                   7599:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7600: 
1.1266    raeburn  7601:     if ($regexp) {
                   7602:         $regexp=&escape($regexp);
                   7603:     } else {
                   7604:         $regexp='.';
                   7605:     }
1.1180    droeschl 7606:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7607:         # user is hosted on this machine
1.1266    raeburn  7608:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7609:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7610:         return %{unserialize($reply, $escapedkeys)};
                   7611:     }
1.1462    raeburn  7612:     my $rep;
                   7613:     if ($encrypt) {
                   7614:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463    raeburn  7615:     } else {
1.1462    raeburn  7616:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7617:     }
1.755     albertel 7618:     my @pairs=split(/\&/,$rep);
                   7619:     my %returnhash=();
1.1098    foxr     7620:     if (!($rep =~ /^error/ )) {
                   7621: 	foreach my $item (@pairs) {
                   7622: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7623:         $key = unescape($key) unless $escapedkeys;
                   7624:         #$key = &unescape($key);
1.1098    foxr     7625: 	    next if ($key =~ /^error: 2 /);
                   7626: 	    $returnhash{$key}=&thaw_unescape($value);
                   7627: 	}
1.755     albertel 7628:     }
                   7629:     return %returnhash;
1.407     www      7630: }
                   7631: 
1.1098    foxr     7632: 
1.717     albertel 7633: # --------------------------------------------------------- dumpstore interface
                   7634: 
                   7635: sub dumpstore {
                   7636:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7637:    # same as dump but keys must be escaped. They may contain colon separated
                   7638:    # lists of values that may themself contain colons (e.g. symbs).
                   7639:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7640: }
                   7641: 
1.407     www      7642: # -------------------------------------------------------------- keys interface
                   7643: 
                   7644: sub getkeys {
                   7645:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7646:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7647:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7648:    my $uhome=&homeserver($uname,$udomain);
                   7649:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7650:    my @keyarray=();
1.800     albertel 7651:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7652:       next if ($key =~ /^error: 2 /);
1.800     albertel 7653:       push(@keyarray,&unescape($key));
1.407     www      7654:    }
                   7655:    return @keyarray;
1.318     matthew  7656: }
                   7657: 
1.319     matthew  7658: # --------------------------------------------------------------- currentdump
                   7659: sub currentdump {
1.328     matthew  7660:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7661:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7662:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7663:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7664:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7665:    my $rep;
                   7666: 
                   7667:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7668:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7669:                    $courseid)));
                   7670:    } else {
                   7671:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7672:    }
                   7673: 
1.318     matthew  7674:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7675:    #
1.318     matthew  7676:    my %returnhash=();
1.319     matthew  7677:    #
1.1343    raeburn  7678:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7679:        # an old lond will not know currentdump
                   7680:        # Do a dump and make it look like a currentdump
1.822     albertel 7681:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7682:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7683:        my %hash = @tmp;
                   7684:        @tmp=();
1.424     matthew  7685:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7686:    } else {
                   7687:        my @pairs=split(/\&/,$rep);
1.800     albertel 7688:        foreach my $pair (@pairs) {
                   7689:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7690:            my ($symb,$param) = split(/:/,$key);
                   7691:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7692:                                                         &thaw_unescape($value);
1.319     matthew  7693:        }
1.191     harris41 7694:    }
1.12      www      7695:    return %returnhash;
1.424     matthew  7696: }
                   7697: 
                   7698: sub convert_dump_to_currentdump{
                   7699:     my %hash = %{shift()};
                   7700:     my %returnhash;
                   7701:     # Code ripped from lond, essentially.  The only difference
                   7702:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7703:     # we might run in to problems with parameter names =~ /^v\./
                   7704:     while (my ($key,$value) = each(%hash)) {
                   7705:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7706: 	$symb  = &unescape($symb);
                   7707: 	$param = &unescape($param);
1.424     matthew  7708:         next if ($v eq 'version' || $symb eq 'keys');
                   7709:         next if (exists($returnhash{$symb}) &&
                   7710:                  exists($returnhash{$symb}->{$param}) &&
                   7711:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7712:         $returnhash{$symb}->{$param}=$value;
                   7713:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7714:     }
                   7715:     #
                   7716:     # Remove all of the keys in the hashes which keep track of
                   7717:     # the version of the parameter.
                   7718:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7719:         # use a foreach because we are going to delete from the hash.
                   7720:         foreach my $key (keys(%$param_hash)) {
                   7721:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7722:         }
                   7723:     }
                   7724:     return \%returnhash;
1.12      www      7725: }
                   7726: 
1.627     albertel 7727: # ------------------------------------------------------ critical inc interface
                   7728: 
                   7729: sub cinc {
                   7730:     return &inc(@_,'critical');
                   7731: }
                   7732: 
1.449     matthew  7733: # --------------------------------------------------------------- inc interface
                   7734: 
                   7735: sub inc {
1.627     albertel 7736:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7737:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7738:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7739:     my $uhome=&homeserver($uname,$udomain);
                   7740:     my $items='';
                   7741:     if (! ref($store)) {
                   7742:         # got a single value, so use that instead
                   7743:         $items = &escape($store).'=&';
                   7744:     } elsif (ref($store) eq 'SCALAR') {
                   7745:         $items = &escape($$store).'=&';        
                   7746:     } elsif (ref($store) eq 'ARRAY') {
                   7747:         $items = join('=&',map {&escape($_);} @{$store});
                   7748:     } elsif (ref($store) eq 'HASH') {
                   7749:         while (my($key,$value) = each(%{$store})) {
                   7750:             $items.= &escape($key).'='.&escape($value).'&';
                   7751:         }
                   7752:     }
                   7753:     $items=~s/\&$//;
1.627     albertel 7754:     if ($critical) {
                   7755: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7756:     } else {
                   7757: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7758:     }
1.449     matthew  7759: }
                   7760: 
1.12      www      7761: # --------------------------------------------------------------- put interface
                   7762: 
                   7763: sub put {
1.1462    raeburn  7764:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7765:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7766:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7767:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7768:    my $items='';
1.800     albertel 7769:    foreach my $item (keys(%$storehash)) {
                   7770:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7771:    }
1.12      www      7772:    $items=~s/\&$//;
1.1462    raeburn  7773:    if ($encrypt) {
                   7774:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7775:    } else {
                   7776:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7777:    }
1.47      www      7778: }
                   7779: 
1.631     albertel 7780: # ------------------------------------------------------------ newput interface
                   7781: 
                   7782: sub newput {
                   7783:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7784:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7785:    if (!$uname) { $uname=$env{'user.name'}; }
                   7786:    my $uhome=&homeserver($uname,$udomain);
                   7787:    my $items='';
                   7788:    foreach my $key (keys(%$storehash)) {
                   7789:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7790:    }
                   7791:    $items=~s/\&$//;
                   7792:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7793: }
                   7794: 
                   7795: # ---------------------------------------------------------  putstore interface
                   7796: 
1.524     raeburn  7797: sub putstore {
1.1269    raeburn  7798:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7799:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7800:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7801:    my $uhome=&homeserver($uname,$udomain);
                   7802:    my $items='';
1.715     albertel 7803:    foreach my $key (keys(%$storehash)) {
                   7804:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7805:    }
1.715     albertel 7806:    $items=~s/\&$//;
1.716     albertel 7807:    my $esc_symb=&escape($symb);
                   7808:    my $esc_v=&escape($version);
1.715     albertel 7809:    my $reply =
1.716     albertel 7810:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7811: 	      $uhome);
1.1269    raeburn  7812:    if (($tolog) && ($reply eq 'ok')) {
                   7813:        my $namevalue='';
                   7814:        foreach my $key (keys(%{$storehash})) {
                   7815:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7816:        }
1.1434    raeburn  7817:        my $ip = &get_requestor_ip();
                   7818:        $namevalue .= 'ip='.&escape($ip).
1.1269    raeburn  7819:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7820:                      '&version='.$esc_v.
                   7821:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
1.1494    raeburn  7822:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
1.1269    raeburn  7823:    }
1.715     albertel 7824:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7825:        # gfall back to way things use to be done
1.715     albertel 7826:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7827: 			    $uname);
1.524     raeburn  7828:    }
1.715     albertel 7829:    return $reply;
                   7830: }
                   7831: 
                   7832: sub old_putstore {
1.716     albertel 7833:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7834:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7835:     if (!$uname) { $uname=$env{'user.name'}; }
                   7836:     my $uhome=&homeserver($uname,$udomain);
                   7837:     my %newstorehash;
1.800     albertel 7838:     foreach my $item (keys(%$storehash)) {
                   7839: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7840: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7841:     }
                   7842:     my $items='';
                   7843:     my %allitems = ();
1.800     albertel 7844:     foreach my $item (keys(%newstorehash)) {
                   7845: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7846: 	    my $key = $1.':keys:'.$2;
                   7847: 	    $allitems{$key} .= $3.':';
                   7848: 	}
1.800     albertel 7849: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7850:     }
1.800     albertel 7851:     foreach my $item (keys(%allitems)) {
                   7852: 	$allitems{$item} =~ s/\:$//;
                   7853: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7854:     }
                   7855:     $items=~s/\&$//;
                   7856:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7857: }
                   7858: 
1.47      www      7859: # ------------------------------------------------------ critical put interface
                   7860: 
                   7861: sub cput {
1.134     albertel 7862:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7863:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7864:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7865:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7866:    my $items='';
1.800     albertel 7867:    foreach my $item (keys(%$storehash)) {
                   7868:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7869:    }
1.47      www      7870:    $items=~s/\&$//;
1.134     albertel 7871:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7872: }
                   7873: 
                   7874: # -------------------------------------------------------------- eget interface
                   7875: 
                   7876: sub eget {
1.133     albertel 7877:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7878:    my $items='';
1.800     albertel 7879:    foreach my $item (@$storearr) {
                   7880:        $items.=&escape($item).'&';
1.191     harris41 7881:    }
1.12      www      7882:    $items=~s/\&$//;
1.620     albertel 7883:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7884:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7885:    my $uhome=&homeserver($uname,$udomain);
                   7886:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7887:    my @pairs=split(/\&/,$rep);
                   7888:    my %returnhash=();
1.42      www      7889:    my $i=0;
1.800     albertel 7890:    foreach my $item (@$storearr) {
                   7891:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7892:       $i++;
1.191     harris41 7893:    }
1.12      www      7894:    return %returnhash;
                   7895: }
                   7896: 
1.667     albertel 7897: # ------------------------------------------------------------ tmpput interface
                   7898: sub tmpput {
1.802     raeburn  7899:     my ($storehash,$server,$context)=@_;
1.667     albertel 7900:     my $items='';
1.800     albertel 7901:     foreach my $item (keys(%$storehash)) {
                   7902: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7903:     }
                   7904:     $items=~s/\&$//;
1.802     raeburn  7905:     if (defined($context)) {
                   7906:         $items .= ':'.&escape($context);
                   7907:     }
1.667     albertel 7908:     return &reply("tmpput:$items",$server);
                   7909: }
                   7910: 
                   7911: # ------------------------------------------------------------ tmpget interface
                   7912: sub tmpget {
1.688     albertel 7913:     my ($token,$server)=@_;
                   7914:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7915:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7916:     my %returnhash;
1.1328    raeburn  7917:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7918:         return %returnhash;
                   7919:     }
1.667     albertel 7920:     foreach my $item (split(/\&/,$rep)) {
                   7921: 	my ($key,$value)=split(/=/,$item);
                   7922: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7923:     }
                   7924:     return %returnhash;
                   7925: }
                   7926: 
1.1113    raeburn  7927: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7928: sub tmpdel {
                   7929:     my ($token,$server)=@_;
                   7930:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7931:     return &reply("tmpdel:$token",$server);
                   7932: }
                   7933: 
1.1198    raeburn  7934: # ------------------------------------------------------------ get_timebased_id 
                   7935: 
                   7936: sub get_timebased_id {
                   7937:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7938:         $maxtries) = @_;
                   7939:     my ($newid,$error,$dellock);
                   7940:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7941:         return ('','ok','invalid call to get suffix');
                   7942:     }
                   7943: 
                   7944: # set defaults for any optional args for which values were not supplied
                   7945:     if ($who eq '') {
                   7946:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7947:     }
                   7948:     if (!$locktries) {
                   7949:         $locktries = 3;
                   7950:     }
                   7951:     if (!$maxtries) {
                   7952:         $maxtries = 10;
                   7953:     }
                   7954:     
                   7955:     if (($cdom eq '') || ($cnum eq '')) {
                   7956:         if ($env{'request.course.id'}) {
                   7957:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7958:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7959:         }
                   7960:         if (($cdom eq '') || ($cnum eq '')) {
                   7961:             return ('','ok','call to get suffix not in course context');
                   7962:         }
                   7963:     }
                   7964: 
                   7965: # construct locking item
                   7966:     my $lockhash = {
                   7967:                       $prefix."\0".'locked_'.$keyid => $who,
                   7968:                    };
                   7969:     my $tries = 0;
                   7970: 
                   7971: # attempt to get lock on nohist_$namespace file
1.1494    raeburn  7972:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198    raeburn  7973:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7974:         $tries ++;
                   7975:         sleep 1;
1.1494    raeburn  7976:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198    raeburn  7977:     }
                   7978: 
                   7979: # attempt to get unique identifier, based on current timestamp
                   7980:     if ($gotlock eq 'ok') {
1.1494    raeburn  7981:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
1.1198    raeburn  7982:         my $id = time;
                   7983:         $newid = $id;
1.1268    raeburn  7984:         if ($idtype eq 'addcode') {
                   7985:             $newid .= &sixnum_code();
                   7986:         }
1.1198    raeburn  7987:         my $idtries = 0;
                   7988:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7989:             if ($idtype eq 'concat') {
                   7990:                 $newid = $id.$idtries;
1.1268    raeburn  7991:             } elsif ($idtype eq 'addcode') {
                   7992:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7993:             } else {
                   7994:                 $newid ++;
                   7995:             }
                   7996:             $idtries ++;
                   7997:         }
                   7998:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7999:             my %new_item =  (
                   8000:                               $prefix."\0".$newid => $who,
                   8001:                             );
1.1494    raeburn  8002:             my $putresult = &put('nohist_'.$namespace,\%new_item,
1.1198    raeburn  8003:                                                  $cdom,$cnum);
                   8004:             if ($putresult ne 'ok') {
                   8005:                 undef($newid);
                   8006:                 $error = 'error saving new item: '.$putresult;
                   8007:             }
                   8008:         } else {
1.1268    raeburn  8009:              undef($newid);
1.1198    raeburn  8010:              $error = ('error: no unique suffix available for the new item ');
                   8011:         }
                   8012: #  remove lock
                   8013:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   8014:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   8015:     } else {
                   8016:         $error = "error: could not obtain lockfile\n";
                   8017:         $dellock = 'ok';
1.1276    raeburn  8018:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   8019:             $dellock = 'nolock';
                   8020:         }
1.1198    raeburn  8021:     }
                   8022:     return ($newid,$dellock,$error);
                   8023: }
                   8024: 
1.1268    raeburn  8025: sub sixnum_code {
                   8026:     my $code;
                   8027:     for (0..6) {
                   8028:         $code .= int( rand(9) );
                   8029:     }
                   8030:     return $code;
                   8031: }
                   8032: 
1.765     albertel 8033: # -------------------------------------------------- portfolio access checking
                   8034: 
                   8035: sub portfolio_access {
1.1270    raeburn  8036:     my ($requrl,$clientip) = @_;
1.765     albertel 8037:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  8038:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  8039:     if ($result) {
                   8040:         my %setters;
                   8041:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473    raeburn  8042:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   8043:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   8044:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8045:                 return 'B';
                   8046:             }
                   8047:         } else {
1.1473    raeburn  8048:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   8049:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8050:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8051:                 return 'B';
                   8052:             }
                   8053:         }
                   8054:     }
1.765     albertel 8055:     if ($result eq 'ok') {
1.766     albertel 8056:        return 'F';
1.765     albertel 8057:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 8058:        return 'A';
1.765     albertel 8059:     }
1.766     albertel 8060:     return '';
1.765     albertel 8061: }
                   8062: 
                   8063: sub get_portfolio_access {
1.1521    raeburn  8064:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash,$portaccessref) = @_;
1.767     albertel 8065: 
                   8066:     if (!ref($access_hash)) {
                   8067: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   8068: 	my %access_controls = &get_access_controls($current_perms,$group,
                   8069: 						   $file_name);
                   8070: 	$access_hash = $access_controls{$file_name};
                   8071:     }
                   8072: 
1.1521    raeburn  8073:     my $portaccess;
                   8074:     if (ref($portaccess) eq 'SCALAR') {
                   8075:         $portaccess = $$portaccessref;
                   8076:     } else {
                   8077:         $portaccess = &usertools_access($unum,$udom,'portaccess',undef,'tools');
                   8078:     }
                   8079: 
1.1522    raeburn  8080:     my ($public,$guest,@domains,@users,@courses,@groups,@ips,@userips);
1.765     albertel 8081:     my $now = time;
                   8082:     if (ref($access_hash) eq 'HASH') {
                   8083:         foreach my $key (keys(%{$access_hash})) {
                   8084:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1521    raeburn  8085:             next if (($scope ne 'ip') && ($portaccess == 0));
1.765     albertel 8086:             if ($start > $now) {
                   8087:                 next;
                   8088:             }
                   8089:             if ($end && $end<$now) {
                   8090:                 next;
                   8091:             }
                   8092:             if ($scope eq 'public') {
                   8093:                 $public = $key;
                   8094:                 last;
                   8095:             } elsif ($scope eq 'guest') {
                   8096:                 $guest = $key;
                   8097:             } elsif ($scope eq 'domains') {
                   8098:                 push(@domains,$key);
                   8099:             } elsif ($scope eq 'users') {
                   8100:                 push(@users,$key);
                   8101:             } elsif ($scope eq 'course') {
                   8102:                 push(@courses,$key);
                   8103:             } elsif ($scope eq 'group') {
                   8104:                 push(@groups,$key);
1.1270    raeburn  8105:             } elsif ($scope eq 'ip') {
                   8106:                 push(@ips,$key);
1.1522    raeburn  8107:             } elsif ($scope eq 'userip') {
                   8108:                 push(@userips,$key);
1.765     albertel 8109:             }
                   8110:         }
                   8111:         if ($public) {
                   8112:             return 'ok';
1.1270    raeburn  8113:         } elsif (@ips > 0) {
                   8114:             my $allowed;
                   8115:             foreach my $ipkey (@ips) {
                   8116:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   8117:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   8118:                         $allowed = 1;
                   8119:                         last; 
                   8120:                     }
                   8121:                 }
                   8122:             }
                   8123:             if ($allowed) {
                   8124:                 return 'ok';
                   8125:             }
1.1522    raeburn  8126:         } elsif (@userips > 0) {
                   8127:             my $allowed;
                   8128:             foreach my $useripkey (@userips) {
                   8129:                 if (ref($access_hash->{$useripkey}{'ip'}) eq 'ARRAY') {
                   8130:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$useripkey}{'ip'}}),$clientip)) {
                   8131:                         $allowed = 1;
                   8132:                         last;
                   8133:                     }
                   8134:                 }
                   8135:             }
                   8136:             if ($allowed) {
                   8137:                 return 'ok';
                   8138:             }
1.765     albertel 8139:         }
                   8140:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   8141:             if ($guest) {
                   8142:                 return $guest;
                   8143:             }
                   8144:         } else {
                   8145:             if (@domains > 0) {
                   8146:                 foreach my $domkey (@domains) {
                   8147:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   8148:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   8149:                             return 'ok';
                   8150:                         }
                   8151:                     }
                   8152:                 }
                   8153:             }
                   8154:             if (@users > 0) {
                   8155:                 foreach my $userkey (@users) {
1.865     raeburn  8156:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   8157:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   8158:                             if (ref($item) eq 'HASH') {
                   8159:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   8160:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   8161:                                     return 'ok';
                   8162:                                 }
                   8163:                             }
                   8164:                         }
                   8165:                     } 
1.765     albertel 8166:                 }
                   8167:             }
                   8168:             my %roleshash;
                   8169:             my @courses_and_groups = @courses;
                   8170:             push(@courses_and_groups,@groups); 
                   8171:             if (@courses_and_groups > 0) {
                   8172:                 my (%allgroups,%allroles); 
                   8173:                 my ($start,$end,$role,$sec,$group);
                   8174:                 foreach my $envkey (%env) {
1.1060    raeburn  8175:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 8176:                         my $cid = $2.'_'.$3; 
                   8177:                         if ($1 eq 'gr') {
                   8178:                             $group = $4;
                   8179:                             $allgroups{$cid}{$group} = $env{$envkey};
                   8180:                         } else {
                   8181:                             if ($4 eq '') {
                   8182:                                 $sec = 'none';
                   8183:                             } else {
                   8184:                                 $sec = $4;
                   8185:                             }
                   8186:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   8187:                         }
1.811     albertel 8188:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 8189:                         my $cid = $2.'_'.$3;
                   8190:                         if ($4 eq '') {
                   8191:                             $sec = 'none';
                   8192:                         } else {
                   8193:                             $sec = $4;
                   8194:                         }
                   8195:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   8196:                     }
                   8197:                 }
                   8198:                 if (keys(%allroles) == 0) {
                   8199:                     return;
                   8200:                 }
                   8201:                 foreach my $key (@courses_and_groups) {
                   8202:                     my %content = %{$$access_hash{$key}};
                   8203:                     my $cnum = $content{'number'};
                   8204:                     my $cdom = $content{'domain'};
                   8205:                     my $cid = $cdom.'_'.$cnum;
                   8206:                     if (!exists($allroles{$cid})) {
                   8207:                         next;
                   8208:                     }    
                   8209:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   8210:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   8211:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   8212:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   8213:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   8214:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   8215:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   8216:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   8217:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   8218:                                         if (grep/^all$/,@sections) {
                   8219:                                             return 'ok';
                   8220:                                         } else {
                   8221:                                             if (grep/^$sec$/,@sections) {
                   8222:                                                 return 'ok';
                   8223:                                             }
                   8224:                                         }
                   8225:                                     }
                   8226:                                 }
                   8227:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   8228:                                     if (grep/^none$/,@groups) {
                   8229:                                         return 'ok';
                   8230:                                     }
                   8231:                                 } else {
                   8232:                                     if (grep/^all$/,@groups) {
                   8233:                                         return 'ok';
                   8234:                                     } 
                   8235:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   8236:                                         if (grep/^$group$/,@groups) {
                   8237:                                             return 'ok';
                   8238:                                         }
                   8239:                                     }
                   8240:                                 } 
                   8241:                             }
                   8242:                         }
                   8243:                     }
                   8244:                 }
                   8245:             }
                   8246:             if ($guest) {
                   8247:                 return $guest;
                   8248:             }
                   8249:         }
                   8250:     }
                   8251:     return;
                   8252: }
                   8253: 
                   8254: sub course_group_datechecker {
                   8255:     my ($dates,$now,$status) = @_;
                   8256:     my ($start,$end) = split(/\./,$dates);
                   8257:     if (!$start && !$end) {
                   8258:         return 'ok';
                   8259:     }
                   8260:     if (grep/^active$/,@{$status}) {
                   8261:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   8262:             return 'ok';
                   8263:         }
                   8264:     }
                   8265:     if (grep/^previous$/,@{$status}) {
                   8266:         if ($end > $now ) {
                   8267:             return 'ok';
                   8268:         }
                   8269:     }
                   8270:     if (grep/^future$/,@{$status}) {
                   8271:         if ($start > $now) {
                   8272:             return 'ok';
                   8273:         }
                   8274:     }
                   8275:     return; 
                   8276: }
                   8277: 
                   8278: sub parse_portfolio_url {
                   8279:     my ($url) = @_;
                   8280: 
                   8281:     my ($type,$udom,$unum,$group,$file_name);
                   8282:     
1.823     albertel 8283:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 8284: 	$type = 1;
                   8285:         $udom = $1;
                   8286:         $unum = $2;
                   8287:         $file_name = $3;
1.823     albertel 8288:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 8289: 	$type = 2;
                   8290:         $udom = $1;
                   8291:         $unum = $2;
                   8292:         $group = $3;
                   8293:         $file_name = $3.'/'.$4;
                   8294:     }
                   8295:     if (wantarray) {
                   8296: 	return ($type,$udom,$unum,$file_name,$group);
                   8297:     }
                   8298:     return $type;
                   8299: }
                   8300: 
                   8301: sub is_portfolio_url {
                   8302:     my ($url) = @_;
                   8303:     return scalar(&parse_portfolio_url($url));
                   8304: }
                   8305: 
1.798     raeburn  8306: sub is_portfolio_file {
                   8307:     my ($file) = @_;
1.820     raeburn  8308:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  8309:         return 1;
                   8310:     }
                   8311:     return;
                   8312: }
                   8313: 
1.1504    raeburn  8314: sub is_coursetool_logo {
                   8315:     my ($uri) = @_;
                   8316:     if ($env{'request.course.id'}) {
                   8317:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8318:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
                   8319:             return 1;
                   8320:         }
                   8321:     }
                   8322:     return;
                   8323: }
                   8324: 
1.976     raeburn  8325: sub usertools_access {
1.1084    raeburn  8326:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  8327:     my ($access,%tools);
                   8328:     if ($context eq '') {
                   8329:         $context = 'tools';
                   8330:     }
                   8331:     if ($context eq 'requestcourses') {
                   8332:         %tools = (
                   8333:                       official   => 1,
                   8334:                       unofficial => 1,
1.1006    raeburn  8335:                       community  => 1,
1.1246    raeburn  8336:                       textbook   => 1,
1.1305    raeburn  8337:                       placement  => 1,
1.1368    raeburn  8338:                       lti        => 1,
1.985     raeburn  8339:                  );
1.1183    raeburn  8340:     } elsif ($context eq 'requestauthor') {
                   8341:         %tools = (
                   8342:                       requestauthor => 1,
                   8343:                  );
1.1517    raeburn  8344:     } elsif ($context eq 'authordefaults') {
                   8345:         %tools = (
                   8346:                       webdav    => 1,
                   8347:                  );
1.985     raeburn  8348:     } else {
                   8349:         %tools = (
                   8350:                       aboutme   => 1,
                   8351:                       blog      => 1,
1.1526    raeburn  8352:                       webdav    => 1,
1.985     raeburn  8353:                       portfolio => 1,
1.1517    raeburn  8354:                       portaccess => 1,
1.1489    raeburn  8355:                       timezone  => 1,
1.985     raeburn  8356:                  );
                   8357:     }
1.976     raeburn  8358:     return if (!defined($tools{$tool}));
                   8359: 
1.1242    raeburn  8360:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  8361:         $udom = $env{'user.domain'};
                   8362:         $uname = $env{'user.name'};
                   8363:     }
                   8364: 
1.978     raeburn  8365:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   8366:         if ($action ne 'reload') {
1.985     raeburn  8367:             if ($context eq 'requestcourses') {
                   8368:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  8369:             } elsif ($context eq 'requestauthor') {
                   8370:                 return $env{'environment.canrequest.author'};
1.1517    raeburn  8371:             } elsif ($context eq 'authordefaults') {
                   8372:                 if ($tool eq 'webdav') {
                   8373:                     return $env{'environment.availabletools.'.$tool};
                   8374:                 }
1.985     raeburn  8375:             } else {
                   8376:                 return $env{'environment.availabletools.'.$tool};
                   8377:             }
                   8378:         }
1.976     raeburn  8379:     }
                   8380: 
1.1183    raeburn  8381:     my ($toolstatus,$inststatus,$envkey);
                   8382:     if ($context eq 'requestauthor') {
1.1517    raeburn  8383:         $envkey = $context;
                   8384:     } elsif ($context eq 'authordefaults') {
                   8385:         if ($tool eq 'webdav') {
                   8386:             $envkey = 'tools.'.$tool;
                   8387:         }
1.1183    raeburn  8388:     } else {
                   8389:         $envkey = $context.'.'.$tool;
                   8390:     }
1.976     raeburn  8391: 
1.985     raeburn  8392:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8393:          ($action ne 'reload')) {
1.1183    raeburn  8394:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  8395:         $inststatus = $env{'environment.inststatus'};
                   8396:     } else {
1.1084    raeburn  8397:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  8398:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  8399:             $inststatus = $userenvref->{'inststatus'};
                   8400:         } else {
1.1183    raeburn  8401:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   8402:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  8403:             $inststatus = $userenv{'inststatus'};
                   8404:         }
1.976     raeburn  8405:     }
                   8406: 
                   8407:     if ($toolstatus ne '') {
                   8408:         if ($toolstatus) {
                   8409:             $access = 1;
                   8410:         } else {
                   8411:             $access = 0;
                   8412:         }
                   8413:         return $access;
                   8414:     }
                   8415: 
1.1084    raeburn  8416:     my ($is_adv,%domdef);
                   8417:     if (ref($is_advref) eq 'HASH') {
                   8418:         $is_adv = $is_advref->{'is_adv'};
                   8419:     } else {
                   8420:         $is_adv = &is_advanced_user($udom,$uname);
                   8421:     }
                   8422:     if (ref($domdefref) eq 'HASH') {
                   8423:         %domdef = %{$domdefref};
                   8424:     } else {
                   8425:         %domdef = &get_domain_defaults($udom);
                   8426:     }
1.976     raeburn  8427:     if (ref($domdef{$tool}) eq 'HASH') {
                   8428:         if ($is_adv) {
                   8429:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8430:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8431:                     $access = 1;
                   8432:                 } else {
                   8433:                     $access = 0;
                   8434:                 }
                   8435:                 return $access;
                   8436:             }
                   8437:         }
                   8438:         if ($inststatus ne '') {
                   8439:             my ($hasaccess,$hasnoaccess);
                   8440:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8441:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8442:                     if ($domdef{$tool}{$affiliation}) {
                   8443:                         $hasaccess = 1;
                   8444:                     } else {
                   8445:                         $hasnoaccess = 1;
                   8446:                     }
                   8447:                 }
                   8448:             }
                   8449:             if ($hasaccess || $hasnoaccess) {
                   8450:                 if ($hasaccess) {
                   8451:                     $access = 1;
                   8452:                 } elsif ($hasnoaccess) {
                   8453:                     $access = 0; 
                   8454:                 }
                   8455:                 return $access;
                   8456:             }
                   8457:         } else {
                   8458:             if ($domdef{$tool}{'default'} ne '') {
                   8459:                 if ($domdef{$tool}{'default'}) {
                   8460:                     $access = 1;
                   8461:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8462:                     $access = 0;
                   8463:                 }
                   8464:                 return $access;
                   8465:             }
                   8466:         }
                   8467:     } else {
1.1177    raeburn  8468:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8469:             $access = 1;
                   8470:         } else {
                   8471:             $access = 0;
                   8472:         }
1.976     raeburn  8473:         return $access;
                   8474:     }
                   8475: }
                   8476: 
1.1050    raeburn  8477: sub is_course_owner {
                   8478:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8479:     if (($udom eq '') || ($uname eq '')) {
                   8480:         $udom = $env{'user.domain'};
                   8481:         $uname = $env{'user.name'};
                   8482:     }
                   8483:     unless (($udom eq '') || ($uname eq '')) {
                   8484:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8485:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8486:                 return 1;
                   8487:             } else {
1.1494    raeburn  8488:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
1.1050    raeburn  8489:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8490:                     return 1;
                   8491:                 }
                   8492:             }
                   8493:         }
                   8494:     }
                   8495:     return;
                   8496: }
                   8497: 
1.976     raeburn  8498: sub is_advanced_user {
1.1512    raeburn  8499:     my ($udom,$uname,$nocache) = @_;
                   8500:     my ($is_adv,$is_author,$use_cache,$hashid);
1.1085    raeburn  8501:     if ($udom ne '' && $uname ne '') {
                   8502:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8503:             if (wantarray) {
                   8504:                 return ($env{'user.adv'},$env{'user.author'});
                   8505:             } else {
                   8506:                 return $env{'user.adv'};
                   8507:             }
1.1512    raeburn  8508:         } elsif (!$nocache) {
                   8509:             $use_cache = 1;
                   8510:             $hashid = "$udom:$uname";  
                   8511:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
                   8512:             if ($cached) {
                   8513:                 ($is_adv,$is_author) = split(/:/,$info);
                   8514:                 if (wantarray) {
                   8515:                     return ($is_adv,$is_author);
                   8516:                 }
                   8517:                 return $is_adv; 
                   8518:             }
1.1085    raeburn  8519:         }
                   8520:     }
1.976     raeburn  8521:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8522:     my %allroles;
                   8523:     foreach my $role (keys(%roleshash)) {
                   8524:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8525:         my $area = '/'.$tdomain.'/'.$trest;
                   8526:         if ($sec ne '') {
                   8527:             $area .= '/'.$sec;
                   8528:         }
                   8529:         if (($area ne '') && ($trole ne '')) {
                   8530:             my $spec=$trole.'.'.$area;
                   8531:             if ($trole =~ /^cr\//) {
                   8532:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8533:             } elsif ($trole ne 'gr') {
                   8534:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8535:             }
1.1128    raeburn  8536:             if ($trole eq 'au') {
                   8537:                 $is_author = 1;
                   8538:             }
1.976     raeburn  8539:         }
                   8540:     }
                   8541:     foreach my $role (keys(%allroles)) {
                   8542:         last if ($is_adv);
                   8543:         foreach my $item (split(/:/,$allroles{$role})) {
                   8544:             if ($item ne '') {
                   8545:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8546:                 if ($privilege eq 'adv') {
                   8547:                     $is_adv = 1;
                   8548:                     last;
                   8549:                 }
                   8550:             }
                   8551:         }
                   8552:     }
1.1512    raeburn  8553:     if ($use_cache) {
                   8554:         my $cachetime = 600;
                   8555:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
                   8556:     }
1.1128    raeburn  8557:     if (wantarray) {
                   8558:         return ($is_adv,$is_author);
                   8559:     }
1.976     raeburn  8560:     return $is_adv;
                   8561: }
1.798     raeburn  8562: 
1.1035    raeburn  8563: sub check_can_request {
1.1368    raeburn  8564:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8565:     my $canreq = 0;
1.1368    raeburn  8566:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8567:         $uname = $env{'user.name'};
                   8568:         $udom = $env{'user.domain'};
                   8569:     }
1.1035    raeburn  8570:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8571:     my @options = ('approval','validate','autolimit');
                   8572:     my $optregex = join('|',@options);
                   8573:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486    raeburn  8574:         my %willtrust;
1.1035    raeburn  8575:         foreach my $type (@{$types}) {
1.1368    raeburn  8576:             if (&usertools_access($uname,$udom,$type,undef,
                   8577:                                   'requestcourses')) {
1.1035    raeburn  8578:                 $canreq ++;
1.1036    raeburn  8579:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  8580:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8581:                 }
1.1368    raeburn  8582:                 if ($dom eq $udom) {
1.1035    raeburn  8583:                     $can_request->{$type} = 1;
                   8584:                 }
                   8585:             }
1.1368    raeburn  8586:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8587:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8588:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8589:                 if (@curr > 0) {
1.1036    raeburn  8590:                     foreach my $item (@curr) {
                   8591:                         if (ref($request_domains) eq 'HASH') {
                   8592:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8593:                             if ($otherdom ne '') {
1.1486    raeburn  8594:                                 unless (exists($willtrust{$otherdom})) {
                   8595:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
                   8596:                                 }
                   8597:                                 if ($willtrust{$otherdom}) {
                   8598:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8599:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8600:                                             push(@{$request_domains->{$type}},$otherdom);
                   8601:                                         }
                   8602:                                     } else {
1.1036    raeburn  8603:                                         push(@{$request_domains->{$type}},$otherdom);
                   8604:                                     }
                   8605:                                 }
                   8606:                             }
                   8607:                         }
                   8608:                     }
1.1368    raeburn  8609:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8610:                         $canreq ++;
1.1035    raeburn  8611:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8612:                             $can_request->{$type} = 1;
                   8613:                         }
                   8614:                     }
                   8615:                 }
                   8616:             }
                   8617:         }
                   8618:     }
                   8619:     return $canreq;
                   8620: }
                   8621: 
1.341     www      8622: # ---------------------------------------------- Custom access rule evaluation
                   8623: 
                   8624: sub customaccess {
                   8625:     my ($priv,$uri)=@_;
1.807     albertel 8626:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8627:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8628:     $udom = &LONCAPA::clean_domain($udom);
                   8629:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8630:     my $access=0;
1.800     albertel 8631:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8632: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8633: 	if ($type eq 'user') {
                   8634: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8635: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8636: 		if ($tdom) {
                   8637: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8638: 		}
1.896     albertel 8639: 		if ($tuname) {
                   8640: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8641: 		}
                   8642: 		$access=($effect eq 'allow');
                   8643: 		last;
                   8644: 	    }
                   8645: 	} else {
                   8646: 	    if ($role) {
                   8647: 		if ($role ne $urole) { next; }
                   8648: 	    }
                   8649: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8650: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8651: 		if ($tdom) {
                   8652: 		    if ($tdom ne $udom) { next; }
                   8653: 		}
                   8654: 		if ($tcrs) {
                   8655: 		    if ($tcrs ne $ucrs) { next; }
                   8656: 		}
                   8657: 		if ($tsec) {
                   8658: 		    if ($tsec ne $usec) { next; }
                   8659: 		}
                   8660: 		$access=($effect eq 'allow');
                   8661: 		last;
                   8662: 	    }
                   8663: 	    if ($realm eq '' && $role eq '') {
                   8664: 		$access=($effect eq 'allow');
                   8665: 	    }
1.402     bowersj2 8666: 	}
1.341     www      8667:     }
                   8668:     return $access;
                   8669: }
                   8670: 
1.103     harris41 8671: # ------------------------------------------------- Check for a user privilege
1.12      www      8672: 
                   8673: sub allowed {
1.1461    raeburn  8674:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8675:     my $ver_orguri=$uri;
1.439     www      8676:     $uri=&deversion($uri);
1.152     www      8677:     my $orguri=$uri;
1.52      www      8678:     $uri=&declutter($uri);
1.809     raeburn  8679: 
1.810     raeburn  8680:     if ($priv eq 'evb') {
1.1478    raeburn  8681: # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8682:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8683:             return $1;
                   8684:         } else {
                   8685:             return;
                   8686:         }
                   8687:     }
                   8688: 
1.620     albertel 8689:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8690: # Free bre access to adm and meta resources
1.1436    raeburn  8691:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8692: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8693: 	&& ($priv eq 'bre')) {
1.14      www      8694: 	return 'F';
1.159     www      8695:     }
                   8696: 
1.545     banghart 8697: # Free bre access to user's own portfolio contents
1.714     raeburn  8698:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8699:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8700: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8701:         my %setters;
1.1473    raeburn  8702:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8703:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8704:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8705:             return 'B';
                   8706:         } else {
                   8707:             return 'F';
                   8708:         }
1.545     banghart 8709:     }
                   8710: 
1.762     raeburn  8711: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8712:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8713:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8714:         if (exists($env{'request.course.id'})) {
                   8715:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8716:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8717:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8718:                 my $courseprivid=$env{'request.course.id'};
                   8719:                 $courseprivid=~s/\_/\//;
                   8720:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8721:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8722:                     return $1; 
1.762     raeburn  8723:                 } else {
                   8724:                     if ($env{'request.course.sec'}) {
                   8725:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8726:                     }
                   8727:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8728:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8729:                         return $2;
                   8730:                     }
1.714     raeburn  8731:                 }
                   8732:             }
                   8733:         }
                   8734:     }
                   8735: 
1.159     www      8736: # Free bre to public access
                   8737: 
                   8738:     if ($priv eq 'bre') {
1.1362    raeburn  8739:         my $copyright;
                   8740:         unless ($uri =~ /ext\.tool/) {
                   8741:             $copyright=&metadata($uri,'copyright');
                   8742:         }
1.620     albertel 8743: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8744:            return 'F'; 
                   8745:         }
1.238     www      8746:         if ($copyright eq 'priv') {
                   8747:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8748: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8749: 		return '';
                   8750:             }
                   8751:         }
                   8752:         if ($copyright eq 'domain') {
                   8753:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8754: 	    unless (($env{'user.domain'} eq $1) ||
                   8755:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8756: 		return '';
                   8757:             }
1.262     matthew  8758:         }
1.620     albertel 8759:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8760:             # Library role, so allow browsing of resources in this domain.
                   8761:             return 'F';
1.238     www      8762:         }
1.341     www      8763:         if ($copyright eq 'custom') {
                   8764: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8765:         }
1.14      www      8766:     }
1.264     matthew  8767:     # Domain coordinator is trying to create a course
1.620     albertel 8768:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8769:         # uri is the requested domain in this case.
                   8770:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8771:         # a role of dc for the domain in question.
1.620     albertel 8772:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8773:     }
1.29      www      8774: 
1.52      www      8775:     my $thisallowed='';
                   8776:     my $statecond=0;
                   8777:     my $courseprivid='';
                   8778: 
1.1039    raeburn  8779:     my $ownaccess;
1.1043    raeburn  8780:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8781:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8782:         if ($uri eq '') {
                   8783:             $ownaccess = 1;
                   8784:         } else {
                   8785:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8786:                 my $udom = $env{'user.domain'};
                   8787:                 my $uname = $env{'user.name'};
                   8788:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8789:                     $ownaccess = 1;
1.1040    raeburn  8790:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8791:                     unless ($uri =~ m{\.\./}) {
                   8792:                         $ownaccess = 1;
                   8793:                     }
                   8794:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8795:                     my $now = time;
                   8796:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8797:                         my $adom = $1;
                   8798:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8799:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452    raeburn  8800:                                 my ($start,$end) = split(/\./,$env{$key});
                   8801:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8802:                                     $ownaccess = 1;
                   8803:                                     last;
                   8804:                                 }
                   8805:                             }
                   8806:                         }
                   8807:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8808:                         my $adom = $1;
                   8809:                         my $aname = $2;
1.1042    raeburn  8810:                         foreach my $role ('ca','aa') { 
                   8811:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8812:                                 my ($start,$end) =
1.1452    raeburn  8813:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8814:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8815:                                     $ownaccess = 1;
                   8816:                                     last;
                   8817:                                 }
1.1039    raeburn  8818:                             }
                   8819:                         }
                   8820:                     }
                   8821:                 }
                   8822:             }
                   8823:         }
                   8824:     }
                   8825: 
1.52      www      8826: # Course
                   8827: 
1.620     albertel 8828:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8829:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8830:             $thisallowed.=$1;
                   8831:         }
1.52      www      8832:     }
1.29      www      8833: 
1.52      www      8834: # Domain
                   8835: 
1.620     albertel 8836:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8837:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8838:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8839:             $thisallowed.=$1;
                   8840:         }
1.12      www      8841:     }
1.52      www      8842: 
1.1141    raeburn  8843: # User who is not author or co-author might still be able to edit
                   8844: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8845:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8846:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8847:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8848:             $thisallowed.=$1;
                   8849:         }
                   8850:     }
                   8851: 
1.52      www      8852: # Course: uri itself is a course
1.66      www      8853:     my $courseuri=$uri;
                   8854:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8855:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8856: 
1.620     albertel 8857:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8858:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8859:         if ($priv eq 'mip') {
                   8860:             my $rem = $1;
                   8861:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8862:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8863:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8864:                 if ($cdom ne '') {
1.1410    raeburn  8865:                     my %passwdconf = &get_passwdconf($cdom);
                   8866:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8867:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8868:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8869:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8870:                                 unless (@inststatuses) {
                   8871:                                     @inststatuses = ('default');
                   8872:                                 }
                   8873:                                 foreach my $status (@inststatuses) {
                   8874:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8875:                                         $thisallowed.=$rem;
                   8876:                                     }
                   8877:                                 }
                   8878:                             }
                   8879:                         }
1.1409    raeburn  8880:                     }
                   8881:                 }
                   8882:             }
                   8883:         } else {
                   8884:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8885:                 $thisallowed.=$1;
                   8886:             }
1.1039    raeburn  8887:         }
1.12      www      8888:     }
1.29      www      8889: 
1.665     albertel 8890: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8891: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8892:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8893: 	$thisallowed='';
1.671     raeburn  8894:         my ($match)=&is_on_map($uri);
                   8895:         if ($match) {
                   8896:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8897:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8898:                 my $value = $1;
1.1461    raeburn  8899:                 my $deeplinkblock;
                   8900:                 unless ($nodeeplinkcheck) {
                   8901:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8902:                 }
1.1402    raeburn  8903:                 if ($deeplinkblock) {
                   8904:                     $thisallowed='D';
                   8905:                 } elsif ($noblockcheck) {
1.1281    raeburn  8906:                     $thisallowed.=$value;
1.1162    raeburn  8907:                 } else {
1.1424    raeburn  8908:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8909:                     if (@blockers > 0) {
                   8910:                         $thisallowed = 'B';
                   8911:                     } else {
                   8912:                         $thisallowed.=$value;
                   8913:                     }
1.1162    raeburn  8914:                 }
1.671     raeburn  8915:             }
                   8916:         } else {
1.705     albertel 8917:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8918:             if ($refuri) {
                   8919:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8920:                     $thisallowed='F';
1.671     raeburn  8921:                 } else {
                   8922:                     $refuri=&declutter($refuri);
                   8923:                     my ($match) = &is_on_map($refuri);
                   8924:                     if ($match) {
1.1461    raeburn  8925:                         my $deeplinkblock;
                   8926:                         unless ($nodeeplinkcheck) {
                   8927:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8928:                         }
1.1402    raeburn  8929:                         if ($deeplinkblock) {
                   8930:                             $thisallowed='D';
                   8931:                         } elsif ($noblockcheck) {
1.1281    raeburn  8932:                             $thisallowed='F';
1.1162    raeburn  8933:                         } else {
1.1426    raeburn  8934:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8935:                             if (@blockers > 0) {
                   8936:                                 $thisallowed = 'B';
                   8937:                             } else {
                   8938:                                 $thisallowed='F';
                   8939:                             }
1.1162    raeburn  8940:                         }
1.671     raeburn  8941:                     }
1.669     raeburn  8942:                 }
1.671     raeburn  8943:             }
                   8944:         }
1.314     www      8945:     }
1.492     albertel 8946: 
1.766     albertel 8947:     if ($priv eq 'bre'
                   8948: 	&& $thisallowed ne 'F' 
                   8949: 	&& $thisallowed ne '2'
                   8950: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8951: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8952:     }
1.1250    raeburn  8953: 
1.52      www      8954: # Full access at system, domain or course-wide level? Exit.
1.29      www      8955:     if ($thisallowed=~/F/) {
                   8956: 	return 'F';
                   8957:     }
                   8958: 
1.52      www      8959: # If this is generating or modifying users, exit with special codes
1.29      www      8960: 
1.1517    raeburn  8961:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
1.643     www      8962: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8963: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8964: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8965: 	    unless ($auname) { return $thisallowed; }
                   8966: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8967: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8968: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8969: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
1.1517    raeburn  8970: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
                   8971:             my ($audom,$auname)=split('/',$uri);
                   8972:             unless ($auname) { return $thisallowed; }
                   8973:             unless (($env{'request.role'} eq "dc./$audom") ||
                   8974:                     ($env{'request.role'} eq "ca./$uri")) {
                   8975:                 return '';
                   8976:             }
1.642     albertel 8977: 	}
1.52      www      8978: 	return $thisallowed;
                   8979:     }
                   8980: #
1.103     harris41 8981: # Gathered so far: system, domain and course wide privileges
1.52      www      8982: #
                   8983: # Course: See if uri or referer is an individual resource that is part of 
                   8984: # the course
                   8985: 
1.620     albertel 8986:     if ($env{'request.course.id'}) {
1.232     www      8987: 
1.1504    raeburn  8988:         if ($priv eq 'bre') {
                   8989:             if (&is_coursetool_logo($uri)) {
                   8990:                 return 'F';
                   8991:             }
                   8992:         }
                   8993: 
1.1409    raeburn  8994: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8995: 
                   8996:         if ($priv eq 'mip') {
                   8997:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8998:                 return $thisallowed;
                   8999:             } else {
                   9000:                 return '';
                   9001:             }
                   9002:         }
                   9003: 
1.620     albertel 9004:        $courseprivid=$env{'request.course.id'};
                   9005:        if ($env{'request.course.sec'}) {
                   9006:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      9007:        }
                   9008:        $courseprivid=~s/\_/\//;
                   9009:        my $checkreferer=1;
1.232     www      9010:        my ($match,$cond)=&is_on_map($uri);
                   9011:        if ($match) {
                   9012:            $statecond=$cond;
1.620     albertel 9013:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 9014:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  9015:                my $value = $1;
                   9016:                if ($priv eq 'bre') {
1.1461    raeburn  9017:                    my $deeplinkblock;
                   9018:                    unless ($nodeeplinkcheck) {
                   9019:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   9020:                    }
1.1458    raeburn  9021:                    if ($deeplinkblock) {
                   9022:                        $thisallowed = 'D';
                   9023:                    } elsif ($noblockcheck) {
1.1281    raeburn  9024:                        $thisallowed.=$value;
1.1162    raeburn  9025:                    } else {
1.1424    raeburn  9026:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  9027:                        if (@blockers > 0) {
                   9028:                            $thisallowed = 'B';
                   9029:                        } else {
                   9030:                            $thisallowed.=$value;
                   9031:                        }
1.1162    raeburn  9032:                    }
                   9033:                } else {
                   9034:                    $thisallowed.=$value;
                   9035:                }
1.52      www      9036:                $checkreferer=0;
                   9037:            }
1.29      www      9038:        }
1.1424    raeburn  9039: 
1.148     www      9040:        if ($checkreferer) {
1.620     albertel 9041: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      9042:             unless ($refuri) {
1.800     albertel 9043:                 foreach my $key (keys(%env)) {
                   9044: 		    if ($key=~/^httpref\..*\*/) {
                   9045: 			my $pattern=$key;
1.156     www      9046:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      9047:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   9048:                         $pattern=~s/\//\\\//g;
1.152     www      9049:                         if ($orguri=~/$pattern/) {
1.800     albertel 9050: 			    $refuri=$env{$key};
1.148     www      9051:                         }
                   9052:                     }
1.191     harris41 9053:                 }
1.148     www      9054:             }
1.232     www      9055: 
1.148     www      9056:          if ($refuri) { 
1.152     www      9057: 	  $refuri=&declutter($refuri);
1.232     www      9058:           my ($match,$cond)=&is_on_map($refuri);
                   9059:             if ($match) {
                   9060:               my $refstatecond=$cond;
1.620     albertel 9061:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 9062:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  9063:                   my $value = $1;
                   9064:                   if ($priv eq 'bre') {
1.1461    raeburn  9065:                       my $deeplinkblock;
                   9066:                       unless ($nodeeplinkcheck) {
                   9067:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   9068:                       }
1.1402    raeburn  9069:                       if ($deeplinkblock) {
                   9070:                           $thisallowed = 'D';
                   9071:                       } elsif ($noblockcheck) {
1.1281    raeburn  9072:                           $thisallowed.=$value;
1.1162    raeburn  9073:                       } else {
1.1426    raeburn  9074:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  9075:                           if (@blockers > 0) {
                   9076:                               $thisallowed = 'B';
                   9077:                           } else {
                   9078:                               $thisallowed.=$value;
                   9079:                           }
1.1162    raeburn  9080:                       }
                   9081:                   } else {
                   9082:                       $thisallowed.=$value;
                   9083:                   }
1.53      www      9084:                   $uri=$refuri;
                   9085:                   $statecond=$refstatecond;
1.52      www      9086:               }
                   9087:           }
1.148     www      9088:         }
1.29      www      9089:        }
1.52      www      9090:    }
1.29      www      9091: 
1.52      www      9092: #
1.103     harris41 9093: # Gathered now: all privileges that could apply, and condition number
1.52      www      9094: # 
                   9095: #
                   9096: # Full or no access?
                   9097: #
1.29      www      9098: 
1.52      www      9099:     if ($thisallowed=~/F/) {
                   9100: 	return 'F';
                   9101:     }
1.29      www      9102: 
1.52      www      9103:     unless ($thisallowed) {
                   9104:         return '';
                   9105:     }
1.29      www      9106: 
1.52      www      9107: # Restrictions exist, deal with them
                   9108: #
                   9109: #   C:according to course preferences
                   9110: #   R:according to resource settings
                   9111: #   L:unless locked
                   9112: #   X:according to user session state
                   9113: #
                   9114: 
                   9115: # Possibly locked functionality, check all courses
1.1454    raeburn  9116: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      9117: # Locks might take effect only after 10 minutes cache expiration for other
1.1454    raeburn  9118: # courses, and 2 minutes for current course, in which user has st or ta role
                   9119: # which is neither expired nor a future role (unless current course).
1.52      www      9120: 
1.1454    raeburn  9121:     my ($needlockcheck,$now,$crsonly);
1.52      www      9122:     if ($thisallowed=~/L/) {
1.1454    raeburn  9123:         $now = time;
                   9124:         if ($priv eq 'bre') {
                   9125:             if ($uri ne '') {
                   9126:                 if ($orguri =~ m{^/+res/}) {
                   9127:                     if ($uri =~ m{^lib/templates/}) {
                   9128:                         if ($env{'request.course.id'}) {
                   9129:                             $crsonly = 1;
                   9130:                             $needlockcheck = 1;
                   9131:                         }
                   9132:                     } else {
                   9133:                         $needlockcheck = 1;
                   9134:                     }
                   9135:                 } elsif ($env{'request.course.id'}) {
                   9136:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   9137:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   9138:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   9139:                         $crsonly = 1;
                   9140:                     }
                   9141:                     $needlockcheck = 1;
                   9142:                 }
                   9143:             }
                   9144:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   9145:             $needlockcheck = 1;
                   9146:         }
                   9147:     }
                   9148:     if ($needlockcheck) {
1.1453    raeburn  9149:         foreach my $envkey (keys(%env)) {
1.54      www      9150:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   9151:                my $courseid=$2;
                   9152:                my $roleid=$1.'.'.$2;
1.92      www      9153:                $courseid=~s/^\///;
1.1453    raeburn  9154:                unless ($env{'request.role'} eq $roleid) {
                   9155:                    my ($start,$end) = split(/\./,$env{$envkey});
                   9156:                    next unless (($now >= $start) && (!$end || $end > $now));
                   9157:                }
1.54      www      9158:                my $expiretime=600;
1.620     albertel 9159:                if ($env{'request.role'} eq $roleid) {
1.54      www      9160: 		  $expiretime=120;
                   9161:                }
                   9162: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   9163:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 9164:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 9165: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      9166:                }
1.620     albertel 9167:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   9168:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   9169: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   9170:                        &log($env{'user.domain'},$env{'user.name'},
                   9171:                             $env{'user.home'},
1.57      www      9172:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      9173:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 9174:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      9175: 		       return '';
                   9176:                    }
                   9177:                }
1.620     albertel 9178:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   9179:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455    raeburn  9180: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 9181:                        &log($env{'user.domain'},$env{'user.name'},
                   9182:                             $env{'user.home'},
1.57      www      9183:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      9184:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 9185:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      9186: 		       return '';
                   9187:                    }
                   9188:                }
                   9189: 	   }
1.29      www      9190:        }
1.52      www      9191:     }
1.1424    raeburn  9192: 
1.52      www      9193: #
                   9194: # Rest of the restrictions depend on selected course
                   9195: #
                   9196: 
1.620     albertel 9197:     unless ($env{'request.course.id'}) {
1.766     albertel 9198: 	if ($thisallowed eq 'A') {
                   9199: 	    return 'A';
1.814     raeburn  9200:         } elsif ($thisallowed eq 'B') {
                   9201:             return 'B';
1.766     albertel 9202: 	} else {
                   9203: 	    return '1';
                   9204: 	}
1.52      www      9205:     }
1.29      www      9206: 
1.52      www      9207: #
                   9208: # Now user is definitely in a course
                   9209: #
1.53      www      9210: 
                   9211: 
                   9212: # Course preferences
                   9213: 
                   9214:    if ($thisallowed=~/C/) {
1.620     albertel 9215:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   9216:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   9217:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 9218: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  9219: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 9220: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   9221: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   9222: 			$env{'request.course.id'});
                   9223: 	   }
1.237     www      9224:            return '';
                   9225:        }
                   9226: 
1.620     albertel 9227:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 9228: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  9229: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 9230: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   9231: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   9232: 			$env{'request.course.id'});
                   9233: 	   }
1.54      www      9234:            return '';
                   9235:        }
1.53      www      9236:    }
                   9237: 
                   9238: # Resource preferences
                   9239: 
                   9240:    if ($thisallowed=~/R/) {
1.620     albertel 9241:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 9242:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  9243: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 9244: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   9245: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   9246: 	   }
                   9247: 	   return '';
1.54      www      9248:        }
1.53      www      9249:    }
1.30      www      9250: 
1.1461    raeburn  9251: # Restricted for deeplinked session?
                   9252: 
                   9253:     if ($env{'request.deeplink.login'}) {
                   9254:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   9255:             if (!$symb) { $symb=&symbread($uri,1); }
                   9256:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   9257:                 return '';
                   9258:             }
                   9259:         }
                   9260:     }
                   9261: 
1.246     www      9262: # Restricted by state or randomout?
1.30      www      9263: 
1.52      www      9264:    if ($thisallowed=~/X/) {
1.620     albertel 9265:       if ($env{'acc.randomout'}) {
1.579     albertel 9266: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 9267:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      9268:             return ''; 
                   9269:          }
1.247     www      9270:       }
                   9271:       if (&condval($statecond)) {
1.52      www      9272: 	 return '2';
                   9273:       } else {
                   9274:          return '';
                   9275:       }
                   9276:    }
1.30      www      9277: 
1.766     albertel 9278:     if ($thisallowed eq 'A') {
                   9279: 	return 'A';
1.814     raeburn  9280:     } elsif ($thisallowed eq 'B') {
                   9281:         return 'B';
1.1402    raeburn  9282:     } elsif ($thisallowed eq 'D') {
                   9283:         return 'D';
1.766     albertel 9284:     }
1.52      www      9285:    return 'F';
1.232     www      9286: }
1.1162    raeburn  9287: 
1.1192    raeburn  9288: # ------------------------------------------- Check construction space access
                   9289: 
                   9290: sub constructaccess {
                   9291:     my ($url,$setpriv)=@_;
                   9292: 
                   9293: # We do not allow editing of previous versions of files
                   9294:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   9295: 
                   9296: # Get username and domain from URL
                   9297:     my ($ownername,$ownerdomain,$ownerhome);
                   9298: 
                   9299:     ($ownerdomain,$ownername) =
1.1325    raeburn  9300:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  9301: 
                   9302: # The URL does not really point to any authorspace, forget it
                   9303:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   9304: 
                   9305: # Now we need to see if the user has access to the authorspace of
                   9306: # $ownername at $ownerdomain
                   9307: 
                   9308:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   9309: # Real author for this?
                   9310:        $ownerhome = $env{'user.home'};
                   9311:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   9312:           return ($ownername,$ownerdomain,$ownerhome);
                   9313:        }
1.1506    raeburn  9314:     } elsif (&is_course($ownerdomain,$ownername)) {
                   9315: # Course Authoring Space?
1.1312    raeburn  9316:         if ($env{'request.course.id'}) {
                   9317:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   9318:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   9319:                 if (&allowed('mdc',$env{'request.course.id'})) {
1.1520    raeburn  9320:                     return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
                   9321:                     unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
                   9322:                         my %domdefs = &get_domain_defaults($ownerdomain);
                   9323:                         my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   9324:                         unless (($type eq 'community') || ($type eq 'placement')) {
                   9325:                             $type = 'unofficial';
                   9326:                             if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
                   9327:                                 $type = 'official';
                   9328:                             } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
                   9329:                                 $type = 'textbook';
                   9330:                             } else {
                   9331:                                 $type = 'unofficial';
                   9332:                             }
                   9333:                         }
                   9334:                         return if ($domdefs{$type.'crsauthor'} eq '0');
                   9335:                     }
1.1312    raeburn  9336:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   9337:                     return ($ownername,$ownerdomain,$ownerhome);
                   9338:                 }
                   9339:             }
                   9340:         }
1.1506    raeburn  9341:         return '';
                   9342:     } else {
                   9343: # Co-author for this?
                   9344:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   9345:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   9346:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   9347:             return ($ownername,$ownerdomain,$ownerhome);
                   9348:         }
1.1192    raeburn  9349:     }
                   9350: 
                   9351: # We don't have any access right now. If we are not possibly going to do anything about this,
                   9352: # we might as well leave
                   9353:    unless ($setpriv) { return ''; }
                   9354: 
                   9355: # Backdoor access?
                   9356:     my $allowed=&allowed('eco',$ownerdomain);
                   9357: # Nope
                   9358:     unless ($allowed) { return ''; }
                   9359: # Looks like we may have access, but could be locked by the owner of the construction space
                   9360:     if ($allowed eq 'U') {
                   9361:         my %blocked=&get('environment',['domcoord.author'],
                   9362:                          $ownerdomain,$ownername);
                   9363: # Is blocked by owner
                   9364:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   9365:     }
                   9366:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   9367: # Grant temporary access
                   9368:         my $then=$env{'user.login.time'};
1.1209    raeburn  9369:         my $update=$env{'user.update.time'};
1.1192    raeburn  9370:         if (!$update) { $update = $then; }
                   9371:         my $refresh=$env{'user.refresh.time'};
                   9372:         if (!$refresh) { $refresh = $update; }
                   9373:         my $now = time;
                   9374:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   9375:                            $now,'ca','constructaccess');
                   9376:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   9377:         return($ownername,$ownerdomain,$ownerhome);
                   9378:     }
                   9379: # No business here
                   9380:     return '';
                   9381: }
                   9382: 
1.1282    raeburn  9383: # ----------------------------------------------------------- Content Blocking
                   9384: 
                   9385: {
                   9386: # Caches for faster Course Contents display where content blocking
                   9387: # is in operation (i.e., interval param set) for timed quiz.
                   9388: #
                   9389: # User for whom data are being temporarily cached.
                   9390: my $cacheduser='';
1.1424    raeburn  9391: # Course for which data are being temporarily cached.
                   9392: my $cachedcid='';
1.1282    raeburn  9393: # Cached blockers for this user (a hash of blocking items). 
                   9394: my %cachedblockers=();
                   9395: # When the data were last cached.
                   9396: my $cachedlast='';
                   9397: 
                   9398: sub load_all_blockers {
1.1427    raeburn  9399:     my ($uname,$udom)=@_;
1.1282    raeburn  9400:     if (($uname ne '') && ($udom ne '')) { 
                   9401:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  9402:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  9403:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  9404:             return;
                   9405:         }
                   9406:     }
                   9407:     $cachedlast=time;
                   9408:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  9409:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  9410:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  9411:     return;
1.1282    raeburn  9412: }
                   9413: 
1.1162    raeburn  9414: sub get_comm_blocks {
                   9415:     my ($cdom,$cnum) = @_;
                   9416:     if ($cdom eq '' || $cnum eq '') {
                   9417:         return unless ($env{'request.course.id'});
                   9418:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9419:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9420:     }
                   9421:     my %commblocks;
                   9422:     my $hashid=$cdom.'_'.$cnum;
                   9423:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   9424:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   9425:         %commblocks = %{$blocksref};
                   9426:     } else {
1.1494    raeburn  9427:         %commblocks = &dump('comm_block',$cdom,$cnum);
1.1162    raeburn  9428:         my $cachetime = 600;
                   9429:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   9430:     }
                   9431:     return %commblocks;
                   9432: }
                   9433: 
1.1282    raeburn  9434: sub get_commblock_resources {
                   9435:     my ($blocks) = @_;
                   9436:     my %blockers = ();
                   9437:     return %blockers unless ($env{'request.course.id'});
1.1470    raeburn  9438:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9439:     if ($env{'request.course.sec'}) {
                   9440:         $courseurl .= '/'.$env{'request.course.sec'};
                   9441:     }
                   9442:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  9443:     my %commblocks;
                   9444:     if (ref($blocks) eq 'HASH') {
                   9445:         %commblocks = %{$blocks};
                   9446:     } else {
                   9447:         %commblocks = &get_comm_blocks();
                   9448:     }
1.1282    raeburn  9449:     return %blockers unless (keys(%commblocks) > 0); 
                   9450:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9451:     return %blockers unless (ref($navmap));
1.1162    raeburn  9452:     my $now = time;
                   9453:     foreach my $block (keys(%commblocks)) {
                   9454:         if ($block =~ /^(\d+)____(\d+)$/) {
                   9455:             my ($start,$end) = ($1,$2);
                   9456:             if ($start <= $now && $end >= $now) {
                   9457:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9458:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   9459:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  9460:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9461:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  9462:                             }
                   9463:                         }
                   9464:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  9465:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9466:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  9467:                             }
                   9468:                         }
                   9469:                     }
                   9470:                 }
                   9471:             }
                   9472:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   9473:             my $item = $1;
                   9474:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9475:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471    raeburn  9476:                     my (@interval,$mapname);
1.1282    raeburn  9477:                     my $type = 'map';
                   9478:                     if ($item eq 'course') {
                   9479:                         $type = 'course';
                   9480:                         @interval=&EXT("resource.0.interval");
                   9481:                     } else {
                   9482:                         if ($item =~ /___\d+___/) {
                   9483:                             $type = 'resource';
                   9484:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  9485:                         } else {
1.1471    raeburn  9486:                             $mapname = &deversion($item);
                   9487:                             if (ref($navmap)) {
                   9488:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9489:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9490:                             }
                   9491:                         }
1.1282    raeburn  9492:                     }
1.1310    raeburn  9493:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  9494:                         my $timelimit = $1; 
1.1282    raeburn  9495:                         my $first_access;
                   9496:                         if ($type eq 'resource') {
                   9497:                             $first_access=&get_first_access($interval[1],$item);
                   9498:                         } elsif ($type eq 'map') {
                   9499:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9500:                         } else {
                   9501:                             $first_access=&get_first_access($interval[1]);
                   9502:                         }
                   9503:                         if ($first_access) {
1.1292    raeburn  9504:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  9505:                             if ($timesup > $now) {
                   9506:                                 my $activeblock;
1.1471    raeburn  9507:                                 if ($type eq 'resource') {
                   9508:                                     if (ref($navmap)) {
                   9509:                                         my $res = $navmap->getBySymb($item);
                   9510:                                         if ($res->answerable()) {
                   9511:                                             $activeblock = 1;
                   9512:                                         }
                   9513:                                     }
                   9514:                                 } elsif ($type eq 'map') {
                   9515:                                     my $mapsymb = &symbread($mapname,1);
                   9516:                                     if (($mapsymb) && (ref($navmap))) {
                   9517:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9518:                                         if (ref($mapres)) {
                   9519:                                             my $first = $mapres->map_start();
                   9520:                                             my $finish = $mapres->map_finish();
                   9521:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9522:                                             if (ref($it)) {
                   9523:                                                 my $res;
                   9524:                                                 while ($res = $it->next(undef,1)) {
                   9525:                                                     next unless (ref($res));
                   9526:                                                     my $symb = $res->symb();
                   9527:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9528:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9529:                                                     if ($interval[1] eq 'map') {
                   9530:                                                         if ($res->answerable()) {
                   9531:                                                             $activeblock = 1;
                   9532:                                                             last;
                   9533:                                                         }
                   9534:                                                     }
                   9535:                                                 }
                   9536:                                             }
                   9537:                                         }
1.1282    raeburn  9538:                                     }
                   9539:                                 }
                   9540:                                 if ($activeblock) {
                   9541:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9542:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9543:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9544:                                          }
                   9545:                                     }
                   9546:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9547:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9548:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9549:                                         }
1.1162    raeburn  9550:                                     }
                   9551:                                 }
                   9552:                             }
                   9553:                         }
                   9554:                     }
                   9555:                 }
                   9556:             }
                   9557:         }
                   9558:     }
1.1282    raeburn  9559:     return %blockers;
1.1162    raeburn  9560: }
                   9561: 
1.1282    raeburn  9562: sub has_comm_blocking {
1.1427    raeburn  9563:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  9564:     my @blockers;
                   9565:     return unless ($env{'request.course.id'});
                   9566:     return unless ($priv eq 'bre');
                   9567:     return if ($env{'request.state'} eq 'construct');
1.1470    raeburn  9568:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9569:     if ($env{'request.course.sec'}) {
                   9570:         $courseurl .= '/'.$env{'request.course.sec'};
                   9571:     }
                   9572:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427    raeburn  9573:     my %blockinfo;
                   9574:     if (ref($blocks) eq 'HASH') {
                   9575:         %blockinfo = &get_commblock_resources($blocks);
                   9576:     } else {
                   9577:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9578:         %blockinfo = %cachedblockers;
                   9579:     }
                   9580:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  9581:     my (%possibles,@symbs);
                   9582:     if (!$symb) {
1.1427    raeburn  9583:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9584:     }
1.1282    raeburn  9585:     if ($symb) {
                   9586:         @symbs = ($symb);
                   9587:     } elsif (keys(%possibles)) { 
                   9588:         @symbs = keys(%possibles);
                   9589:     }
                   9590:     my $noblock;
                   9591:     foreach my $symb (@symbs) {
                   9592:         last if ($noblock);
                   9593:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  9594:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  9595:             if ($block =~ /^firstaccess____(.+)$/) {
                   9596:                 my $item = $1;
1.1424    raeburn  9597:                 unless ($blocked) {
                   9598:                     if (($item eq $map) || ($item eq $symb)) {
                   9599:                         $noblock = 1;
                   9600:                         last;
                   9601:                     }
1.1282    raeburn  9602:                 }
                   9603:             }
1.1427    raeburn  9604:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9605:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9606:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  9607:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9608:                             push(@blockers,$block);
                   9609:                         }
                   9610:                     }
                   9611:                 }
1.1427    raeburn  9612:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9613:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  9614:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9615:                             push(@blockers,$block);
                   9616:                         }
1.1282    raeburn  9617:                     }
                   9618:                 }
1.1162    raeburn  9619:             }
                   9620:         }
                   9621:     }
1.1424    raeburn  9622:     unless ($noblock) { 
                   9623:         return @blockers;
                   9624:     }
                   9625:     return;
1.1282    raeburn  9626: }
1.1162    raeburn  9627: }
                   9628: 
1.1402    raeburn  9629: sub deeplink_check {
                   9630:     my ($priv,$symb,$uri) = @_;
                   9631:     return unless ($env{'request.course.id'});
                   9632:     return unless ($priv eq 'bre');
                   9633:     return if ($env{'request.state'} eq 'construct');
                   9634:     return if ($env{'request.role.adv'});
                   9635:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9636:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9637:     my (%possibles,@symbs);
                   9638:     if (!$symb) {
                   9639:         $symb = &symbread($uri,1,1,1,\%possibles);
                   9640:     }
                   9641:     if ($symb) {
                   9642:         @symbs = ($symb);
                   9643:     } elsif (keys(%possibles)) {
                   9644:         @symbs = keys(%possibles);
                   9645:     }
                   9646: 
1.1461    raeburn  9647:     my ($deeplink_symb,$allow);
                   9648:     if ($env{'request.deeplink.login'}) {
                   9649:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402    raeburn  9650:     }
                   9651:     foreach my $symb (@symbs) {
                   9652:         last if ($allow);
                   9653:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9654:         if ($deeplink eq '') {
                   9655:             $allow = 1;
                   9656:         } else {
1.1463    raeburn  9657:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9658:             if ($state ne 'only') {
1.1402    raeburn  9659:                 $allow = 1;
1.1463    raeburn  9660:             } else {
                   9661:                 my $check_deeplink_entry;
                   9662:                 if ($protect ne 'none') {
                   9663:                     my ($acctype,$item) = split(/:/,$protect);
                   9664:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9665:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9666:                             $check_deeplink_entry = 1
                   9667:                         }
                   9668:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9669:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9670:                             $check_deeplink_entry = 1;
                   9671:                         }
                   9672:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9673:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9674:                             $check_deeplink_entry = 1;
                   9675:                         }
                   9676:                     }
                   9677:                 }
                   9678:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402    raeburn  9679:                     if ($scope eq 'res') {
1.1461    raeburn  9680:                         if ($symb eq $deeplink_symb) {
1.1402    raeburn  9681:                             $allow = 1;
                   9682:                         }
1.1459    raeburn  9683:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463    raeburn  9684:                         my ($map_from_symb,$map_from_login);
1.1461    raeburn  9685:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9686:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9687:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9688:                         } else {
                   9689:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9690:                         }
1.1459    raeburn  9691:                         if (($map_from_symb) && ($map_from_login)) {
                   9692:                             if ($map_from_symb eq $map_from_login) {
                   9693:                                 $allow = 1;
                   9694:                             } elsif ($scope eq 'rec') {
                   9695:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9696:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9697:                                     $allow = 1;
                   9698:                                 }
                   9699:                             }
                   9700:                         }
1.1402    raeburn  9701:                     }
                   9702:                 }
                   9703:             }
                   9704:         }
                   9705:     }
                   9706:     return if ($allow);
                   9707:     return 1;
                   9708: }
                   9709: 
1.1282    raeburn  9710: # -------------------------------- Deversion and split uri into path an filename   
                   9711: 
1.1133    foxr     9712: #
1.1282    raeburn  9713: #   Removes the version from a URI and
1.1133    foxr     9714: #   splits it in to its filename and path to the filename.
                   9715: #   Seems like File::Basename could have done this more clearly.
                   9716: #   Parameters:
                   9717: #      $uri   - input URI
                   9718: #   Returns:
                   9719: #     Two element list consisting of 
                   9720: #     $pathname  - the URI up to and excluding the trailing /
                   9721: #     $filename  - The part of the URI following the last /
                   9722: #  NOTE:
                   9723: #    Another realization of this is simply:
                   9724: #    use File::Basename;
                   9725: #    ...
                   9726: #    $uri = shift;
                   9727: #    $filename = basename($uri);
                   9728: #    $path     = dirname($uri);
                   9729: #    return ($filename, $path);
                   9730: #
                   9731: #     The implementation below is probably faster however.
                   9732: #
1.710     albertel 9733: sub split_uri_for_cond {
                   9734:     my $uri=&deversion(&declutter(shift));
                   9735:     my @uriparts=split(/\//,$uri);
                   9736:     my $filename=pop(@uriparts);
                   9737:     my $pathname=join('/',@uriparts);
                   9738:     return ($pathname,$filename);
                   9739: }
1.232     www      9740: # --------------------------------------------------- Is a resource on the map?
                   9741: 
                   9742: sub is_on_map {
1.710     albertel 9743:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9744:     #Trying to find the conditional for the file
1.620     albertel 9745:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9746: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9747:     if ($match) {
1.289     bowersj2 9748: 	return (1,$1);
                   9749:     } else {
1.434     www      9750: 	return (0,0);
1.289     bowersj2 9751:     }
1.12      www      9752: }
                   9753: 
1.427     www      9754: # --------------------------------------------------------- Get symb from alias
                   9755: 
                   9756: sub get_symb_from_alias {
                   9757:     my $symb=shift;
                   9758:     my ($map,$resid,$url)=&decode_symb($symb);
                   9759: # Already is a symb
                   9760:     if ($url) { return $symb; }
                   9761: # Must be an alias
                   9762:     my $aliassymb='';
                   9763:     my %bighash;
1.620     albertel 9764:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9765:                             &GDBM_READER(),0640)) {
                   9766:         my $rid=$bighash{'mapalias_'.$symb};
                   9767: 	if ($rid) {
                   9768: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9769: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9770: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9771: 	}
                   9772:         untie %bighash;
                   9773:     }
                   9774:     return $aliassymb;
                   9775: }
                   9776: 
1.12      www      9777: # ----------------------------------------------------------------- Define Role
                   9778: 
                   9779: sub definerole {
                   9780:   if (allowed('mcr','/')) {
1.1326    raeburn  9781:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9782:     foreach my $role (split(':',$sysrole)) {
                   9783: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9784:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9785:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9786: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9787:                return "refused:s:$crole&$cqual"; 
                   9788:             }
                   9789:         }
1.191     harris41 9790:     }
1.800     albertel 9791:     foreach my $role (split(':',$domrole)) {
                   9792: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9793:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9794:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9795: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9796:                return "refused:d:$crole&$cqual"; 
                   9797:             }
                   9798:         }
1.191     harris41 9799:     }
1.800     albertel 9800:     foreach my $role (split(':',$courole)) {
                   9801: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9802:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9803:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9804: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9805:                return "refused:c:$crole&$cqual"; 
                   9806:             }
                   9807:         }
1.191     harris41 9808:     }
1.1326    raeburn  9809:     my $uhome;
                   9810:     if (($uname ne '') && ($udom ne '')) {
                   9811:         $uhome = &homeserver($uname,$udom);
                   9812:         return $uhome if ($uhome eq 'no_host');
                   9813:     } else {
                   9814:         $uname = $env{'user.name'};
                   9815:         $udom = $env{'user.domain'};
                   9816:         $uhome = $env{'user.home'};
                   9817:     }
1.620     albertel 9818:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9819:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9820:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9821:     return reply($command,$uhome);
1.12      www      9822:   } else {
                   9823:     return 'refused';
                   9824:   }
1.105     harris41 9825: }
                   9826: 
                   9827: # ---------------- Make a metadata query against the network of library servers
                   9828: 
                   9829: sub metadata_query {
1.1237    raeburn  9830:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9831:     my %rhash;
1.845     albertel 9832:     my %libserv = &all_library();
1.244     matthew  9833:     my @server_list = (defined($server_array) ? @$server_array
                   9834:                                               : keys(%libserv) );
                   9835:     for my $server (@server_list) {
1.1237    raeburn  9836:         my $domains = ''; 
                   9837:         if (ref($domains_hash) eq 'HASH') {
                   9838:             $domains = $domains_hash->{$server}; 
                   9839:         }
1.118     harris41 9840: 	unless ($custom or $customshow) {
1.1237    raeburn  9841: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9842: 	    $rhash{$server}=$reply;
                   9843: 	}
                   9844: 	else {
                   9845: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9846: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9847: 			     $server);
                   9848: 	    $rhash{$server}=$reply;
                   9849: 	}
1.112     harris41 9850:     }
1.118     harris41 9851:     return \%rhash;
1.240     www      9852: }
                   9853: 
                   9854: # ----------------------------------------- Send log queries and wait for reply
                   9855: 
                   9856: sub log_query {
                   9857:     my ($uname,$udom,$query,%filters)=@_;
                   9858:     my $uhome=&homeserver($uname,$udom);
                   9859:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9860:     my $uhost=&hostname($uhome);
1.800     albertel 9861:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9862:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9863:                        $uhome);
1.479     albertel 9864:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9865:     return get_query_reply($queryid);
                   9866: }
                   9867: 
1.818     raeburn  9868: # -------------------------- Update MySQL table for portfolio file
                   9869: 
                   9870: sub update_portfolio_table {
1.821     raeburn  9871:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9872:     if ($group ne '') {
                   9873:         $file_name =~s /^\Q$group\E//;
                   9874:     }
1.818     raeburn  9875:     my $homeserver = &homeserver($uname,$udom);
                   9876:     my $queryid=
1.821     raeburn  9877:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9878:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9879:     my $reply = &get_query_reply($queryid);
                   9880:     return $reply;
                   9881: }
                   9882: 
1.899     raeburn  9883: # -------------------------- Update MySQL allusers table
                   9884: 
                   9885: sub update_allusers_table {
                   9886:     my ($uname,$udom,$names) = @_;
                   9887:     my $homeserver = &homeserver($uname,$udom);
                   9888:     my $queryid=
                   9889:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9890:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9891:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9892:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9893:                'generation='.&escape($names->{'generation'}).'%%'.
                   9894:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9895:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9896:     return;
1.899     raeburn  9897: }
                   9898: 
1.508     raeburn  9899: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9900: 
                   9901: sub fetch_enrollment_query {
1.511     raeburn  9902:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9903:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9904:     my $maxtries = 1;
1.508     raeburn  9905:     if ($context eq 'automated') {
                   9906:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9907:         $sleep = 2;
                   9908:         $loopmax = 100;
1.547     raeburn  9909:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9910:     } else {
                   9911:         $homeserver = &homeserver($cnum,$dom);
                   9912:     }
1.838     albertel 9913:     my $host=&hostname($homeserver);
1.506     raeburn  9914:     my $cmd = '';
1.1000    raeburn  9915:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9916:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9917:     }
                   9918:     $cmd =~ s/%%$//;
                   9919:     $cmd = &escape($cmd);
                   9920:     my $query = 'fetchenrollment';
1.620     albertel 9921:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9922:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9923:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9924:         return 'error: '.$queryid;
                   9925:     }
1.1317    raeburn  9926:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9927:     my $tries = 1;
                   9928:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9929:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9930:         $tries ++;
                   9931:     }
1.526     raeburn  9932:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9933:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9934:     } else {
1.901     albertel 9935:         my @responses = split(/:/,$reply);
1.1322    raeburn  9936:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9937:             foreach my $line (@responses) {
                   9938:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9939:                 $$replyref{$key} = $value;
                   9940:             }
                   9941:         } else {
1.1117    foxr     9942:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9943:             foreach my $line (@responses) {
                   9944:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9945:                 $$replyref{$key} = $value;
                   9946:                 if ($value > 0) {
1.800     albertel 9947:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9948:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9949:                         my $destname = $pathname.'/'.$filename;
                   9950:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9951:                         if ($xml_classlist =~ /^error/) {
                   9952:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9953:                         } else {
1.1359    raeburn  9954:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9955:                                 print FILE &unescape($xml_classlist);
                   9956:                                 close(FILE);
1.526     raeburn  9957:                             } else {
                   9958:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9959:                             }
                   9960:                         }
                   9961:                     }
                   9962:                 }
                   9963:             }
                   9964:         }
                   9965:         return 'ok';
                   9966:     }
                   9967:     return 'error';
                   9968: }
                   9969: 
1.242     www      9970: sub get_query_reply {
1.1471    raeburn  9971:     my ($queryid,$sleep,$loopmax) = @_;
1.1317    raeburn  9972:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9973:         $sleep = 0.2;
                   9974:     }
                   9975:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9976:         $loopmax = 100;
                   9977:     }
1.1117    foxr     9978:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9979:     my $reply='';
1.1317    raeburn  9980:     for (1..$loopmax) {
                   9981: 	sleep($sleep);
1.240     www      9982:         if (-e $replyfile.'.end') {
1.1359    raeburn  9983: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9984: 		$reply = join('',<$fh>);
                   9985: 		close($fh);
1.240     www      9986: 	   } else { return 'error: reply_file_error'; }
1.242     www      9987:            return &unescape($reply);
                   9988: 	}
1.240     www      9989:     }
1.242     www      9990:     return 'timeout:'.$queryid;
1.240     www      9991: }
                   9992: 
                   9993: sub courselog_query {
1.241     www      9994: #
                   9995: # possible filters:
                   9996: # url: url or symb
                   9997: # username
                   9998: # domain
                   9999: # action: view, submit, grade
                   10000: # start: timestamp
                   10001: # end: timestamp
                   10002: #
1.240     www      10003:     my (%filters)=@_;
1.620     albertel 10004:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      10005:     if ($filters{'url'}) {
                   10006: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   10007:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   10008:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   10009:     }
1.620     albertel 10010:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10011:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      10012:     return &log_query($cname,$cdom,'courselog',%filters);
                   10013: }
                   10014: 
                   10015: sub userlog_query {
1.858     raeburn  10016: #
                   10017: # possible filters:
                   10018: # action: log check role
                   10019: # start: timestamp
                   10020: # end: timestamp
                   10021: #
1.240     www      10022:     my ($uname,$udom,%filters)=@_;
                   10023:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      10024: }
                   10025: 
1.506     raeburn  10026: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   10027: 
                   10028: sub auto_run {
1.508     raeburn  10029:     my ($cnum,$cdom) = @_;
1.876     raeburn  10030:     my $response = 0;
                   10031:     my $settings;
                   10032:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   10033:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   10034:         $settings = $domconfig{'autoenroll'};
                   10035:         if ($settings->{'run'} eq '1') {
                   10036:             $response = 1;
                   10037:         }
                   10038:     } else {
1.934     raeburn  10039:         my $homeserver;
                   10040:         if (&is_course($cdom,$cnum)) {
                   10041:             $homeserver = &homeserver($cnum,$cdom);
                   10042:         } else {
                   10043:             $homeserver = &domain($cdom,'primary');
                   10044:         }
                   10045:         if ($homeserver ne 'no_host') {
                   10046:             $response = &reply('autorun:'.$cdom,$homeserver);
                   10047:         }
1.876     raeburn  10048:     }
1.506     raeburn  10049:     return $response;
                   10050: }
1.776     albertel 10051: 
1.506     raeburn  10052: sub auto_get_sections {
1.508     raeburn  10053:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  10054:     my $homeserver;
                   10055:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   10056:         $homeserver = &homeserver($cnum,$cdom);
                   10057:     }
                   10058:     if (!defined($homeserver)) { 
                   10059:         if ($cdom =~ /^$match_domain$/) {
                   10060:             $homeserver = &domain($cdom,'primary');
                   10061:         }
                   10062:     }
                   10063:     my @secs;
                   10064:     if (defined($homeserver)) {
                   10065:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   10066:         unless ($response eq 'refused') {
                   10067:             @secs = split(/:/,$response);
                   10068:         }
1.506     raeburn  10069:     }
                   10070:     return @secs;
                   10071: }
1.776     albertel 10072: 
1.506     raeburn  10073: sub auto_new_course {
1.1099    raeburn  10074:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  10075:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  10076:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  10077:     return $response;
                   10078: }
1.776     albertel 10079: 
1.506     raeburn  10080: sub auto_validate_courseID {
1.508     raeburn  10081:     my ($cnum,$cdom,$inst_course_id) = @_;
                   10082:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  10083:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  10084:     return $response;
                   10085: }
1.776     albertel 10086: 
1.1007    raeburn  10087: sub auto_validate_instcode {
1.1020    raeburn  10088:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  10089:     my ($homeserver,$response);
                   10090:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   10091:         $homeserver = &homeserver($cnum,$cdom);
                   10092:     }
                   10093:     if (!defined($homeserver)) {
                   10094:         if ($cdom =~ /^$match_domain$/) {
                   10095:             $homeserver = &domain($cdom,'primary');
                   10096:         }
                   10097:     }
1.1065    raeburn  10098:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   10099:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  10100:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   10101:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  10102: }
                   10103: 
1.1444    raeburn  10104: sub auto_validate_inst_crosslist {
                   10105:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   10106:     my ($homeserver,$response);
                   10107:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   10108:         $homeserver = &homeserver($cnum,$cdom);
                   10109:     }
                   10110:     if (!defined($homeserver)) {
                   10111:         if ($cdom =~ /^$match_domain$/) {
                   10112:             $homeserver = &domain($cdom,'primary');
                   10113:         }
                   10114:     }
                   10115:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   10116:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   10117:                          &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445    raeburn  10118:                          &escape($coowner),$homeserver);
1.1444    raeburn  10119:     }
                   10120:     return $response;
                   10121: }
                   10122: 
1.506     raeburn  10123: sub auto_create_password {
1.873     raeburn  10124:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   10125:     my ($homeserver,$response);
1.506     raeburn  10126:     my $create_passwd = 0;
                   10127:     my $authchk = '';
1.873     raeburn  10128:     if ($udom =~ /^$match_domain$/) {
                   10129:         $homeserver = &domain($udom,'primary');
                   10130:     }
                   10131:     if ($homeserver eq '') {
                   10132:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   10133:             $homeserver = &homeserver($cnum,$cdom);
                   10134:         }
                   10135:     }
                   10136:     if ($homeserver eq '') {
                   10137:         $authchk = 'nodomain';
1.506     raeburn  10138:     } else {
1.873     raeburn  10139:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   10140:         if ($response eq 'refused') {
                   10141:             $authchk = 'refused';
                   10142:         } else {
1.901     albertel 10143:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  10144:         }
1.506     raeburn  10145:     }
                   10146:     return ($authparam,$create_passwd,$authchk);
                   10147: }
                   10148: 
1.706     raeburn  10149: sub auto_photo_permission {
                   10150:     my ($cnum,$cdom,$students) = @_;
                   10151:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 10152:     my ($outcome,$perm_reqd,$conditions) = 
                   10153: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 10154:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   10155: 	return (undef,undef);
                   10156:     }
1.706     raeburn  10157:     return ($outcome,$perm_reqd,$conditions);
                   10158: }
                   10159: 
                   10160: sub auto_checkphotos {
                   10161:     my ($uname,$udom,$pid) = @_;
                   10162:     my $homeserver = &homeserver($uname,$udom);
                   10163:     my ($result,$resulttype);
                   10164:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 10165: 				   &escape($uname).':'.&escape($pid),
                   10166: 				   $homeserver));
1.709     albertel 10167:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   10168: 	return (undef,undef);
                   10169:     }
1.706     raeburn  10170:     if ($outcome) {
                   10171:         ($result,$resulttype) = split(/:/,$outcome);
                   10172:     } 
                   10173:     return ($result,$resulttype);
                   10174: }
                   10175: 
                   10176: sub auto_photochoice {
                   10177:     my ($cnum,$cdom) = @_;
                   10178:     my $homeserver = &homeserver($cnum,$cdom);
                   10179:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 10180: 						       &escape($cdom),
                   10181: 						       $homeserver)));
1.709     albertel 10182:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   10183: 	return (undef,undef);
                   10184:     }
1.706     raeburn  10185:     return ($update,$comment);
                   10186: }
                   10187: 
                   10188: sub auto_photoupdate {
                   10189:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   10190:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 10191:     my $host=&hostname($homeserver);
1.706     raeburn  10192:     my $cmd = '';
                   10193:     my $maxtries = 1;
1.800     albertel 10194:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   10195:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  10196:     }
                   10197:     $cmd =~ s/%%$//;
                   10198:     $cmd = &escape($cmd);
                   10199:     my $query = 'institutionalphotos';
                   10200:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   10201:     unless ($queryid=~/^\Q$host\E\_/) {
                   10202:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   10203:         return 'error: '.$queryid;
                   10204:     }
                   10205:     my $reply = &get_query_reply($queryid);
                   10206:     my $tries = 1;
                   10207:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   10208:         $reply = &get_query_reply($queryid);
                   10209:         $tries ++;
                   10210:     }
                   10211:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   10212:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   10213:     } else {
                   10214:         my @responses = split(/:/,$reply);
                   10215:         my $outcome = shift(@responses); 
                   10216:         foreach my $item (@responses) {
                   10217:             my ($key,$value) = split(/=/,$item);
                   10218:             $$photo{$key} = $value;
                   10219:         }
                   10220:         return $outcome;
                   10221:     }
                   10222:     return 'error';
                   10223: }
                   10224: 
1.521     raeburn  10225: sub auto_instcode_format {
1.793     albertel 10226:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   10227: 	$cat_order) = @_;
1.521     raeburn  10228:     my $courses = '';
1.772     raeburn  10229:     my @homeservers;
1.521     raeburn  10230:     if ($caller eq 'global') {
1.841     albertel 10231: 	my %servers = &get_servers($codedom,'library');
                   10232: 	foreach my $tryserver (keys(%servers)) {
                   10233: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10234: 		push(@homeservers,$tryserver);
                   10235: 	    }
1.584     raeburn  10236:         }
1.1022    raeburn  10237:     } elsif ($caller eq 'requests') {
                   10238:         if ($codedom =~ /^$match_domain$/) {
                   10239:             my $chome = &domain($codedom,'primary');
                   10240:             unless ($chome eq 'no_host') {
                   10241:                 push(@homeservers,$chome);
                   10242:             }
                   10243:         }
1.521     raeburn  10244:     } else {
1.772     raeburn  10245:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  10246:     }
1.793     albertel 10247:     foreach my $code (keys(%{$instcodes})) {
                   10248:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  10249:     }
                   10250:     chop($courses);
1.772     raeburn  10251:     my $ok_response = 0;
                   10252:     my $response;
                   10253:     while (@homeservers > 0 && $ok_response == 0) {
                   10254:         my $server = shift(@homeservers); 
                   10255:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   10256:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   10257:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 10258: 		split(/:/,$response);
1.772     raeburn  10259:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   10260:             push(@{$codetitles},&str2array($codetitles_str));
                   10261:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   10262:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   10263:             $ok_response = 1;
                   10264:         }
                   10265:     }
                   10266:     if ($ok_response) {
1.521     raeburn  10267:         return 'ok';
1.772     raeburn  10268:     } else {
                   10269:         return $response;
1.521     raeburn  10270:     }
                   10271: }
                   10272: 
1.792     raeburn  10273: sub auto_instcode_defaults {
                   10274:     my ($domain,$returnhash,$code_order) = @_;
                   10275:     my @homeservers;
1.841     albertel 10276: 
                   10277:     my %servers = &get_servers($domain,'library');
                   10278:     foreach my $tryserver (keys(%servers)) {
                   10279: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10280: 	    push(@homeservers,$tryserver);
                   10281: 	}
1.792     raeburn  10282:     }
1.841     albertel 10283: 
1.792     raeburn  10284:     my $response;
1.841     albertel 10285:     foreach my $server (@homeservers) {
1.792     raeburn  10286:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 10287:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   10288: 	
                   10289: 	foreach my $pair (split(/\&/,$response)) {
                   10290: 	    my ($name,$value)=split(/\=/,$pair);
                   10291: 	    if ($name eq 'code_order') {
                   10292: 		@{$code_order} = split(/\&/,&unescape($value));
                   10293: 	    } else {
                   10294: 		$returnhash->{&unescape($name)}=&unescape($value);
                   10295: 	    }
                   10296: 	}
                   10297: 	return 'ok';
1.792     raeburn  10298:     }
1.841     albertel 10299: 
                   10300:     return $response;
1.1003    raeburn  10301: }
                   10302: 
                   10303: sub auto_possible_instcodes {
1.1007    raeburn  10304:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   10305:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   10306:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10307:         return;
                   10308:     }
1.1003    raeburn  10309:     my (@homeservers,$uhome);
                   10310:     if (defined(&domain($domain,'primary'))) {
                   10311:         $uhome=&domain($domain,'primary');
                   10312:         push(@homeservers,&domain($domain,'primary'));
                   10313:     } else {
                   10314:         my %servers = &get_servers($domain,'library');
                   10315:         foreach my $tryserver (keys(%servers)) {
                   10316:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10317:                 push(@homeservers,$tryserver);
                   10318:             }
                   10319:         }
                   10320:     }
                   10321:     my $response;
                   10322:     foreach my $server (@homeservers) {
                   10323:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   10324:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  10325:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   10326:             split(':',$response);
                   10327:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   10328:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  10329:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  10330:             my ($name,$value)=split('=',$item);
                   10331:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  10332:         }
                   10333:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  10334:             my ($name,$value)=split('=',$item);
                   10335:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  10336:         }
                   10337:         return 'ok';
                   10338:     }
                   10339:     return $response;
                   10340: }
1.792     raeburn  10341: 
1.1010    raeburn  10342: sub auto_courserequest_checks {
                   10343:     my ($dom) = @_;
1.1020    raeburn  10344:     my ($homeserver,%validations);
                   10345:     if ($dom =~ /^$match_domain$/) {
                   10346:         $homeserver = &domain($dom,'primary');
                   10347:     }
                   10348:     unless ($homeserver eq 'no_host') {
                   10349:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   10350:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10351:             my @items = split(/&/,$response);
                   10352:             foreach my $item (@items) {
                   10353:                 my ($key,$value) = split('=',$item);
                   10354:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   10355:             }
                   10356:         }
                   10357:     }
1.1010    raeburn  10358:     return %validations; 
                   10359: }
                   10360: 
1.1020    raeburn  10361: sub auto_courserequest_validation {
1.1255    raeburn  10362:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  10363:     my ($homeserver,$response);
                   10364:     if ($dom =~ /^$match_domain$/) {
                   10365:         $homeserver = &domain($dom,'primary');
                   10366:     }
1.1255    raeburn  10367:     unless ($homeserver eq 'no_host') {
                   10368:         my $customdata;
                   10369:         if (ref($custominfo) eq 'HASH') {
                   10370:             $customdata = &freeze_escape($custominfo);
                   10371:         }
1.1020    raeburn  10372:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  10373:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  10374:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   10375:                                     $customdata,$homeserver));
1.1020    raeburn  10376:     }
                   10377:     return $response;
                   10378: }
                   10379: 
1.777     albertel 10380: sub auto_validate_class_sec {
1.918     raeburn  10381:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  10382:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  10383:     my $ownerlist;
                   10384:     if (ref($owners) eq 'ARRAY') {
                   10385:         $ownerlist = join(',',@{$owners});
                   10386:     } else {
                   10387:         $ownerlist = $owners;
                   10388:     }
1.773     raeburn  10389:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  10390:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  10391:     return $response;
                   10392: }
                   10393: 
1.1460    raeburn  10394: sub auto_instsec_reformat {
                   10395:     my ($cdom,$action,$instsecref) = @_;
                   10396:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   10397:     my @homeservers;
                   10398:     if (defined(&domain($cdom,'primary'))) {
                   10399:         push(@homeservers,&domain($cdom,'primary'));
                   10400:     } else {
                   10401:         my %servers = &get_servers($cdom,'library');
                   10402:         foreach my $tryserver (keys(%servers)) {
                   10403:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10404:                 push(@homeservers,$tryserver);
                   10405:             }
                   10406:         }
                   10407:     }
                   10408:     my $response;
                   10409:     my %reformatted = %{$instsecref};
                   10410:     foreach my $server (@homeservers) {
                   10411:         if (ref($instsecref) eq 'HASH') {
                   10412:             my $info = &freeze_escape($instsecref);
                   10413:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   10414:                                 $action.':'.$info,$server);
1.1531    raeburn  10415:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_cmd)/);
1.1460    raeburn  10416:             my @items = split(/&/,$response);
                   10417:             foreach my $item (@items) {
                   10418:                 my ($key,$value) = split(/=/,$item);
                   10419:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   10420:             }
                   10421:         }
                   10422:     }
                   10423:     return %reformatted;
                   10424: }
                   10425: 
1.1367    raeburn  10426: sub auto_validate_instclasses {
                   10427:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   10428:     my ($homeserver,%validations);
                   10429:     $homeserver = &homeserver($cnum,$cdom);
                   10430:     unless ($homeserver eq 'no_host') {
                   10431:         my $ownerlist;
                   10432:         if (ref($owners) eq 'ARRAY') {
                   10433:             $ownerlist = join(',',@{$owners});
                   10434:         } else {
                   10435:             $ownerlist = $owners;
                   10436:         }
                   10437:         if (ref($classesref) eq 'HASH') {
                   10438:             my $classes = &freeze_escape($classesref);
                   10439:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   10440:                                 ':'.$cdom.':'.$classes,$homeserver);
                   10441:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10442:                 my @items = split(/&/,$response);
                   10443:                 foreach my $item (@items) {
                   10444:                     my ($key,$value) = split('=',$item);
                   10445:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   10446:                 }
                   10447:             }
                   10448:         }
                   10449:     }
                   10450:     return %validations;
                   10451: }
                   10452: 
1.1248    raeburn  10453: sub auto_crsreq_update {
                   10454:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  10455:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  10456:     my ($homeserver,%crsreqresponse);
                   10457:     if ($cdom =~ /^$match_domain$/) {
                   10458:         $homeserver = &domain($cdom,'primary');
                   10459:     }
                   10460:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10461:         my $info;
                   10462:         if (ref($inbound) eq 'HASH') {
                   10463:             $info = &freeze_escape($inbound);
                   10464:         }
                   10465:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   10466:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   10467:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  10468:                             &escape($title).':'.&escape($code).':'.
                   10469:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   10470:                             $homeserver);
1.1248    raeburn  10471:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10472:             my @items = split(/&/,$response);
                   10473:             foreach my $item (@items) {
                   10474:                 my ($key,$value) = split('=',$item);
                   10475:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   10476:             }
                   10477:         }
                   10478:     }
                   10479:     return \%crsreqresponse;
                   10480: }
                   10481: 
1.1305    raeburn  10482: sub auto_export_grades {
1.1309    raeburn  10483:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   10484:     my ($homeserver,%exportresponse);
                   10485:     if ($cdom =~ /^$match_domain$/) {
                   10486:         $homeserver = &domain($cdom,'primary');
                   10487:     }
                   10488:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10489:         my $info;
                   10490:         if (ref($inforef) eq 'HASH') {
                   10491:             $info = &freeze_escape($inforef);
                   10492:         }
                   10493:         if (ref($gradesref) eq 'HASH') {
                   10494:             my $grades = &freeze_escape($gradesref);
                   10495:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10496:                                 $info.':'.$grades,$homeserver);
1.1531    raeburn  10497:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_cmd)/) {
1.1309    raeburn  10498:                 my @items = split(/&/,$response);
                   10499:                 foreach my $item (@items) {
                   10500:                     my ($key,$value) = split('=',$item);
                   10501:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10502:                 }
                   10503:             }
                   10504:         }
                   10505:     }
                   10506:     return \%exportresponse;
1.1305    raeburn  10507: }
                   10508: 
1.1287    raeburn  10509: sub check_instcode_cloning {
                   10510:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10511:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10512:         return;
                   10513:     }
                   10514:     my $canclone;
                   10515:     if (@{$code_order} > 0) {
                   10516:         my $instcoderegexp ='^';
                   10517:         my @clonecodes = split(/\&/,$cloner);
                   10518:         foreach my $item (@{$code_order}) {
                   10519:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10520:                 foreach my $pair (@clonecodes) {
                   10521:                     my ($key,$val) = split(/\=/,$pair,2);
                   10522:                     $val = &unescape($val);
                   10523:                     if ($key eq $item) {
                   10524:                         $instcoderegexp .= '('.$val.')';
                   10525:                         last;
                   10526:                     }
                   10527:                 }
                   10528:             } else {
                   10529:                 $instcoderegexp .= $codedefaults->{$item};
                   10530:             }
                   10531:         }
                   10532:         $instcoderegexp .= '$';
                   10533:         my (@from,@to);
                   10534:         eval {
                   10535:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10536:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10537:         };
                   10538:         if ((@from > 0) && (@to > 0)) {
                   10539:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10540:             if (!@diffs) {
                   10541:                 $canclone = 1;
                   10542:             }
                   10543:         }
                   10544:     }
                   10545:     return $canclone;
                   10546: }
                   10547: 
                   10548: sub default_instcode_cloning {
                   10549:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10550:     my (%codedefaults,@code_order,$canclone);
                   10551:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10552:         %codedefaults = %{$codedefaultsref};
                   10553:         @code_order = @{$codeorderref};
                   10554:     } elsif ($clonedom) {
                   10555:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10556:     }
                   10557:     if (($domdefclone) && (@code_order)) {
                   10558:         my @clonecodes = split(/\+/,$domdefclone);
                   10559:         my $instcoderegexp ='^';
                   10560:         foreach my $item (@code_order) {
                   10561:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10562:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10563:             } else {
                   10564:                 $instcoderegexp .= $codedefaults{$item};
                   10565:             }
                   10566:         }
                   10567:         $instcoderegexp .= '$';
                   10568:         my (@from,@to);
                   10569:         eval {
                   10570:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10571:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10572:         };
                   10573:         if ((@from > 0) && (@to > 0)) {
                   10574:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10575:             if (!@diffs) {
                   10576:                 $canclone = 1;
                   10577:             }
                   10578:         }
                   10579:     }
                   10580:     return $canclone;
                   10581: }
                   10582: 
1.679     raeburn  10583: # ------------------------------------------------------- Course Group routines
                   10584: 
                   10585: sub get_coursegroups {
1.809     raeburn  10586:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10587:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10588: }
                   10589: 
1.679     raeburn  10590: sub modify_coursegroup {
                   10591:     my ($cdom,$cnum,$groupsettings) = @_;
                   10592:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10593: }
                   10594: 
1.809     raeburn  10595: sub toggle_coursegroup_status {
                   10596:     my ($cdom,$cnum,$group,$action) = @_;
                   10597:     my ($from_namespace,$to_namespace);
                   10598:     if ($action eq 'delete') {
                   10599:         $from_namespace = 'coursegroups';
                   10600:         $to_namespace = 'deleted_groups';
                   10601:     } else {
                   10602:         $from_namespace = 'deleted_groups';
                   10603:         $to_namespace = 'coursegroups';
                   10604:     }
                   10605:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10606:     if (my $tmp = &error(%curr_group)) {
                   10607:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10608:         return ('read error',$tmp);
                   10609:     } else {
                   10610:         my %savedsettings = %curr_group; 
1.809     raeburn  10611:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10612:         my $deloutcome;
                   10613:         if ($result eq 'ok') {
1.809     raeburn  10614:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10615:         } else {
                   10616:             return ('write error',$result);
                   10617:         }
                   10618:         if ($deloutcome eq 'ok') {
                   10619:             return 'ok';
                   10620:         } else {
                   10621:             return ('delete error',$deloutcome);
                   10622:         }
                   10623:     }
                   10624: }
                   10625: 
1.679     raeburn  10626: sub modify_group_roles {
1.1512    raeburn  10627:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
                   10628:         $othdomby,$requester) = @_;
1.679     raeburn  10629:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10630:     my $role = 'gr/'.&escape($userprivs);
                   10631:     my ($uname,$udom) = split(/:/,$user);
1.1512    raeburn  10632:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
                   10633:                              $othdomby,$requester);
1.684     raeburn  10634:     if ($result eq 'ok') {
                   10635:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10636:     }
1.679     raeburn  10637:     return $result;
                   10638: }
                   10639: 
                   10640: sub modify_coursegroup_membership {
                   10641:     my ($cdom,$cnum,$membership) = @_;
                   10642:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10643:     return $result;
                   10644: }
                   10645: 
1.682     raeburn  10646: sub get_active_groups {
                   10647:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10648:     my $now = time;
                   10649:     my %groups = ();
                   10650:     foreach my $key (keys(%env)) {
1.811     albertel 10651:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10652:             my ($start,$end) = split(/\./,$env{$key});
                   10653:             if (($end!=0) && ($end<$now)) { next; }
                   10654:             if (($start!=0) && ($start>$now)) { next; }
                   10655:             if ($1 eq $cdom && $2 eq $cnum) {
                   10656:                 $groups{$3} = $env{$key} ;
                   10657:             }
                   10658:         }
                   10659:     }
                   10660:     return %groups;
                   10661: }
                   10662: 
1.683     raeburn  10663: sub get_group_membership {
                   10664:     my ($cdom,$cnum,$group) = @_;
                   10665:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10666: }
                   10667: 
                   10668: sub get_users_groups {
                   10669:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10670:     my @usersgroups;
1.683     raeburn  10671:     my $cachetime=1800;
                   10672: 
                   10673:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10674:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10675:     if (defined($cached)) {
1.734     albertel 10676:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10677:     } else {  
                   10678:         $grouplist = '';
1.816     raeburn  10679:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10680:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10681:         my $access_end = $env{'course.'.$courseid.
                   10682:                               '.default_enrollment_end_date'};
                   10683:         my $now = time;
                   10684:         foreach my $key (keys(%roleshash)) {
                   10685:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10686:                 my $group = $1;
                   10687:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10688:                     my $start = $2;
                   10689:                     my $end = $1;
                   10690:                     if ($start == -1) { next; } # deleted from group
                   10691:                     if (($start!=0) && ($start>$now)) { next; }
                   10692:                     if (($end!=0) && ($end<$now)) {
                   10693:                         if ($access_end && $access_end < $now) {
                   10694:                             if ($access_end - $end < 86400) {
                   10695:                                 push(@usersgroups,$group);
1.733     raeburn  10696:                             }
                   10697:                         }
1.817     raeburn  10698:                         next;
1.733     raeburn  10699:                     }
1.817     raeburn  10700:                     push(@usersgroups,$group);
1.683     raeburn  10701:                 }
                   10702:             }
                   10703:         }
1.817     raeburn  10704:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10705:         $grouplist = join(':',@usersgroups);
                   10706:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10707:     }
1.733     raeburn  10708:     return @usersgroups;
1.683     raeburn  10709: }
                   10710: 
                   10711: sub devalidate_getgroups_cache {
                   10712:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10713:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10714: 
1.683     raeburn  10715:     my $hashid="$udom:$uname:$courseid";
                   10716:     &devalidate_cache_new('getgroups',$hashid);
                   10717: }
                   10718: 
1.12      www      10719: # ------------------------------------------------------------------ Plain Text
                   10720: 
                   10721: sub plaintext {
1.988     raeburn  10722:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10723:     if ($short =~ m{^cr/}) {
1.758     albertel 10724: 	return (split('/',$short))[-1];
                   10725:     }
1.742     raeburn  10726:     if (!defined($cid)) {
                   10727:         $cid = $env{'request.course.id'};
                   10728:     }
                   10729:     my %rolenames = (
1.1008    raeburn  10730:                       Course    => 'std',
                   10731:                       Community => 'alt1',
1.1305    raeburn  10732:                       Placement => 'std',
1.742     raeburn  10733:                     );
1.1037    raeburn  10734:     if ($cid ne '') {
                   10735:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10736:             unless ($forcedefault) {
                   10737:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10738:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10739:                 return &Apache::lonlocal::mt($roletext);
                   10740:             }
                   10741:         }
                   10742:     }
                   10743:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10744:         (defined($rolenames{$type})) && 
                   10745:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10746:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10747:     } elsif ($cid ne '') {
                   10748:         my $crstype = $env{'course.'.$cid.'.type'};
                   10749:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10750:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10751:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10752:         }
1.742     raeburn  10753:     }
1.1037    raeburn  10754:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10755: }
                   10756: 
                   10757: # ----------------------------------------------------------------- Assign Role
                   10758: 
                   10759: sub assignrole {
1.957     raeburn  10760:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
1.1512    raeburn  10761:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
1.1517    raeburn  10762:     my ($mrole,$rolelogcontext);
1.21      www      10763:     if ($role =~ /^cr\//) {
1.393     www      10764:         my $cwosec=$url;
1.811     albertel 10765:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.1502    raeburn  10766:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
1.1512    raeburn  10767:             my $refused = 1;
                   10768:             if ($context eq 'requestcourses') {
                   10769:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10770:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10771:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10772:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10773:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10774:                             if ($crsenv{'internal.courseowner'} eq
                   10775:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
                   10776:                                 $refused = '';
                   10777:                             }
                   10778:                         }
                   10779:                     }
                   10780:                 }
                   10781:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
                   10782:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10783:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
                   10784:                 my $key = "$uname:$udom:$role:$sec";
                   10785:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
                   10786:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10787:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10788:                         $refused = '';
                   10789:                     }
                   10790:                 }
                   10791:             }
                   10792:             if ($refused) {
                   10793:                 &logthis('Refused custom assignrole: '.
                   10794:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10795:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10796:                 return 'refused';
                   10797:             }
1.104     www      10798:         }
1.21      www      10799:         $mrole='cr';
1.678     raeburn  10800:     } elsif ($role =~ /^gr\//) {
                   10801:         my $cwogrp=$url;
1.811     albertel 10802:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.1512    raeburn  10803:         if (!&allowed('mdg',$cwogrp)) {
                   10804:             my $refused = 1;
                   10805:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
                   10806:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
                   10807:                 my $key = "$uname:$udom:$reqrole:$reqsec";
                   10808:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
                   10809:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10810:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10811:                         $refused = '';
                   10812:                     }
                   10813:                 }
                   10814:             }
                   10815:             if ($refused) {
                   10816:                 &logthis('Refused group assignrole: '.
                   10817:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10818:                          $env{'user.name'}.' at '.$env{'user.domain'});
                   10819:                 return 'refused';
                   10820:             }
1.678     raeburn  10821:         }
                   10822:         $mrole='gr';
1.21      www      10823:     } else {
1.82      www      10824:         my $cwosec=$url;
1.811     albertel 10825:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10826:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10827:             my $refused;
                   10828:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10829:                 if (!(&allowed('c'.$role,$url))) {
                   10830:                     $refused = 1;
                   10831:                 }
                   10832:             } else {
                   10833:                 $refused = 1;
                   10834:             }
1.947     raeburn  10835:             if ($refused) {
1.1045    raeburn  10836:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1512    raeburn  10837:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
                   10838:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10839:                     my %crsenv;
                   10840:                     if ($role eq 'cc' || $role eq 'co') {
                   10841:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10842:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10843:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10844:                                 if ($crsenv{'internal.courseowner'} eq 
                   10845:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10846:                                     $refused = '';
                   10847:                                 }
                   10848:                             }
                   10849:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10850:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10851:                                 if ($crsenv{'internal.courseowner'} eq 
                   10852:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10853:                                     $refused = '';
                   10854:                                 }
                   10855:                             }
                   10856:                         }
                   10857:                     }
1.1368    raeburn  10858:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10859:                     if ($role eq 'st') {
                   10860:                         $refused = '';
1.1377    raeburn  10861:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10862:                         $refused = '';
                   10863:                     }
1.1512    raeburn  10864:                 } elsif ($othdomby eq 'othdombyuser') {
                   10865:                     my ($key,%queuedrolereq);
                   10866:                     if ($context eq 'course') {
                   10867:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
                   10868:                         $key = "$uname:$udom:$role:$sec";
                   10869:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
                   10870:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10871:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10872:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
                   10873:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
                   10874:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10875:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
                   10876:                                         $refused = '';
                   10877:                                     }
                   10878:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
                   10879:                                     $refused = '';
                   10880:                                 }
                   10881:                             }
                   10882:                         }
                   10883:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
                   10884:                         my $key = "$uname:$udom:$role"; 
                   10885:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
                   10886:                         if (($audom ne '') && ($auname ne '')) {
                   10887:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
                   10888:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10889:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10890:                                     $refused = '';
                   10891:                                 }
                   10892:                             }
                   10893:                         }
                   10894:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
                   10895:                         my $key = "$uname:$udom:$role";
                   10896:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
                   10897:                         if ($roledom ne '') {
                   10898:                             my $confname = $roledom.'-domainconfig';
                   10899:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
                   10900:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10901:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10902:                                     $refused = '';
                   10903:                                 }
                   10904:                             }
                   10905:                         }
                   10906:                     }
1.1017    raeburn  10907:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10908:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10909:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10910:                         my $wrongcc;
                   10911:                         if ($cnum =~ /^$match_community$/) {
                   10912:                             $wrongcc = 1 if ($role eq 'cc');
                   10913:                         } else {
                   10914:                             $wrongcc = 1 if ($role eq 'co');
                   10915:                         }
                   10916:                         unless ($wrongcc) {
                   10917:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10918:                             if ($crsenv{'internal.courseowner'} eq 
                   10919:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10920:                                 $refused = '';
                   10921:                             }
1.1017    raeburn  10922:                         }
                   10923:                     }
1.1183    raeburn  10924:                 } elsif ($context eq 'requestauthor') {
                   10925:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10926:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10927:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10928:                             $refused = '';
                   10929:                         } else {
                   10930:                             my %domdefaults = &get_domain_defaults($udom);
                   10931:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10932:                                 my $checkbystatus;
                   10933:                                 if ($env{'user.adv'}) { 
                   10934:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10935:                                     if ($disposition eq 'automatic') {
                   10936:                                         $refused = '';
                   10937:                                     } elsif ($disposition eq '') {
                   10938:                                         $checkbystatus = 1;
                   10939:                                     } 
                   10940:                                 } else {
                   10941:                                     $checkbystatus = 1;
                   10942:                                 }
                   10943:                                 if ($checkbystatus) {
                   10944:                                     if ($env{'environment.inststatus'}) {
                   10945:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10946:                                         foreach my $type (@inststatuses) {
                   10947:                                             if (($type ne '') &&
                   10948:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10949:                                                 $refused = '';
                   10950:                                             }
                   10951:                                         }
                   10952:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10953:                                         $refused = '';
                   10954:                                     }
                   10955:                                 }
                   10956:                             }
                   10957:                         }
                   10958:                     }
1.1517    raeburn  10959:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
                   10960:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
                   10961:                         my ($audom,$auname) = ($1,$2);
                   10962:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
                   10963:                             ($env{"environment.internal.manager.$url"})) {
                   10964:                             $refused = '';
                   10965:                             $rolelogcontext = 'coauthor';
                   10966:                         }
                   10967:                     }
1.1017    raeburn  10968:                 }
                   10969:                 if ($refused) {
1.947     raeburn  10970:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10971:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10972: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10973:                     return 'refused';
                   10974:                 }
1.932     raeburn  10975:             }
1.1131    raeburn  10976:         } elsif ($role eq 'au') {
                   10977:             if ($url ne '/'.$udom.'/') {
                   10978:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10979:                          ' to assign author role for '.$uname.':'.$udom.
                   10980:                          ' in domain: '.$url.' refused (wrong domain).');
                   10981:                 return 'refused';
                   10982:             }
1.104     www      10983:         }
1.21      www      10984:         $mrole=$role;
                   10985:     }
1.620     albertel 10986:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10987:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10988:     if ($end) { $command.='_'.$end; }
1.21      www      10989:     if ($start) {
                   10990: 	if ($end) { 
1.81      www      10991:            $command.='_'.$start; 
1.21      www      10992:         } else {
1.81      www      10993:            $command.='_0_'.$start;
1.21      www      10994:         }
                   10995:     }
1.739     raeburn  10996:     my $origstart = $start;
                   10997:     my $origend = $end;
1.957     raeburn  10998:     my $delflag;
1.357     www      10999: # actually delete
                   11000:     if ($deleteflag) {
1.373     www      11001: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      11002: # modify command to delete the role
1.620     albertel 11003:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      11004:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 11005: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      11006: # set start and finish to negative values for userrolelog
                   11007:            $start=-1;
                   11008:            $end=-1;
1.957     raeburn  11009:            $delflag = 1;
1.357     www      11010:         }
                   11011:     }
                   11012: # send command
1.349     www      11013:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      11014: # log new user role if status is ok
1.349     www      11015:     if ($answer eq 'ok') {
1.663     raeburn  11016: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  11017:         if (($role eq 'cc') || ($role eq 'in') ||
                   11018:             ($role eq 'ep') || ($role eq 'ad') ||
                   11019:             ($role eq 'ta') || ($role eq 'st') ||
                   11020:             ($role=~/^cr/) || ($role eq 'gr') ||
                   11021:             ($role eq 'co')) {
1.1200    raeburn  11022: # for course roles, perform group memberships changes triggered by role change.
                   11023:             unless ($role =~ /^gr/) {
                   11024:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   11025:                                                  $origstart,$selfenroll,$context);
                   11026:             }
1.1184    raeburn  11027:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1512    raeburn  11028:                            $selfenroll,$context,$othdomby,$requester);
1.1184    raeburn  11029:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  11030:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   11031:                  ($role eq 'da')) {
1.1184    raeburn  11032:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1512    raeburn  11033:                            $context,$othdomby,$requester);
1.1184    raeburn  11034:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
1.1517    raeburn  11035:             if ($rolelogcontext eq '') {
                   11036:                 $rolelogcontext = $context;
                   11037:             }
1.1184    raeburn  11038:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1517    raeburn  11039:                              $rolelogcontext,$othdomby,$requester); 
1.1184    raeburn  11040:         }
1.1053    raeburn  11041:         if ($role eq 'cc') {
                   11042:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   11043:         }
1.349     www      11044:     }
                   11045:     return $answer;
1.169     harris41 11046: }
                   11047: 
1.1053    raeburn  11048: sub autoupdate_coowners {
                   11049:     my ($url,$end,$start,$uname,$udom) = @_;
                   11050:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   11051:     if (($cdom ne '') && ($cnum ne '')) {
                   11052:         my $now = time;
                   11053:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   11054:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   11055:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   11056:             my $instcode = $coursehash{'internal.coursecode'};
1.1444    raeburn  11057:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  11058:             if ($instcode ne '') {
1.1056    raeburn  11059:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   11060:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  11061:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  11062:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444    raeburn  11063:                         unless ($result eq 'valid') {
                   11064:                             if ($xlists ne '') {
                   11065:                                 foreach my $xlist (split(',',$xlists)) {
                   11066:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   11067:                                     $result =
1.1446    raeburn  11068:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   11069:                                                                       $inst_crosslist,$uname.':'.$udom);
                   11070:                                     last if ($result eq 'valid');
1.1444    raeburn  11071:                                 }
                   11072:                             }
                   11073:                         }
1.1056    raeburn  11074:                         if ($result eq 'valid') {
                   11075:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  11076:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   11077:                                     push(@newcoowners,$coowner);
                   11078:                                 }
                   11079:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   11080:                                     push(@newcoowners,$uname.':'.$udom);
                   11081:                                 }
                   11082:                                 @newcoowners = sort(@newcoowners);
                   11083:                             } else {
                   11084:                                 push(@newcoowners,$uname.':'.$udom);
                   11085:                             }
1.1444    raeburn  11086:                         } elsif ($coursehash{'internal.co-owners'}) {
                   11087:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   11088:                                 unless ($coowner eq $uname.':'.$udom) {
                   11089:                                     push(@newcoowners,$coowner);
1.1053    raeburn  11090:                                 }
1.1444    raeburn  11091:                             }
                   11092:                             unless (@newcoowners > 0) {
                   11093:                                 $delcoowners = 1;
                   11094:                                 $coowners = '';
1.1053    raeburn  11095:                             }
                   11096:                         }
                   11097:                         if (@newcoowners || $delcoowners) {
                   11098:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   11099:                                             $delcoowners,@newcoowners);
                   11100:                         }
                   11101:                     }
                   11102:                 }
                   11103:             }
                   11104:         }
                   11105:     }
                   11106: }
                   11107: 
                   11108: sub store_coowners {
                   11109:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   11110:     my $cid = $cdom.'_'.$cnum;
                   11111:     my ($coowners,$delresult,$putresult);
                   11112:     if (@newcoowners) {
                   11113:         $coowners = join(',',@newcoowners);
                   11114:         my %coownershash = (
                   11115:                             'internal.co-owners' => $coowners,
                   11116:                            );
                   11117:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   11118:         if ($putresult eq 'ok') {
                   11119:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   11120:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   11121:             }
                   11122:         }
                   11123:     }
                   11124:     if ($delcoowners) {
                   11125:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   11126:         if ($delresult eq 'ok') {
                   11127:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   11128:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   11129:             }
                   11130:         }
                   11131:     }
                   11132:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   11133:         my %crsinfo =
1.1494    raeburn  11134:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
1.1053    raeburn  11135:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   11136:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
1.1494    raeburn  11137:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
1.1053    raeburn  11138:         }
                   11139:     }
                   11140: }
                   11141: 
1.169     harris41 11142: # -------------------------------------------------- Modify user authentication
1.197     www      11143: # Overrides without validation
                   11144: 
1.169     harris41 11145: sub modifyuserauth {
                   11146:     my ($udom,$uname,$umode,$upass)=@_;
                   11147:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  11148:     my $allowed;
                   11149:     if (&allowed('mau',$udom)) {
                   11150:         $allowed = 1;
                   11151:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   11152:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   11153:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   11154:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11155:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11156:         if (($cdom ne '') && ($cnum ne '')) {
                   11157:             my $is_owner = &is_course_owner($cdom,$cnum);
                   11158:             if ($is_owner) {
                   11159:                 $allowed = 1;
                   11160:             }
                   11161:         }
                   11162:     }
                   11163:     unless ($allowed) { return 'refused'; }
1.197     www      11164:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 11165:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   11166:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 11167:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   11168: 		     &escape($upass),$uhome);
1.1434    raeburn  11169:     my $ip = &get_requestor_ip();
1.620     albertel 11170:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      11171:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434    raeburn  11172:          '(Remote '.$ip.'): '.$reply);
1.197     www      11173:     &log($udom,,$uname,$uhome,
1.620     albertel 11174:         'Authentication changed by '.$env{'user.domain'}.', '.
                   11175:                                      $env{'user.name'}.', '.$umode.
1.1435    raeburn  11176:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 11177:     unless ($reply eq 'ok') {
1.197     www      11178:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 11179: 	return 'error: '.$reply;
                   11180:     }   
1.170     harris41 11181:     return 'ok';
1.80      www      11182: }
                   11183: 
1.81      www      11184: # --------------------------------------------------------------- Modify a user
1.80      www      11185: 
1.81      www      11186: sub modifyuser {
1.206     matthew  11187:     my ($udom,    $uname, $uid,
                   11188:         $umode,   $upass, $first,
                   11189:         $middle,  $last,  $gene,
1.1058    raeburn  11190:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 11191:     $udom= &LONCAPA::clean_domain($udom);
                   11192:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  11193:     my $showcandelete = 'none';
                   11194:     if (ref($candelete) eq 'ARRAY') {
                   11195:         if (@{$candelete} > 0) {
                   11196:             $showcandelete = join(', ',@{$candelete});
                   11197:         }
                   11198:     }
1.81      www      11199:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      11200:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  11201: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  11202:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   11203:                                      ' desiredhome not specified'). 
1.620     albertel 11204:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   11205:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 11206:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  11207:     my $newuser;
                   11208:     if ($uhome eq 'no_host') {
                   11209:         $newuser = 1;
1.1368    raeburn  11210:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   11211:                 ($umode eq 'lti')) {
                   11212:             return 'error: more information needed to create new user';
                   11213:         }
1.1075    raeburn  11214:     }
1.80      www      11215: # ----------------------------------------------------------------- Create User
1.406     albertel 11216:     if (($uhome eq 'no_host') && 
1.1368    raeburn  11217: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      11218:         my $unhome='';
1.844     albertel 11219:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  11220:             $unhome = $desiredhome;
1.620     albertel 11221: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   11222: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  11223:         } else { # load balancing routine for determining $unhome
1.81      www      11224:             my $loadm=10000000;
1.841     albertel 11225: 	    my %servers = &get_servers($udom,'library');
                   11226: 	    foreach my $tryserver (keys(%servers)) {
                   11227: 		my $answer=reply('load',$tryserver);
                   11228: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   11229: 		    $loadm=$answer;
                   11230: 		    $unhome=$tryserver;
                   11231: 		}
1.80      www      11232: 	    }
                   11233:         }
                   11234:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  11235: 	    return 'error: unable to find a home server for '.$uname.
                   11236:                    ' in domain '.$udom;
1.80      www      11237:         }
                   11238:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   11239:                          &escape($upass),$unhome);
                   11240: 	unless ($reply eq 'ok') {
                   11241:             return 'error: '.$reply;
                   11242:         }   
1.230     stredwic 11243:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      11244:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  11245: 	    return 'error: unable verify users home machine.';
1.80      www      11246:         }
1.209     matthew  11247:     }   # End of creation of new user
1.80      www      11248: # ---------------------------------------------------------------------- Add ID
                   11249:     if ($uid) {
                   11250:        $uid=~tr/A-Z/a-z/;
                   11251:        my %uidhash=&idrget($udom,$uname);
1.196     www      11252:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   11253:          && (!$forceid)) {
1.80      www      11254: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  11255: 	      return 'error: user id "'.$uid.'" does not match '.
                   11256:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      11257:           }
                   11258:        } else {
1.1300    raeburn  11259: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      11260:        }
                   11261:     }
                   11262: # -------------------------------------------------------------- Add names, etc
1.313     matthew  11263:     my @tmp=&get('environment',
1.899     raeburn  11264: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  11265:                     'permanentemail','inststatus'],
1.134     albertel 11266: 		   $udom,$uname);
1.1075    raeburn  11267:     my (%names,%oldnames);
1.313     matthew  11268:     if ($tmp[0] =~ m/^error:.*/) { 
                   11269:         %names=(); 
                   11270:     } else {
                   11271:         %names = @tmp;
1.1075    raeburn  11272:         %oldnames = %names;
1.313     matthew  11273:     }
1.388     www      11274: #
1.1058    raeburn  11275: # If name, email and/or uid are blank (e.g., because an uploaded file
                   11276: # of users did not contain them), do not overwrite existing values
                   11277: # unless field is in $candelete array ref.  
                   11278: #
                   11279: 
                   11280:     my @fields = ('firstname','middlename','lastname','generation',
                   11281:                   'permanentemail','id');
                   11282:     my %newvalues;
                   11283:     if (ref($candelete) eq 'ARRAY') {
                   11284:         foreach my $field (@fields) {
                   11285:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   11286:                 if ($field eq 'firstname') {
                   11287:                     $names{$field} = $first;
                   11288:                 } elsif ($field eq 'middlename') {
                   11289:                     $names{$field} = $middle;
                   11290:                 } elsif ($field eq 'lastname') {
                   11291:                     $names{$field} = $last;
                   11292:                 } elsif ($field eq 'generation') { 
                   11293:                     $names{$field} = $gene;
                   11294:                 } elsif ($field eq 'permanentemail') {
                   11295:                     $names{$field} = $email;
                   11296:                 } elsif ($field eq 'id') {
                   11297:                     $names{$field}  = $uid;
                   11298:                 }
                   11299:             }
                   11300:         }
                   11301:     }
1.388     www      11302:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  11303:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      11304:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  11305:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      11306:     if ($email) {
                   11307:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  11308:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      11309:     }
1.899     raeburn  11310:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  11311:     if (defined($inststatus)) {
                   11312:         $names{'inststatus'} = '';
                   11313:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   11314:         if (ref($usertypes) eq 'HASH') {
                   11315:             my @okstatuses; 
                   11316:             foreach my $item (split(/:/,$inststatus)) {
                   11317:                 if (defined($usertypes->{$item})) {
                   11318:                     push(@okstatuses,$item);  
                   11319:                 }
                   11320:             }
                   11321:             if (@okstatuses) {
                   11322:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   11323:             }
                   11324:         }
                   11325:     }
1.1075    raeburn  11326:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  11327:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  11328:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  11329:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   11330:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   11331:     } else {
                   11332:         $logmsg .= ' during self creation';
                   11333:     }
1.1075    raeburn  11334:     my $changed;
                   11335:     if ($newuser) {
                   11336:         $changed = 1;
                   11337:     } else {
                   11338:         foreach my $field (@fields) {
                   11339:             if ($names{$field} ne $oldnames{$field}) {
                   11340:                 $changed = 1;
                   11341:                 last;
                   11342:             }
                   11343:         }
                   11344:     }
                   11345:     unless ($changed) {
                   11346:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   11347:         &logthis($logmsg);
                   11348:         return 'ok';
                   11349:     }
                   11350:     my $reply = &put('environment', \%names, $udom,$uname);
                   11351:     if ($reply ne 'ok') { 
                   11352:         return 'error: '.$reply;
                   11353:     }
1.1087    raeburn  11354:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
1.1494    raeburn  11355:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
1.1087    raeburn  11356:     }
1.1075    raeburn  11357:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   11358:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   11359:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  11360:     &logthis($logmsg);
1.134     albertel 11361:     return 'ok';
1.80      www      11362: }
                   11363: 
1.81      www      11364: # -------------------------------------------------------------- Modify student
1.80      www      11365: 
1.81      www      11366: sub modifystudent {
                   11367:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  11368:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  11369:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 11370:     if (!$cid) {
1.620     albertel 11371: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 11372: 	    return 'not_in_class';
                   11373: 	}
1.80      www      11374:     }
                   11375: # --------------------------------------------------------------- Make the user
1.81      www      11376:     my $reply=&modifyuser
1.209     matthew  11377: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  11378:          $desiredhome,$email,$inststatus);
1.80      www      11379:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  11380:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  11381:     # student's environment
1.297     matthew  11382:     $uid = undef if (!$forceid);
1.455     albertel 11383:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  11384:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  11385:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  11386:     return $reply;
                   11387: }
                   11388: 
                   11389: sub modify_student_enrollment {
1.1216    raeburn  11390:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1512    raeburn  11391:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
1.455     albertel 11392:     my ($cdom,$cnum,$chome);
                   11393:     if (!$cid) {
1.620     albertel 11394: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 11395: 	    return 'not_in_class';
                   11396: 	}
1.620     albertel 11397: 	$cdom=$env{'course.'.$cid.'.domain'};
                   11398: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 11399:     } else {
                   11400: 	($cdom,$cnum)=split(/_/,$cid);
                   11401:     }
1.620     albertel 11402:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 11403:     if (!$chome) {
1.457     raeburn  11404: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  11405:     }
1.455     albertel 11406:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  11407:     # Make sure the user exists
1.81      www      11408:     my $uhome=&homeserver($uname,$udom);
                   11409:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11410: 	return 'error: no such user';
                   11411:     }
1.297     matthew  11412:     # Get student data if we were not given enough information
                   11413:     if (!defined($first)  || $first  eq '' || 
                   11414:         !defined($last)   || $last   eq '' || 
                   11415:         !defined($uid)    || $uid    eq '' || 
                   11416:         !defined($middle) || $middle eq '' || 
                   11417:         !defined($gene)   || $gene   eq '') {
1.294     matthew  11418:         # They did not supply us with enough data to enroll the student, so
                   11419:         # we need to pick up more information.
1.297     matthew  11420:         my %tmp = &get('environment',
1.294     matthew  11421:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  11422:                        ,$udom,$uname);
                   11423: 
1.800     albertel 11424:         #foreach my $key (keys(%tmp)) {
                   11425:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 11426:         #}
1.294     matthew  11427:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   11428:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   11429:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  11430:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  11431:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   11432:     }
1.556     albertel 11433:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  11434:     my $user = "$uname:$udom";
1.1494    raeburn  11435:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
1.487     albertel 11436:     my $reply=cput('classlist',
1.1148    raeburn  11437: 		   {$user => 
1.1314    raeburn  11438: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 11439: 		   $cdom,$cnum);
1.1148    raeburn  11440:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   11441:         &devalidate_getsection_cache($udom,$uname,$cid);
                   11442:     } else { 
1.81      www      11443: 	return 'error: '.$reply;
                   11444:     }
1.297     matthew  11445:     # Add student role to user
1.83      www      11446:     my $uurl='/'.$cid;
1.81      www      11447:     $uurl=~s/\_/\//g;
                   11448:     if ($usec) {
                   11449: 	$uurl.='/'.$usec;
                   11450:     }
1.1148    raeburn  11451:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
1.1512    raeburn  11452:                              $selfenroll,$context,$othdomby,$requester);
1.1148    raeburn  11453:     if ($result ne 'ok') {
                   11454:         if ($old_entry{$user} ne '') {
                   11455:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   11456:         } else {
                   11457:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   11458:         }
                   11459:     }
                   11460:     return $result; 
1.21      www      11461: }
                   11462: 
1.556     albertel 11463: sub format_name {
                   11464:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   11465:     my $name;
                   11466:     if ($first ne 'lastname') {
                   11467: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   11468:     } else {
                   11469: 	if ($lastname=~/\S/) {
                   11470: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   11471: 	    $name=~s/\s+,/,/;
                   11472: 	} else {
                   11473: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   11474: 	}
                   11475:     }
                   11476:     $name=~s/^\s+//;
                   11477:     $name=~s/\s+$//;
                   11478:     $name=~s/\s+/ /g;
                   11479:     return $name;
                   11480: }
                   11481: 
1.84      www      11482: # ------------------------------------------------- Write to course preferences
                   11483: 
                   11484: sub writecoursepref {
                   11485:     my ($courseid,%prefs)=@_;
                   11486:     $courseid=~s/^\///;
                   11487:     $courseid=~s/\_/\//g;
                   11488:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   11489:     my $chome=homeserver($cnum,$cdomain);
                   11490:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   11491: 	return 'error: no such course';
                   11492:     }
                   11493:     my $cstring='';
1.800     albertel 11494:     foreach my $pref (keys(%prefs)) {
                   11495: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 11496:     }
1.84      www      11497:     $cstring=~s/\&$//;
                   11498:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   11499: }
                   11500: 
                   11501: # ---------------------------------------------------------- Make/modify course
                   11502: 
                   11503: sub createcourse {
1.741     raeburn  11504:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  11505:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      11506:     $url=&declutter($url);
                   11507:     my $cid='';
1.1028    raeburn  11508:     if ($context eq 'requestcourses') {
                   11509:         my $can_create = 0;
                   11510:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   11511:         if ($udom eq $ownerdom) {
1.1423    raeburn  11512:             my $reload;
                   11513:             if (($callercontext eq 'auto') &&
                   11514:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   11515:                 $reload = 'reload';
                   11516:             }
                   11517:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  11518:                                   $context)) {
                   11519:                 $can_create = 1;
                   11520:             }
                   11521:         } else {
                   11522:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   11523:                                            $category);
                   11524:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   11525:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   11526:                 if (@curr > 0) {
                   11527:                     my @options = qw(approval validate autolimit);
                   11528:                     my $optregex = join('|',@options);
                   11529:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   11530:                         $can_create = 1;
                   11531:                     }
                   11532:                 }
                   11533:             }
                   11534:         }
                   11535:         if ($can_create) {
                   11536:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   11537:                 unless (&allowed('ccc',$udom)) {
                   11538:                     return 'refused'; 
                   11539:                 }
1.1017    raeburn  11540:             }
                   11541:         } else {
                   11542:             return 'refused';
                   11543:         }
1.1028    raeburn  11544:     } elsif (!&allowed('ccc',$udom)) {
                   11545:         return 'refused';
1.84      www      11546:     }
1.1011    raeburn  11547: # --------------------------------------------------------------- Get Unique ID
                   11548:     my $uname;
                   11549:     if ($cnum =~ /^$match_courseid$/) {
                   11550:         my $chome=&homeserver($cnum,$udom,'true');
                   11551:         if (($chome eq '') || ($chome eq 'no_host')) {
                   11552:             $uname = $cnum;
                   11553:         } else {
1.1038    raeburn  11554:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11555:         }
                   11556:     } else {
1.1038    raeburn  11557:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11558:     }
                   11559:     return $uname if ($uname =~ /^error/);
                   11560: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  11561:     if (!defined($course_server)) {
                   11562:         if (defined(&domain($udom,'primary'))) {
                   11563:             $course_server = &domain($udom,'primary');
                   11564:         } else {
                   11565:             $course_server = $env{'user.home'}; 
                   11566:         }
                   11567:     }
                   11568:     my %host_servers =
1.1494    raeburn  11569:         &get_servers($udom,'library');
1.1052    raeburn  11570:     unless ($host_servers{$course_server}) {
                   11571:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11572:     }
1.84      www      11573: # ------------------------------------------------------------- Make the course
                   11574:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11575:                       $course_server);
1.84      www      11576:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11577:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11578:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11579: 	return 'error: no such course';
                   11580:     }
1.271     www      11581: # ----------------------------------------------------------------- Course made
1.516     raeburn  11582: # log existence
1.1029    raeburn  11583:     my $now = time;
1.918     raeburn  11584:     my $newcourse = {
                   11585:                     $udom.'_'.$uname => {
1.921     raeburn  11586:                                      description => $description,
                   11587:                                      inst_code   => $inst_code,
                   11588:                                      owner       => $course_owner,
                   11589:                                      type        => $crstype,
1.1029    raeburn  11590:                                      creator     => $env{'user.name'}.':'.
                   11591:                                                     $env{'user.domain'},
                   11592:                                      created     => $now,
                   11593:                                      context     => $context,
1.918     raeburn  11594:                                                 },
                   11595:                     };
1.921     raeburn  11596:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11597: # set toplevel url
1.271     www      11598:     my $topurl=$url;
                   11599:     unless ($nonstandard) {
                   11600: # ------------------------------------------ For standard courses, make top url
                   11601:         my $mapurl=&clutter($url);
1.278     www      11602:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11603:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11604: <map>
                   11605: <resource id="1" type="start"></resource>
                   11606: <resource id="2" src="$mapurl"></resource>
                   11607: <resource id="3" type="finish"></resource>
                   11608: <link index="1" from="1" to="2"></link>
                   11609: <link index="2" from="2" to="3"></link>
                   11610: </map>
                   11611: ENDINITMAP
                   11612:         $topurl=&declutter(
1.638     albertel 11613:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11614:                           );
                   11615:     }
                   11616: # ----------------------------------------------------------- Write preferences
1.84      www      11617:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11618:                      ('description'              => $description,
                   11619:                       'url'                      => $topurl,
                   11620:                       'internal.creator'         => $env{'user.name'}.':'.
                   11621:                                                     $env{'user.domain'},
                   11622:                       'internal.created'         => $now,
                   11623:                       'internal.creationcontext' => $context)
                   11624:                     );
1.84      www      11625:     return '/'.$udom.'/'.$uname;
                   11626: }
                   11627: 
1.1011    raeburn  11628: # ------------------------------------------------------------------- Create ID
                   11629: sub generate_coursenum {
1.1038    raeburn  11630:     my ($udom,$crstype) = @_;
1.1011    raeburn  11631:     my $domdesc = &domain($udom);
                   11632:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11633:     my $first;
                   11634:     if ($crstype eq 'Community') {
                   11635:         $first = '0';
                   11636:     } else {
                   11637:         $first = int(1+rand(9)); 
                   11638:     } 
                   11639:     my $uname=$first.
1.1011    raeburn  11640:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11641:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11642:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11643: # ----------------------------------------------- Make sure that does not exist
                   11644:     my $uhome=&homeserver($uname,$udom,'true');
                   11645:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11646:         if ($crstype eq 'Community') {
                   11647:             $first = '0';
                   11648:         } else {
                   11649:             $first = int(1+rand(9));
                   11650:         }
                   11651:         $uname=$first.
1.1011    raeburn  11652:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11653:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11654:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11655:         $uhome=&homeserver($uname,$udom,'true');
                   11656:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11657:             return 'error: unable to generate unique course-ID';
                   11658:         }
                   11659:     }
                   11660:     return $uname;
                   11661: }
                   11662: 
1.813     albertel 11663: sub is_course {
1.1167    droeschl 11664:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11665:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   11666: 
1.1381    raeburn  11667:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11668:     my $uhome=&homeserver($cnum,$cdom);
                   11669:     my $iscourse;
                   11670:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  11671:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  11672:     } else {
                   11673:         my $hashid = $cdom.':'.$cnum;
                   11674:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11675:         unless (defined($cached)) {
                   11676:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11677:                                         $cnum,undef,undef,'.');
                   11678:             $iscourse = 0;
                   11679:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11680:                 $iscourse = 1;
                   11681:             }
                   11682:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11683:         }
                   11684:     }
                   11685:     return unless ($iscourse);
1.1167    droeschl 11686:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11687: }
                   11688: 
1.1015    raeburn  11689: sub store_userdata {
1.1533    raeburn  11690:     my ($storehash,$datakey,$namespace,$udom,$uname,$ip) = @_;
1.1013    raeburn  11691:     my $result;
1.1016    raeburn  11692:     if ($datakey ne '') {
1.1013    raeburn  11693:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11694:             if ($udom eq '' || $uname eq '') {
                   11695:                 $udom = $env{'user.domain'};
                   11696:                 $uname = $env{'user.name'};
                   11697:             }
                   11698:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11699:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11700:                 $result = 'error: no_host';
                   11701:             } else {
1.1533    raeburn  11702:                 if ($ip ne '') {
                   11703:                     $storehash->{'ip'} = $ip;
                   11704:                 } else {
                   11705:                     $storehash->{'ip'} = &get_requestor_ip();
                   11706:                 }
1.1013    raeburn  11707:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11708: 
                   11709:                 my $namevalue='';
                   11710:                 foreach my $key (keys(%{$storehash})) {
                   11711:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11712:                 }
                   11713:                 $namevalue=~s/\&$//;
1.1224    raeburn  11714:                 unless ($namespace eq 'courserequests') {
                   11715:                     $datakey = &escape($datakey);
                   11716:                 }
1.1105    raeburn  11717:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11718:                                   $namevalue,$uhome);
1.1013    raeburn  11719:             }
                   11720:         } else {
                   11721:             $result = 'error: data to store was not a hash reference'; 
                   11722:         }
                   11723:     } else {
                   11724:         $result= 'error: invalid requestkey'; 
                   11725:     }
                   11726:     return $result;
                   11727: }
                   11728: 
1.21      www      11729: # ---------------------------------------------------------- Assign Custom Role
                   11730: 
                   11731: sub assigncustomrole {
1.1512    raeburn  11732:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
                   11733:         $selfenroll,$context,$othdomby,$requester)=@_;
1.21      www      11734:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.1512    raeburn  11735:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
                   11736:                        $requester);
1.21      www      11737: }
                   11738: 
                   11739: # ----------------------------------------------------------------- Revoke Role
                   11740: 
                   11741: sub revokerole {
1.957     raeburn  11742:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11743:     my $now=time;
1.965     raeburn  11744:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11745: }
                   11746: 
                   11747: # ---------------------------------------------------------- Revoke Custom Role
                   11748: 
                   11749: sub revokecustomrole {
1.957     raeburn  11750:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11751:     my $now=time;
1.357     www      11752:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11753:            $deleteflag,$selfenroll,$context);
1.17      www      11754: }
                   11755: 
1.533     banghart 11756: # ------------------------------------------------------------ Disk usage
1.535     albertel 11757: sub diskusage {
1.955     raeburn  11758:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11759:     $directorypath =~ s/\/$//;
                   11760:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11761:                        .&escape($getpropath).':'.&escape($uname).':'
                   11762:                        .&escape($udom),homeserver($uname,$udom));
                   11763:     if ($listing eq 'unknown_cmd') {
                   11764:         if ($getpropath) {
                   11765:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11766:         }
                   11767:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11768:     }
1.514     albertel 11769:     return $listing;
1.512     banghart 11770: }
                   11771: 
1.566     banghart 11772: sub is_locked {
1.1096    raeburn  11773:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11774:     my @check;
                   11775:     my $is_locked;
1.1093    raeburn  11776:     push (@check,$file_name);
1.613     albertel 11777:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11778: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11779:     my ($tmp)=keys(%locked);
                   11780:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11781:     
1.566     banghart 11782:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11783:         $is_locked = 'false';
                   11784:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11785:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11786:                $is_locked = 'true';
1.1096    raeburn  11787:                if (ref($which) eq 'ARRAY') {
                   11788:                    push(@{$which},$entry);
                   11789:                } else {
                   11790:                    last;
                   11791:                }
1.745     raeburn  11792:            }
                   11793:        }
1.566     banghart 11794:     } else {
                   11795:         $is_locked = 'false';
                   11796:     }
1.1093    raeburn  11797:     return $is_locked;
1.566     banghart 11798: }
                   11799: 
1.759     albertel 11800: sub declutter_portfile {
                   11801:     my ($file) = @_;
1.833     albertel 11802:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11803:     return $file;
                   11804: }
                   11805: 
1.559     banghart 11806: # ------------------------------------------------------------- Mark as Read Only
                   11807: 
                   11808: sub mark_as_readonly {
                   11809:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11810:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11811:     my ($tmp)=keys(%current_permissions);
                   11812:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11813:     foreach my $file (@{$files}) {
1.759     albertel 11814: 	$file = &declutter_portfile($file);
1.561     banghart 11815:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11816:     }
1.613     albertel 11817:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11818:     return;
                   11819: }
                   11820: 
1.572     banghart 11821: # ------------------------------------------------------------Save Selected Files
                   11822: 
                   11823: sub save_selected_files {
                   11824:     my ($user, $path, @files) = @_;
                   11825:     my $filename = $user."savedfiles";
1.573     banghart 11826:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  11827:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11828:     foreach my $file (@files) {
1.620     albertel 11829:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11830:     }
                   11831:     foreach my $file (@other_files) {
1.574     banghart 11832:         print (OUT $file."\n");
1.572     banghart 11833:     }
1.574     banghart 11834:     close (OUT);
1.572     banghart 11835:     return 'ok';
                   11836: }
                   11837: 
1.574     banghart 11838: sub clear_selected_files {
                   11839:     my ($user) = @_;
                   11840:     my $filename = $user."savedfiles";
1.1359    raeburn  11841:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11842:     print (OUT undef);
                   11843:     close (OUT);
                   11844:     return ("ok");    
                   11845: }
                   11846: 
1.572     banghart 11847: sub files_in_path {
                   11848:     my ($user, $path) = @_;
                   11849:     my $filename = $user."savedfiles";
                   11850:     my %return_files;
1.1359    raeburn  11851:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11852:     while (my $line_in = <IN>) {
1.574     banghart 11853:         chomp ($line_in);
                   11854:         my @paths_and_file = split (m!/!, $line_in);
                   11855:         my $file_part = pop (@paths_and_file);
                   11856:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11857:         $path_part.='/';
                   11858:         my $path_and_file = $path_part.$file_part;
                   11859:         if ($path_part eq $path) {
                   11860:             $return_files{$file_part}= 'selected';
                   11861:         }
                   11862:     }
1.574     banghart 11863:     close (IN);
                   11864:     return (\%return_files);
1.572     banghart 11865: }
                   11866: 
                   11867: # called in portfolio select mode, to show files selected NOT in current directory
                   11868: sub files_not_in_path {
                   11869:     my ($user, $path) = @_;
                   11870:     my $filename = $user."savedfiles";
                   11871:     my @return_files;
                   11872:     my $path_part;
1.1359    raeburn  11873:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11874:     while (my $line = <IN>) {
1.572     banghart 11875:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11876:         my @paths_and_file = split(m|/|, $line);
                   11877:         my $file_part = pop(@paths_and_file);
                   11878:         chomp($file_part);
                   11879:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11880:         $path_part .= '/';
                   11881:         my $path_and_file = $path_part.$file_part;
                   11882:         if ($path_part ne $path) {
1.800     albertel 11883:             push(@return_files, ($path_and_file));
1.572     banghart 11884:         }
                   11885:     }
1.800     albertel 11886:     close(OUT);
1.574     banghart 11887:     return (@return_files);
1.572     banghart 11888: }
                   11889: 
1.1273    raeburn  11890: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11891:  
                   11892: sub portfiles_versioning {
                   11893:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11894:     my $portfolio_root = '/userfiles/portfolio';
                   11895:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11896:     foreach my $file (@{$portfiles}) {
                   11897:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11898:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11899:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11900:         my $getpropath = 1;
                   11901:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11902:                                              $stu_name,$getpropath);
                   11903:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11904:         my $new_answer = 
                   11905:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11906:         if ($new_answer ne 'problem getting file') {
                   11907:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11908:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11909:                               [$symb,$env{'request.course.id'},'graded']);
                   11910:         }
                   11911:     }
                   11912: }
                   11913: 
                   11914: sub get_next_version {
                   11915:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11916:     my $version;
                   11917:     if (ref($dir_list) eq 'ARRAY') {
                   11918:         foreach my $row (@{$dir_list}) {
                   11919:             my ($file) = split(/\&/,$row,2);
                   11920:             my ($file_name,$file_version,$file_ext) =
                   11921:                 &file_name_version_ext($file);
                   11922:             if (($file_name eq $answer_name) &&
                   11923:                 ($file_ext eq $answer_ext)) {
                   11924:                      # gets here if filename and extension match,
                   11925:                      # regardless of version
                   11926:                 if ($file_version ne '') {
                   11927:                     # a versioned file is found  so save it for later
                   11928:                     if ($file_version > $version) {
                   11929:                         $version = $file_version;
                   11930:                     }
                   11931:                 }
                   11932:             }
                   11933:         }
                   11934:     }
                   11935:     $version ++;
                   11936:     return($version);
                   11937: }
                   11938: 
                   11939: sub version_selected_portfile {
                   11940:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11941:     my ($answer_name,$answer_ver,$answer_ext) =
                   11942:         &file_name_version_ext($file_name);
                   11943:     my $new_answer;
                   11944:     $env{'form.copy'} =
                   11945:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11946:     if($env{'form.copy'} eq '-1') {
                   11947:         $new_answer = 'problem getting file';
                   11948:     } else {
                   11949:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11950:         my $copy_result = 
                   11951:             &finishuserfileupload($stu_name,$domain,'copy',
                   11952:                                   '/portfolio'.$directory.$new_answer);
                   11953:     }
                   11954:     undef($env{'form.copy'});
                   11955:     return ($new_answer);
                   11956: }
                   11957: 
                   11958: sub file_name_version_ext {
                   11959:     my ($file)=@_;
                   11960:     my @file_parts = split(/\./, $file);
                   11961:     my ($name,$version,$ext);
                   11962:     if (@file_parts > 1) {
                   11963:         $ext=pop(@file_parts);
                   11964:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11965:             $version=pop(@file_parts);
                   11966:         }
                   11967:         $name=join('.',@file_parts);
                   11968:     } else {
                   11969:         $name=join('.',@file_parts);
                   11970:     }
                   11971:     return($name,$version,$ext);
                   11972: }
                   11973: 
1.745     raeburn  11974: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11975: 
1.745     raeburn  11976: sub get_portfile_permissions {
                   11977:     my ($domain,$user) = @_;
1.613     albertel 11978:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11979:     my ($tmp)=keys(%current_permissions);
                   11980:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11981:     return \%current_permissions;
                   11982: }
                   11983: 
                   11984: #---------------------------------------------Get portfolio file access controls
                   11985: 
1.749     raeburn  11986: sub get_access_controls {
1.745     raeburn  11987:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11988:     my %access;
                   11989:     my $real_file = $file;
                   11990:     $file =~ s/\.meta$//;
1.745     raeburn  11991:     if (defined($file)) {
1.749     raeburn  11992:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11993:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11994:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11995:             }
                   11996:         }
1.745     raeburn  11997:     } else {
1.749     raeburn  11998:         foreach my $key (keys(%{$current_permissions})) {
                   11999:             if ($key =~ /\0accesscontrol$/) {
                   12000:                 if (defined($group)) {
                   12001:                     if ($key !~ m-^\Q$group\E/-) {
                   12002:                         next;
                   12003:                     }
                   12004:                 }
                   12005:                 my ($fullpath) = split(/\0/,$key);
                   12006:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   12007:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   12008:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   12009:                     }
                   12010:                 }
                   12011:             }
                   12012:         }
                   12013:     }
                   12014:     return %access;
                   12015: }
                   12016: 
                   12017: sub modify_access_controls {
                   12018:     my ($file_name,$changes,$domain,$user)=@_;
                   12019:     my ($outcome,$deloutcome);
                   12020:     my %store_permissions;
                   12021:     my %new_values;
                   12022:     my %new_control;
                   12023:     my %translation;
                   12024:     my @deletions = ();
                   12025:     my $now = time;
                   12026:     if (exists($$changes{'activate'})) {
                   12027:         if (ref($$changes{'activate'}) eq 'HASH') {
                   12028:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   12029:             my $numnew = scalar(@newitems);
                   12030:             for (my $i=0; $i<$numnew; $i++) {
                   12031:                 my $newkey = $newitems[$i];
                   12032:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  12033:                 if ($newkey =~ /^\d+:/) { 
                   12034:                     $newkey =~ s/^(\d+)/$newid/;
                   12035:                     $translation{$1} = $newid;
                   12036:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   12037:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   12038:                     $translation{$1} = $newid;
                   12039:                 }
1.749     raeburn  12040:                 $new_values{$file_name."\0".$newkey} = 
                   12041:                                           $$changes{'activate'}{$newitems[$i]};
                   12042:                 $new_control{$newkey} = $now;
                   12043:             }
                   12044:         }
                   12045:     }
                   12046:     my %todelete;
                   12047:     my %changed_items;
                   12048:     foreach my $action ('delete','update') {
                   12049:         if (exists($$changes{$action})) {
                   12050:             if (ref($$changes{$action}) eq 'HASH') {
                   12051:                 foreach my $key (keys(%{$$changes{$action}})) {
                   12052:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   12053:                     if ($action eq 'delete') { 
                   12054:                         $todelete{$itemnum} = 1;
                   12055:                     } else {
                   12056:                         $changed_items{$itemnum} = $key;
                   12057:                     }
                   12058:                 }
1.745     raeburn  12059:             }
                   12060:         }
1.749     raeburn  12061:     }
                   12062:     # get lock on access controls for file.
                   12063:     my $lockhash = {
                   12064:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   12065:                                                        ':'.$env{'user.domain'},
                   12066:                    }; 
                   12067:     my $tries = 0;
                   12068:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   12069:    
1.1288    damieng  12070:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  12071:         $tries ++;
1.1289    damieng  12072:         sleep(0.1);
1.749     raeburn  12073:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   12074:     }
                   12075:     if ($gotlock eq 'ok') {
                   12076:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   12077:         my ($tmp)=keys(%curr_permissions);
                   12078:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   12079:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   12080:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   12081:             if (ref($curr_controls) eq 'HASH') {
                   12082:                 foreach my $control_item (keys(%{$curr_controls})) {
                   12083:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   12084:                     if (defined($todelete{$itemnum})) {
                   12085:                         push(@deletions,$file_name."\0".$control_item);
                   12086:                     } else {
                   12087:                         if (defined($changed_items{$itemnum})) {
                   12088:                             $new_control{$changed_items{$itemnum}} = $now;
                   12089:                             push(@deletions,$file_name."\0".$control_item);
                   12090:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   12091:                         } else {
                   12092:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   12093:                         }
                   12094:                     }
1.745     raeburn  12095:                 }
                   12096:             }
                   12097:         }
1.970     raeburn  12098:         my ($group);
                   12099:         if (&is_course($domain,$user)) {
                   12100:             ($group,my $file) = split(/\//,$file_name,2);
                   12101:         }
1.749     raeburn  12102:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   12103:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   12104:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   12105:         #  remove lock
                   12106:         my @del_lock = ($file_name."\0".'locked_access_records');
                   12107:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  12108:         my $sqlresult =
1.970     raeburn  12109:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  12110:                                     $group);
1.749     raeburn  12111:     } else {
                   12112:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  12113:     }
1.749     raeburn  12114:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  12115: }
                   12116: 
1.827     raeburn  12117: sub make_public_indefinitely {
1.1271    raeburn  12118:     my (@requrl) = @_;
                   12119:     return &automated_portfile_access('public',\@requrl);
                   12120: }
                   12121: 
                   12122: sub automated_portfile_access {
                   12123:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  12124:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   12125:         return 'invalid';
                   12126:     }
1.1271    raeburn  12127:     my %urls;
                   12128:     if (ref($addsref) eq 'ARRAY') {
                   12129:         foreach my $requrl (@{$addsref}) {
                   12130:             if (&is_portfolio_url($requrl)) {
                   12131:                 unless (exists($urls{$requrl})) {
                   12132:                     $urls{$requrl} = 'add';
                   12133:                 }
                   12134:             }
                   12135:         }
                   12136:     }
                   12137:     if (ref($delsref) eq 'ARRAY') {
                   12138:         foreach my $requrl (@{$delsref}) { 
                   12139:             if (&is_portfolio_url($requrl)) {
                   12140:                 unless (exists($urls{$requrl})) {
                   12141:                     $urls{$requrl} = 'delete'; 
                   12142:                 }
                   12143:             }
                   12144:         }
                   12145:     }
                   12146:     unless (keys(%urls)) {
                   12147:         return 'invalid';
                   12148:     }
                   12149:     my $ip;
                   12150:     if ($accesstype eq 'ip') {
                   12151:         if (ref($info) eq 'HASH') {
                   12152:             if ($info->{'ip'} ne '') {
                   12153:                 $ip = $info->{'ip'};
                   12154:             }
                   12155:         }
                   12156:         if ($ip eq '') {
                   12157:             return 'invalid';
                   12158:         }
                   12159:     }
                   12160:     my $errors;
1.827     raeburn  12161:     my $now = time;
1.1271    raeburn  12162:     my %current_perms;
                   12163:     foreach my $requrl (sort(keys(%urls))) {
                   12164:         my $action;
                   12165:         if ($urls{$requrl} eq 'add') {
                   12166:             $action = 'activate';
                   12167:         } else {
                   12168:             $action = 'none';
                   12169:         }
                   12170:         my $aclnum = 0;
1.827     raeburn  12171:         my (undef,$udom,$unum,$file_name,$group) =
                   12172:             &parse_portfolio_url($requrl);
1.1271    raeburn  12173:         unless (exists($current_perms{$unum.':'.$udom})) {
                   12174:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   12175:         }
                   12176:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  12177:                                                    $group,$file_name);
                   12178:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   12179:             my ($num,$scope,$end,$start) = 
                   12180:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  12181:             if ($scope eq $accesstype) {
                   12182:                 if (($start <= $now) && ($end == 0)) {
                   12183:                     if ($accesstype eq 'ip') {
                   12184:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   12185:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   12186:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   12187:                                     if ($urls{$requrl} eq 'add') {
                   12188:                                         $action = 'none';
                   12189:                                         last;
                   12190:                                     } else {
                   12191:                                         $action = 'delete';
                   12192:                                         $aclnum = $num;
                   12193:                                         last;
                   12194:                                     }
                   12195:                                 }
                   12196:                             }
                   12197:                         }
                   12198:                     } elsif ($accesstype eq 'public') {
                   12199:                         if ($urls{$requrl} eq 'add') {
                   12200:                             $action = 'none';
                   12201:                             last;
                   12202:                         } else {
                   12203:                             $action = 'delete';
                   12204:                             $aclnum = $num;
                   12205:                             last;
                   12206:                         }
                   12207:                     }
                   12208:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  12209:                     $action = 'update';
                   12210:                     $aclnum = $num;
1.1271    raeburn  12211:                     last;
1.827     raeburn  12212:                 }
                   12213:             }
                   12214:         }
                   12215:         if ($action eq 'none') {
1.1271    raeburn  12216:             next;
1.827     raeburn  12217:         } else {
                   12218:             my %changes;
                   12219:             my $newend = 0;
                   12220:             my $newstart = $now;
1.1271    raeburn  12221:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  12222:             $changes{$action}{$newkey} = {
1.1271    raeburn  12223:                 type => $accesstype,
1.827     raeburn  12224:                 time => {
                   12225:                     start => $newstart,
                   12226:                     end   => $newend,
                   12227:                 },
                   12228:             };
1.1271    raeburn  12229:             if ($accesstype eq 'ip') {
                   12230:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   12231:             }
1.827     raeburn  12232:             my ($outcome,$deloutcome,$new_values,$translation) =
                   12233:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  12234:             unless ($outcome eq 'ok') {
                   12235:                 $errors .= $outcome.' ';
                   12236:             }
1.827     raeburn  12237:         }
1.1271    raeburn  12238:     }
                   12239:     if ($errors) {
                   12240:         $errors =~ s/\s$//;
                   12241:         return $errors;
1.827     raeburn  12242:     } else {
1.1271    raeburn  12243:         return 'ok';
1.827     raeburn  12244:     }
                   12245: }
                   12246: 
1.745     raeburn  12247: #------------------------------------------------------Get Marked as Read Only
                   12248: 
                   12249: sub get_marked_as_readonly {
                   12250:     my ($domain,$user,$what,$group) = @_;
                   12251:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 12252:     my @readonly_files;
1.629     banghart 12253:     my $cmp1=$what;
                   12254:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  12255:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   12256:         if (defined($group)) {
                   12257:             if ($file_name !~ m-^\Q$group\E/-) {
                   12258:                 next;
                   12259:             }
                   12260:         }
1.561     banghart 12261:         if (ref($value) eq "ARRAY"){
                   12262:             foreach my $stored_what (@{$value}) {
1.629     banghart 12263:                 my $cmp2=$stored_what;
1.759     albertel 12264:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  12265:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  12266:                 }
1.629     banghart 12267:                 if ($cmp1 eq $cmp2) {
1.561     banghart 12268:                     push(@readonly_files, $file_name);
1.745     raeburn  12269:                     last;
1.563     banghart 12270:                 } elsif (!defined($what)) {
                   12271:                     push(@readonly_files, $file_name);
1.745     raeburn  12272:                     last;
1.561     banghart 12273:                 }
                   12274:             }
1.745     raeburn  12275:         }
1.561     banghart 12276:     }
                   12277:     return @readonly_files;
                   12278: }
1.577     banghart 12279: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 12280: 
1.577     banghart 12281: sub get_marked_as_readonly_hash {
1.745     raeburn  12282:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 12283:     my %readonly_files;
1.745     raeburn  12284:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   12285:         if (defined($group)) {
                   12286:             if ($file_name !~ m-^\Q$group\E/-) {
                   12287:                 next;
                   12288:             }
                   12289:         }
1.577     banghart 12290:         if (ref($value) eq "ARRAY"){
                   12291:             foreach my $stored_what (@{$value}) {
1.745     raeburn  12292:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 12293:                     foreach my $lock_descriptor(@{$stored_what}) {
                   12294:                         if ($lock_descriptor eq 'graded') {
                   12295:                             $readonly_files{$file_name} = 'graded';
                   12296:                         } elsif ($lock_descriptor eq 'handback') {
                   12297:                             $readonly_files{$file_name} = 'handback';
                   12298:                         } else {
                   12299:                             if (!exists($readonly_files{$file_name})) {
                   12300:                                 $readonly_files{$file_name} = 'locked';
                   12301:                             }
                   12302:                         }
1.745     raeburn  12303:                     }
1.750     banghart 12304:                 } 
1.577     banghart 12305:             }
                   12306:         } 
                   12307:     }
                   12308:     return %readonly_files;
                   12309: }
1.559     banghart 12310: # ------------------------------------------------------------ Unmark as Read Only
                   12311: 
                   12312: sub unmark_as_readonly {
1.629     banghart 12313:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   12314:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  12315:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 12316:     $file_name = &declutter_portfile($file_name);
1.634     albertel 12317:     my $symb_crs = $what;
                   12318:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  12319:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 12320:     my ($tmp)=keys(%current_permissions);
                   12321:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  12322:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 12323:     foreach my $file (@readonly_files) {
1.759     albertel 12324: 	my $clean_file = &declutter_portfile($file);
                   12325: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 12326: 	my $current_locks = $current_permissions{$file};
1.563     banghart 12327:         my @new_locks;
                   12328:         my @del_keys;
                   12329:         if (ref($current_locks) eq "ARRAY"){
                   12330:             foreach my $locker (@{$current_locks}) {
1.632     albertel 12331:                 my $compare=$locker;
1.749     raeburn  12332:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  12333:                     $compare=join('',@{$locker});
1.746     raeburn  12334:                     if ($compare ne $symb_crs) {
                   12335:                         push(@new_locks, $locker);
                   12336:                     }
1.563     banghart 12337:                 }
                   12338:             }
1.650     albertel 12339:             if (scalar(@new_locks) > 0) {
1.563     banghart 12340:                 $current_permissions{$file} = \@new_locks;
                   12341:             } else {
                   12342:                 push(@del_keys, $file);
1.613     albertel 12343:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 12344:                 delete($current_permissions{$file});
1.563     banghart 12345:             }
                   12346:         }
1.561     banghart 12347:     }
1.613     albertel 12348:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 12349:     return;
                   12350: }
1.512     banghart 12351: 
1.17      www      12352: # ------------------------------------------------------------ Directory lister
                   12353: 
                   12354: sub dirlist {
1.955     raeburn  12355:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      12356:     $uri=~s/^\///;
                   12357:     $uri=~s/\/$//;
1.253     stredwic 12358:     my ($udom, $uname);
1.955     raeburn  12359:     if ($getuserdir) {
1.253     stredwic 12360:         $udom = $userdomain;
                   12361:         $uname = $username;
1.955     raeburn  12362:     } else {
                   12363:         (undef,$udom,$uname)=split(/\//,$uri);
                   12364:         if(defined($userdomain)) {
                   12365:             $udom = $userdomain;
                   12366:         }
                   12367:         if(defined($username)) {
                   12368:             $uname = $username;
                   12369:         }
1.253     stredwic 12370:     }
1.955     raeburn  12371:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 12372: 
1.955     raeburn  12373:     $dirRoot = $perlvar{'lonDocRoot'};
                   12374:     if (defined($getpropath)) {
                   12375:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 12376:         $dirRoot =~ s/\/$//;
1.955     raeburn  12377:     } elsif (defined($getuserdir)) {
                   12378:         my $subdir=$uname.'__';
                   12379:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   12380:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   12381:                    ."/$udom/$subdir/$uname";
                   12382:     } elsif (defined($alternateRoot)) {
                   12383:         $dirRoot = $alternateRoot;
1.751     banghart 12384:     }
1.253     stredwic 12385: 
                   12386:     if($udom) {
                   12387:         if($uname) {
1.1135    raeburn  12388:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  12389:             if ($uhome eq 'no_host') {
                   12390:                 return ([],'no_host');
                   12391:             }
1.955     raeburn  12392:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  12393:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  12394:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  12395:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  12396:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  12397:             } else {
                   12398:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   12399:             }
1.605     matthew  12400:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  12401:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  12402:                 @listing_results = split(/:/,$listing);
                   12403:             } else {
                   12404:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   12405:             }
1.1135    raeburn  12406:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  12407:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   12408:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   12409:                 return ([],$listing);
                   12410:             } else {
                   12411:                 return (\@listing_results);
1.1135    raeburn  12412:             }
1.955     raeburn  12413:         } elsif(!$alternateRoot) {
1.1136    raeburn  12414:             my (%allusers,%listerror);
1.841     albertel 12415: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  12416:  	    foreach my $tryserver (keys(%servers)) {
                   12417:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   12418:                                   &escape($udom),$tryserver);
                   12419:                 if ($listing eq 'unknown_cmd') {
                   12420: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   12421: 				      $udom, $tryserver);
                   12422:                 } else {
                   12423:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   12424:                 }
1.841     albertel 12425: 		if ($listing eq 'unknown_cmd') {
                   12426: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   12427: 				      $udom, $tryserver);
                   12428: 		    @listing_results = split(/:/,$listing);
                   12429: 		} else {
                   12430: 		    @listing_results =
                   12431: 			map { &unescape($_); } split(/:/,$listing);
                   12432: 		}
1.1136    raeburn  12433:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   12434:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   12435:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   12436:                     $listerror{$tryserver} = $listing;
                   12437:                 } else {
1.841     albertel 12438: 		    foreach my $line (@listing_results) {
                   12439: 			my ($entry) = split(/&/,$line,2);
                   12440: 			$allusers{$entry} = 1;
                   12441: 		    }
                   12442: 		}
1.253     stredwic 12443:             }
1.1136    raeburn  12444:             my @alluserslist=();
1.800     albertel 12445:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  12446:                 push(@alluserslist,$user.'&user');
1.253     stredwic 12447:             }
1.1318    droeschl 12448: 
                   12449:             if (!%listerror) {
                   12450:                 # no errors
                   12451:                 return (\@alluserslist);
                   12452:             } elsif (scalar(keys(%servers)) == 1) {
                   12453:                 # one library server, one error 
                   12454:                 my ($key) = keys(%listerror);
                   12455:                 return (\@alluserslist, $listerror{$key});
                   12456:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   12457:                 # con_lost indicates that we might miss data from at least one
                   12458:                 # library server
                   12459:                 return (\@alluserslist, 'con_lost');
                   12460:             } else {
                   12461:                 # multiple library servers and no con_lost -> data should be
                   12462:                 # complete. 
                   12463:                 return (\@alluserslist);
                   12464:             }
                   12465: 
1.253     stredwic 12466:         } else {
1.1136    raeburn  12467:             return ([],'missing username');
1.253     stredwic 12468:         }
1.955     raeburn  12469:     } elsif(!defined($getpropath)) {
1.1136    raeburn  12470:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   12471:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   12472:         return (\@all_domains);
1.955     raeburn  12473:     } else {
1.1136    raeburn  12474:         return ([],'missing domain');
1.275     stredwic 12475:     }
                   12476: }
                   12477: 
                   12478: # --------------------------------------------- GetFileTimestamp
                   12479: # This function utilizes dirlist and returns the date stamp for
                   12480: # when it was last modified.  It will also return an error of -1
                   12481: # if an error occurs
                   12482: 
                   12483: sub GetFileTimestamp {
1.955     raeburn  12484:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 12485:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   12486:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  12487:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   12488:                                     undef,$getuserdir);
                   12489:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   12490:         return -1;
                   12491:     }
                   12492:     if (ref($fileref) eq 'ARRAY') {
                   12493:         my @stats = split('&',$fileref->[0]);
1.375     matthew  12494:         # @stats contains first the filename, then the stat output
                   12495:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 12496:     } else {
                   12497:         return -1;
1.253     stredwic 12498:     }
1.26      www      12499: }
                   12500: 
1.712     albertel 12501: sub stat_file {
                   12502:     my ($uri) = @_;
1.787     albertel 12503:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 12504: 
1.955     raeburn  12505:     my ($udom,$uname,$file);
1.712     albertel 12506:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   12507: 	($udom,$uname,$file) =
1.811     albertel 12508: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 12509: 	$file = 'userfiles/'.$file;
                   12510:     }
                   12511:     if ($uri =~ m-^/res/-) {
                   12512: 	($udom,$uname) = 
1.807     albertel 12513: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 12514: 	$file = $uri;
                   12515:     }
                   12516: 
                   12517:     if (!$udom || !$uname || !$file) {
                   12518: 	# unable to handle the uri
                   12519: 	return ();
                   12520:     }
1.956     raeburn  12521:     my $getpropath;
                   12522:     if ($file =~ /^userfiles\//) {
                   12523:         $getpropath = 1;
                   12524:     }
1.1136    raeburn  12525:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   12526:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   12527:         return ();
                   12528:     } else {
                   12529:         if (ref($listref) eq 'ARRAY') {
                   12530:             my @stats = split('&',$listref->[0]);
                   12531: 	    shift(@stats); #filename is first
                   12532: 	    return @stats;
                   12533:         }
1.712     albertel 12534:     }
                   12535:     return ();
                   12536: }
                   12537: 
1.1313    raeburn  12538: # --------------------------------------------------------- recursedirs
                   12539: # Recursive function to traverse either a specific user's Authoring Space
                   12540: # or corresponding Published Resource Space, and populate the hash ref:
                   12541: # $dirhashref with URLs of all directories, and if $filehashref hash
                   12542: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
1.1503    raeburn  12543: # or .rights files in resource space, and .meta, .save, .log, .bak and
                   12544: # .rights files in Authoring Space.
1.1313    raeburn  12545: #
                   12546: # Inputs:
                   12547: #
                   12548: # $is_home - true if current server is home server for user's space
1.1503    raeburn  12549: # $recurse - if true will also traverse subdirectories recursively
                   12550: # $include - reference to hash containing allowed file extensions.  If provided,
                   12551: #             files which do not have a matching extension will be ignored.
                   12552: # $exclude - reference to hash containing excluded file extensions.  If provided,
                   12553: #             files which have a matching extension will be ignored.
                   12554: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
                   12555: #             directory with first file found (with acceptable extension).
1.1505    raeburn  12556: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
1.1313    raeburn  12557: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   12558: # $relpath - Current path (relative to top level).
                   12559: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   12560: # $filehashref - reference to hash to populate with URLs of files (Optional)
1.1532    raeburn  12561: # $getlastmod - if true, will set value for each key in innerhash in $filehashref
                   12562: #               to last modification time of file; value set to 1 otherwise.
1.1313    raeburn  12563: #
                   12564: # Returns: nothing
                   12565: #
                   12566: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   12567: #
                   12568: # Currently used by interface/londocs.pm to create linked select boxes for
                   12569: # directory and filename to import a Course "Author" resource into a course, and
                   12570: # also to create linked select boxes for Authoring Space and Directory to choose
                   12571: # save location for creation of a new "standard" problem from the Course Editor.
                   12572: #
                   12573: 
                   12574: sub recursedirs {
1.1532    raeburn  12575:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,
                   12576:         $relpath,$dirhashref,$filehashref,$getlastmod) = @_;
1.1313    raeburn  12577:     return unless (ref($dirhashref) eq 'HASH');
1.1503    raeburn  12578:     my $docroot = $perlvar{'lonDocRoot'};
1.1313    raeburn  12579:     my $currpath = $docroot.$toppath;
1.1503    raeburn  12580:     if ($relpath ne '') {
1.1313    raeburn  12581:         $currpath .= "/$relpath";
                   12582:     }
1.1503    raeburn  12583:     my ($savefile,$checkinc,$checkexc);
1.1532    raeburn  12584:     if (ref($filehashref) eq 'HASH') {
1.1313    raeburn  12585:         $savefile = 1;
                   12586:     }
1.1503    raeburn  12587:     if (ref($include) eq 'HASH') {
                   12588:         $checkinc = 1;
                   12589:     }
                   12590:     if (ref($exclude) eq 'HASH') {
                   12591:         $checkexc = 1;
                   12592:     }
1.1313    raeburn  12593:     if ($is_home) {
1.1505    raeburn  12594:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
1.1503    raeburn  12595:             my $filecount = 0;
1.1313    raeburn  12596:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   12597:                 next if ($item eq '');
                   12598:                 if (-d "$currpath/$item") {
                   12599:                     my $newpath;
1.1503    raeburn  12600:                     if ($relpath ne '') {
1.1313    raeburn  12601:                         $newpath = "$relpath/$item";
                   12602:                     } else {
                   12603:                         $newpath = $item;
                   12604:                     }
                   12605:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503    raeburn  12606:                     if ($recurse) {
1.1532    raeburn  12607:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,
                   12608:                                      $toppath,$newpath,$dirhashref,$filehashref,$getlastmod);
1.1503    raeburn  12609:                     }
                   12610:                 } elsif (($savefile) || ($relpath eq '')) {
                   12611:                     next if ($nonemptydir && $filecount);
                   12612:                     if ($checkinc || $checkexc) {
                   12613:                         my ($extension) = ($item =~ /\.(\w+)$/);
                   12614:                         if ($checkinc) {
                   12615:                             next unless ($extension && $include->{$extension});
                   12616:                         }
                   12617:                         if ($checkexc) {
                   12618:                             next if ($extension && $exclude->{$extension});
                   12619:                         }
                   12620:                     }
1.1505    raeburn  12621:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
1.1503    raeburn  12622:                         $dirhashref->{'/'} = 1;
                   12623:                     }
                   12624:                     if ($savefile) {
1.1532    raeburn  12625:                         my $value;
                   12626:                         if ($getlastmod) {
                   12627:                             ($value) = (stat("$currpath/$item"))[9];
                   12628:                         } else {
                   12629:                             $value = 1;
                   12630:                         }
1.1503    raeburn  12631:                         if ($relpath eq '') {
1.1532    raeburn  12632:                             $filehashref->{'/'}{$item} = $value
1.1503    raeburn  12633:                         } else {
1.1532    raeburn  12634:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = $value;
1.1313    raeburn  12635:                         }
                   12636:                     }
1.1503    raeburn  12637:                     $filecount ++;
1.1313    raeburn  12638:                 }
                   12639:             }
                   12640:             closedir($dirh);
                   12641:         }
                   12642:     } else {
1.1532    raeburn  12643:         my $url = $toppath;
                   12644:         if ($relpath ne '') {
                   12645:             $url = $toppath.'/'.$relpath;
                   12646:         }
                   12647:         my ($dirlistref,$listerror) = &dirlist($url);
1.1313    raeburn  12648:         my @dir_lines;
                   12649:         my $dirptr=16384;
                   12650:         if (ref($dirlistref) eq 'ARRAY') {
1.1503    raeburn  12651:             my $filecount = 0;
1.1313    raeburn  12652:             foreach my $dir_line (sort
                   12653:                               {
                   12654:                                   my ($afile)=split('&',$a,2);
                   12655:                                   my ($bfile)=split('&',$b,2);
                   12656:                                   return (lc($afile) cmp lc($bfile));
                   12657:                               } (@{$dirlistref})) {
                   12658:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   12659:                     split(/\&/,$dir_line,16);
                   12660:                 $item =~ s/\s+$//;
                   12661:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   12662:                 if ($dirptr&$testdir) {
                   12663:                     my $newpath;
                   12664:                     if ($relpath) {
                   12665:                         $newpath = "$relpath/$item";
                   12666:                     } else {
                   12667:                         $newpath = $item;
                   12668:                     }
                   12669:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503    raeburn  12670:                     if ($recurse) {
1.1532    raeburn  12671:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,
                   12672:                                      $toppath,$newpath,$dirhashref,$filehashref,$getlastmod);
1.1503    raeburn  12673:                     }
                   12674:                 } elsif (($savefile) || ($relpath eq '')) {
                   12675:                     next if ($nonemptydir && $filecount);
                   12676:                     if ($checkinc || $checkexc) {
1.1532    raeburn  12677:                         my ($extension) = ($item =~ /\.(\w+)$/);
1.1503    raeburn  12678:                         if ($checkinc) {
                   12679:                             next unless ($extension && $include->{$extension});
                   12680:                         }
                   12681:                         if ($checkexc) {
                   12682:                             next if ($extension && $exclude->{$extension});
                   12683:                         }
                   12684:                     }
                   12685:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
                   12686:                         $dirhashref->{'/'} = 1;
                   12687:                     }
                   12688:                     if ($savefile) {
1.1532    raeburn  12689:                         my $value;
                   12690:                         if ($getlastmod) {
                   12691:                             $value = $mtime;
                   12692:                         } else {
                   12693:                             $value = 1;
                   12694:                         }
1.1503    raeburn  12695:                         if ($relpath eq '') {
1.1532    raeburn  12696:                             $filehashref->{'/'}{$item} = $value;
1.1503    raeburn  12697:                         } else {
1.1532    raeburn  12698:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = $value;
1.1313    raeburn  12699:                         }
                   12700:                     }
1.1503    raeburn  12701:                     $filecount ++; 
1.1313    raeburn  12702:                 }
                   12703:             }
                   12704:         }
                   12705:     }
1.1505    raeburn  12706:     if ($addtopdir) {
                   12707:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
                   12708:             $dirhashref->{'/'} = 1;
                   12709:         }
                   12710:     }
1.1313    raeburn  12711:     return;
                   12712: }
                   12713: 
1.1503    raeburn  12714: sub priv_exclude {
                   12715:     return {
                   12716:              meta => 1,
                   12717:              save => 1,
                   12718:              log => 1,
                   12719:              bak => 1,
                   12720:              rights => 1,
                   12721:              DS_Store => 1,
                   12722:            };
                   12723: }
                   12724: 
1.1532    raeburn  12725: sub res_exclude {
                   12726:     return {
                   12727:              meta => 1,
                   12728:              subscription => 1,
                   12729:              rights => 1,
                   12730:            };
                   12731: }
                   12732: 
1.26      www      12733: # -------------------------------------------------------- Value of a Condition
                   12734: 
1.713     albertel 12735: # gets the value of a specific preevaluated condition
                   12736: #    stored in the string  $env{user.state.<cid>}
                   12737: # or looks up a condition reference in the bighash and if if hasn't
                   12738: # already been evaluated recurses into docondval to get the value of
                   12739: # the condition, then memoizing it to 
                   12740: #   $env{user.state.<cid>.<condition>}
1.40      www      12741: sub directcondval {
                   12742:     my $number=shift;
1.620     albertel 12743:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 12744: 	&Apache::lonuserstate::evalstate();
                   12745:     }
1.713     albertel 12746:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   12747: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   12748:     } elsif ($number =~ /^_/) {
                   12749: 	my $sub_condition;
                   12750: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12751: 		&GDBM_READER(),0640)) {
                   12752: 	    $sub_condition=$bighash{'conditions'.$number};
                   12753: 	    untie(%bighash);
                   12754: 	}
                   12755: 	my $value = &docondval($sub_condition);
1.949     raeburn  12756: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 12757: 	return $value;
                   12758:     }
1.620     albertel 12759:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   12760:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      12761:     } else {
                   12762:        return 2;
                   12763:     }
                   12764: }
                   12765: 
1.713     albertel 12766: # get the collection of conditions for this resource
1.26      www      12767: sub condval {
                   12768:     my $condidx=shift;
1.54      www      12769:     my $allpathcond='';
1.713     albertel 12770:     foreach my $cond (split(/\|/,$condidx)) {
                   12771: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   12772: 	    $allpathcond.=
                   12773: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   12774: 	}
1.191     harris41 12775:     }
1.54      www      12776:     $allpathcond=~s/\|$//;
1.713     albertel 12777:     return &docondval($allpathcond);
                   12778: }
                   12779: 
                   12780: #evaluates an expression of conditions
                   12781: sub docondval {
                   12782:     my ($allpathcond) = @_;
                   12783:     my $result=0;
                   12784:     if ($env{'request.course.id'}
                   12785: 	&& defined($allpathcond)) {
                   12786: 	my $operand='|';
                   12787: 	my @stack;
                   12788: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   12789: 	    if ($chunk eq '(') {
                   12790: 		push @stack,($operand,$result);
                   12791: 	    } elsif ($chunk eq ')') {
                   12792: 		my $before=pop @stack;
                   12793: 		if (pop @stack eq '&') {
                   12794: 		    $result=$result>$before?$before:$result;
                   12795: 		} else {
                   12796: 		    $result=$result>$before?$result:$before;
                   12797: 		}
                   12798: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   12799: 		$operand=$chunk;
                   12800: 	    } else {
                   12801: 		my $new=directcondval($chunk);
                   12802: 		if ($operand eq '&') {
                   12803: 		    $result=$result>$new?$new:$result;
                   12804: 		} else {
                   12805: 		    $result=$result>$new?$result:$new;
                   12806: 		}
                   12807: 	    }
                   12808: 	}
1.26      www      12809:     }
                   12810:     return $result;
1.421     albertel 12811: }
                   12812: 
                   12813: # ---------------------------------------------------- Devalidate courseresdata
                   12814: 
                   12815: sub devalidatecourseresdata {
                   12816:     my ($coursenum,$coursedomain)=@_;
                   12817:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12818:     &devalidate_cache_new('courseres',$hashid);
1.28      www      12819: }
                   12820: 
1.763     www      12821: 
1.200     www      12822: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     12823: #
                   12824: #  Parameters:
                   12825: #      $coursenum    - Number of the course.
                   12826: #      $coursedomain - Domain at which the course was created.
                   12827: #  Returns:
                   12828: #     A hash of the course parameters along (I think) with timestamps
                   12829: #     and version info.
1.877     foxr     12830: 
1.624     albertel 12831: sub get_courseresdata {
                   12832:     my ($coursenum,$coursedomain)=@_;
1.200     www      12833:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   12834:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12835:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 12836:     my %dumpreply;
1.417     albertel 12837:     unless (defined($cached)) {
1.624     albertel 12838: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 12839: 	$result=\%dumpreply;
1.251     albertel 12840: 	my ($tmp) = keys(%dumpreply);
                   12841: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 12842: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 12843: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   12844: 	    return $tmp;
1.416     albertel 12845: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 12846: 	    $result=undef;
1.599     albertel 12847: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 12848: 	}
                   12849:     }
1.624     albertel 12850:     return $result;
                   12851: }
                   12852: 
1.633     albertel 12853: sub devalidateuserresdata {
                   12854:     my ($uname,$udom)=@_;
                   12855:     my $hashid="$udom:$uname";
                   12856:     &devalidate_cache_new('userres',$hashid);
                   12857: }
                   12858: 
1.624     albertel 12859: sub get_userresdata {
                   12860:     my ($uname,$udom)=@_;
                   12861:     #most student don\'t have any data set, check if there is some data
                   12862:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   12863: 
                   12864:     my $hashid="$udom:$uname";
                   12865:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   12866:     if (!defined($cached)) {
                   12867: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   12868: 	$result=\%resourcedata;
                   12869: 	&do_cache_new('userres',$hashid,$result,600);
                   12870:     }
                   12871:     my ($tmp)=keys(%$result);
                   12872:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   12873: 	return $result;
                   12874:     }
                   12875:     #error 2 occurs when the .db doesn't exist
                   12876:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  12877:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   12878: 	    &logthis("<font color=\"blue\">WARNING:".
                   12879: 		     " Trying to get resource data for ".
                   12880: 		     $uname." at ".$udom.": ".
                   12881: 		     $tmp."</font>");
                   12882:         }
1.624     albertel 12883:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 12884: 	#&EXT_cache_set($udom,$uname);
                   12885: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 12886: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 12887:     }
                   12888:     return $tmp;
                   12889: }
1.879     foxr     12890: #----------------------------------------------- resdata - return resource data
                   12891: #  Purpose:
                   12892: #    Return resource data for either users or for a course.
                   12893: #  Parameters:
                   12894: #     $name      - Course/user name.
                   12895: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  12896: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  12897: #     $mapp      - decluttered URL of enclosing map  
                   12898: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   12899: #     $recurseup - Ref to array of map URLs, starting with map containing
                   12900: #                  $mapp up through hierarchy of nested maps to top level map.  
                   12901: #     $courseid  - CourseID (first part of param identifier).
                   12902: #     $modifier  - Middle part of param identifier.
                   12903: #     $what      - Last part of param identifier.
1.879     foxr     12904: #     @which     - Array of names of resources desired.
                   12905: #  Returns:
                   12906: #     The value of the first reasource in @which that is found in the
                   12907: #     resource hash.
                   12908: #  Exceptional Conditions:
                   12909: #     If the $type passed in is not valid (not the string 'course' or 
                   12910: #     'user', an undefined  reference is returned.
                   12911: #     If none of the resources are found, an undef is returned
1.624     albertel 12912: sub resdata {
1.1301    raeburn  12913:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   12914:         $modifier,$what,@which)=@_;
1.624     albertel 12915:     my $result;
                   12916:     if ($type eq 'course') {
                   12917: 	$result=&get_courseresdata($name,$domain);
                   12918:     } elsif ($type eq 'user') {
                   12919: 	$result=&get_userresdata($name,$domain);
                   12920:     }
                   12921:     if (!ref($result)) { return $result; }    
1.251     albertel 12922:     foreach my $item (@which) {
1.1301    raeburn  12923:         if ($item->[1] eq 'course') {
                   12924:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   12925:                 unless ($$recursed) {
1.1302    raeburn  12926:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  12927:                     $$recursed = 1;
                   12928:                 }
                   12929:                 foreach my $item (@${recurseup}) {
                   12930:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   12931:                     last if (defined($result->{$norecursechk}));
                   12932:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   12933:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   12934:                 }
                   12935:             }
                   12936:         }
                   12937:         if (defined($result->{$item->[0]})) {
1.927     albertel 12938: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12939: 	}
1.250     albertel 12940:     }
1.291     albertel 12941:     return undef;
1.200     www      12942: }
                   12943: 
1.1360    raeburn  12944: sub get_domain_lti {
                   12945:     my ($cdom,$context) = @_;
1.1483    raeburn  12946:     my ($name,$cachename,%lti);
1.1360    raeburn  12947:     if ($context eq 'consumer') {
                   12948:         $name = 'ltitools';
                   12949:     } elsif ($context eq 'provider') {
                   12950:         $name = 'lti';
1.1483    raeburn  12951:     } elsif ($context eq 'linkprot') {
                   12952:         $name = 'ltisec';
1.1360    raeburn  12953:     } else {
                   12954:         return %lti;
                   12955:     }
1.1483    raeburn  12956:     if ($context eq 'linkprot') {
                   12957:         $cachename = $context;
                   12958:     } else {
                   12959:         $cachename = $name;
                   12960:     }
                   12961:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298    raeburn  12962:     if (defined($cached)) {
                   12963:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12964:             %lti = %{$result};
1.1298    raeburn  12965:         }
                   12966:     } else {
1.1360    raeburn  12967:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12968:         if (ref($domconfig{$name}) eq 'HASH') {
1.1483    raeburn  12969:             if ($context eq 'linkprot') {
                   12970:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12971:                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12972:                 }
                   12973:             } else {
                   12974:                 %lti = %{$domconfig{$name}};
                   12975:             }
1.1298    raeburn  12976:         }
                   12977:         my $cachetime = 24*60*60;
1.1483    raeburn  12978:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298    raeburn  12979:     }
1.1360    raeburn  12980:     return %lti;
1.1298    raeburn  12981: }
                   12982: 
1.1463    raeburn  12983: sub get_course_lti {
1.1510    raeburn  12984:     my ($cnum,$cdom,$context) = @_;
                   12985:     my ($name,$cachename,%lti);
                   12986:     if ($context eq 'consumer') {
                   12987:         $name = 'ltitools';
                   12988:         $cachename = 'courseltitools';
                   12989:     } elsif ($context eq 'provider') {
                   12990:         $name = 'lti';
                   12991:         $cachename = 'courselti';
                   12992:     } else {
                   12993:         return %lti;
                   12994:     }
1.1463    raeburn  12995:     my $hashid=$cdom.'_'.$cnum;
1.1510    raeburn  12996:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
1.1463    raeburn  12997:     if (defined($cached)) {
                   12998:         if (ref($result) eq 'HASH') {
1.1510    raeburn  12999:             %lti = %{$result};
1.1463    raeburn  13000:         }
                   13001:     } else {
1.1510    raeburn  13002:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
1.1463    raeburn  13003:         my $cachetime = 24*60*60;
1.1510    raeburn  13004:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
1.1463    raeburn  13005:     }
1.1510    raeburn  13006:     return %lti;
1.1463    raeburn  13007: }
                   13008: 
1.1479    raeburn  13009: sub courselti_itemid {
                   13010:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   13011:     my ($chome,$itemid);
                   13012:     $chome = &homeserver($cnum,$cdom);
                   13013:     return if ($chome eq 'no_host');
                   13014:     if (ref($params) eq 'HASH') {
                   13015:         my $rep;
                   13016:         if (grep { $_ eq $chome } current_machine_ids()) {
                   13017:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   13018:         } else {
                   13019:             my $escurl = &escape($url);
                   13020:             my $escmethod = &escape($method);
                   13021:             my $items = &freeze_escape($params);
                   13022:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   13023:         }
                   13024:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   13025:                 ($rep eq 'unknown_cmd')) {
                   13026:             $itemid = $rep;
                   13027:         }
                   13028:     }
                   13029:     return $itemid;
                   13030: }
                   13031: 
                   13032: sub domainlti_itemid {
                   13033:     my ($cdom,$url,$method,$params,$context) = @_;
                   13034:     my ($primary_id,$itemid);
                   13035:     $primary_id = &domain($cdom,'primary');
                   13036:     return if ($primary_id eq '');
                   13037:     if (ref($params) eq 'HASH') {
                   13038:         my $rep;
                   13039:         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   13040:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   13041:         } else {
                   13042:             my $cnum = '';
                   13043:             my $escurl = &escape($url);
                   13044:             my $escmethod = &escape($method);
                   13045:             my $items = &freeze_escape($params);
                   13046:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   13047:         }
                   13048:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   13049:                 ($rep eq 'unknown_cmd')) {
                   13050:             $itemid = $rep;
                   13051:         }
                   13052:     }
                   13053:     return $itemid;
                   13054: }
                   13055: 
1.1513    raeburn  13056: sub get_ltitools_id {
                   13057:     my ($context,$cdom,$cnum,$title) = @_;
                   13058:     my ($lockhash,$tries,$gotlock,$id,$error);
                   13059: 
                   13060:     # get lock on ltitools db
                   13061:     $lockhash = {
                   13062:                    lock => $env{'user.name'}.
                   13063:                            ':'.$env{'user.domain'},
                   13064:                 };
                   13065:     $tries = 0;
                   13066:     if ($context eq 'domain') {
                   13067:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   13068:     } else {
                   13069:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   13070:     }
                   13071:     while (($gotlock ne 'ok') && ($tries<10)) {
                   13072:         $tries ++;
                   13073:         sleep (0.1);
                   13074:         if ($context eq 'domain') {
                   13075:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   13076:         } else {
                   13077:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   13078:         }
                   13079:     }
                   13080:     if ($gotlock eq 'ok') {
                   13081:         my %currids;
                   13082:         if ($context eq 'domain') {
                   13083:             %currids = &dump_dom('ltitools',$cdom);
                   13084:         } else {
                   13085:             %currids = &dump('ltitools',$cdom,$cnum);
                   13086:         }
                   13087:         if ($currids{'lock'}) {
                   13088:             delete($currids{'lock'});
                   13089:             if (keys(%currids)) {
                   13090:                 my @curr = sort { $a <=> $b } keys(%currids);
                   13091:                 if ($curr[-1] =~ /^\d+$/) {
                   13092:                     $id = 1 + $curr[-1];
                   13093:                 }
                   13094:             } else {
                   13095:                 $id = 1;
                   13096:             }
                   13097:             if ($id) {
                   13098:                 if ($context eq 'domain') {
                   13099:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
                   13100:                         $error = 'nostore';
                   13101:                     }
                   13102:                 } else {
                   13103:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
                   13104:                         $error = 'nostore';
                   13105:                     }
                   13106:                 }
                   13107:             } else {
                   13108:                 $error = 'nonumber';
                   13109:             }
                   13110:         }
                   13111:         my $dellockoutcome;
                   13112:         if ($context eq 'domain') {
                   13113:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
                   13114:         } else {
                   13115:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
                   13116:         }
                   13117:     } else {
                   13118:         $error = 'nolock';
                   13119:     }
                   13120:     return ($id,$error);
                   13121: }
                   13122: 
1.1496    raeburn  13123: sub count_supptools {
                   13124:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
                   13125:     my $hashid=$cnum.':'.$cdom;
                   13126:     my ($numexttools,$cached);
                   13127:     unless ($ignorecache) {
                   13128:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
                   13129:     }
                   13130:     unless (defined($cached)) {
                   13131:         my $chome=&homeserver($cnum,$cdom);
                   13132:         $numexttools = 0;
                   13133:         unless ($chome eq 'no_host') {
1.1500    raeburn  13134:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
1.1496    raeburn  13135:             if (ref($supplemental) eq 'HASH') {
                   13136:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   13137:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   13138:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   13139:                             $numexttools ++;
                   13140:                         }
                   13141:                     }
                   13142:                 }
                   13143:             }
                   13144:         }
                   13145:         &do_cache_new('supptools',$hashid,$numexttools,600);
                   13146:     }
                   13147:     return $numexttools;
                   13148: }
                   13149: 
                   13150: sub has_unhidden_suppfiles {
1.1498    raeburn  13151:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
1.1236    raeburn  13152:     my $hashid=$cnum.':'.$cdom;
1.1496    raeburn  13153:     my ($showsupp,$cached);
1.1236    raeburn  13154:     unless ($ignorecache) {
1.1496    raeburn  13155:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
1.1236    raeburn  13156:     }
                   13157:     unless (defined($cached)) {
                   13158:         my $chome=&homeserver($cnum,$cdom);
                   13159:         unless ($chome eq 'no_host') {
1.1500    raeburn  13160:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
1.1496    raeburn  13161:             if (ref($supplemental) eq 'HASH') {
                   13162:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   13163:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   13164:                         next if ($key =~ /\.sequence$/);
                   13165:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   13166:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   13167:                                 unless ($supplemental->{'hidden'}->{$id}) {
                   13168:                                     $showsupp = 1;
                   13169:                                     last;
                   13170:                                 }
                   13171:                             }
                   13172:                         }
                   13173:                         last if ($showsupp);
                   13174:                     }
                   13175:                 }
                   13176:             }
1.1236    raeburn  13177:         }
1.1496    raeburn  13178:         &do_cache_new('showsupp',$hashid,$showsupp,600);
1.1236    raeburn  13179:     }
1.1496    raeburn  13180:     return $showsupp;
                   13181: }
                   13182: 
1.379     matthew  13183: #
                   13184: # EXT resource caching routines
                   13185: #
                   13186: 
1.1302    raeburn  13187: {
                   13188: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   13189: #
                   13190: # The course for which we cache
                   13191: my $cachedmapkey='';
                   13192: # The cached recursive maps for this course
                   13193: my %cachedmaps=();
                   13194: # When this was last done
                   13195: my $cachedmaptime='';
                   13196: 
1.379     matthew  13197: sub clear_EXT_cache_status {
1.383     albertel 13198:     &delenv('cache.EXT.');
1.379     matthew  13199: }
                   13200: 
                   13201: sub EXT_cache_status {
                   13202:     my ($target_domain,$target_user) = @_;
1.383     albertel 13203:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 13204:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  13205:         # We know already the user has no data
                   13206:         return 1;
                   13207:     } else {
                   13208:         return 0;
                   13209:     }
                   13210: }
                   13211: 
                   13212: sub EXT_cache_set {
                   13213:     my ($target_domain,$target_user) = @_;
1.383     albertel 13214:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  13215:     #&appenv({$cachename => time});
1.379     matthew  13216: }
                   13217: 
1.28      www      13218: # --------------------------------------------------------- Value of a Variable
1.58      www      13219: sub EXT {
1.715     albertel 13220: 
1.1461    raeburn  13221:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68      www      13222:     unless ($varname) { return ''; }
1.218     albertel 13223:     #get real user name/domain, courseid and symb
                   13224:     my $courseid;
1.359     albertel 13225:     my $publicuser;
1.427     www      13226:     if ($symbparm) {
                   13227: 	$symbparm=&get_symb_from_alias($symbparm);
                   13228:     }
1.218     albertel 13229:     if (!($uname && $udom)) {
1.790     albertel 13230:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 13231:       if (!$symbparm) {	$symbparm=$cursymb; }
                   13232:     } else {
1.620     albertel 13233: 	$courseid=$env{'request.course.id'};
1.218     albertel 13234:     }
1.48      www      13235:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   13236:     my $rest;
1.320     albertel 13237:     if (defined($therest[0])) {
1.48      www      13238:        $rest=join('.',@therest);
                   13239:     } else {
                   13240:        $rest='';
                   13241:     }
1.320     albertel 13242: 
1.57      www      13243:     my $qualifierrest=$qualifier;
                   13244:     if ($rest) { $qualifierrest.='.'.$rest; }
                   13245:     my $spacequalifierrest=$space;
                   13246:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      13247:     if ($realm eq 'user') {
1.48      www      13248: # --------------------------------------------------------------- user.resource
                   13249: 	if ($space eq 'resource') {
1.651     albertel 13250: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   13251: 		  || defined($Apache::lonhomework::parsing_a_task))
                   13252: 		 &&
1.1469    raeburn  13253: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 13254: 		# if we are in the middle of processing the resource the
                   13255: 		# get the value we are planning on committing
                   13256:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   13257:                     return $Apache::lonhomework::results{$qualifierrest};
                   13258:                 } else {
                   13259:                     return $Apache::lonhomework::history{$qualifierrest};
                   13260:                 }
1.335     albertel 13261: 	    } else {
1.359     albertel 13262: 		my %restored;
1.620     albertel 13263: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 13264: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   13265: 		} else {
                   13266: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   13267: 		}
1.335     albertel 13268: 		return $restored{$qualifierrest};
                   13269: 	    }
1.48      www      13270: # ----------------------------------------------------------------- user.access
                   13271:         } elsif ($space eq 'access') {
1.218     albertel 13272: 	    # FIXME - not supporting calls for a specific user
1.48      www      13273:             return &allowed($qualifier,$rest);
                   13274: # ------------------------------------------ user.preferences, user.environment
                   13275:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 13276: 	    if (($uname eq $env{'user.name'}) &&
                   13277: 		($udom eq $env{'user.domain'})) {
                   13278: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 13279: 	    } else {
1.359     albertel 13280: 		my %returnhash;
                   13281: 		if (!$publicuser) {
                   13282: 		    %returnhash=&userenvironment($udom,$uname,
                   13283: 						 $qualifierrest);
                   13284: 		}
1.218     albertel 13285: 		return $returnhash{$qualifierrest};
                   13286: 	    }
1.48      www      13287: # ----------------------------------------------------------------- user.course
                   13288:         } elsif ($space eq 'course') {
1.218     albertel 13289: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 13290:             return $env{join('.',('request.course',$qualifier))};
1.48      www      13291: # ------------------------------------------------------------------- user.role
                   13292:         } elsif ($space eq 'role') {
1.218     albertel 13293: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 13294:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      13295:             if ($qualifier eq 'value') {
                   13296: 		return $role;
                   13297:             } elsif ($qualifier eq 'extent') {
                   13298:                 return $where;
                   13299:             }
                   13300: # ----------------------------------------------------------------- user.domain
                   13301:         } elsif ($space eq 'domain') {
1.218     albertel 13302:             return $udom;
1.48      www      13303: # ------------------------------------------------------------------- user.name
                   13304:         } elsif ($space eq 'name') {
1.218     albertel 13305:             return $uname;
1.48      www      13306: # ---------------------------------------------------- Any other user namespace
1.29      www      13307:         } else {
1.359     albertel 13308: 	    my %reply;
                   13309: 	    if (!$publicuser) {
                   13310: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   13311: 	    }
                   13312: 	    return $reply{$qualifierrest};
1.48      www      13313:         }
1.236     www      13314:     } elsif ($realm eq 'query') {
                   13315: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 13316:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   13317: 						[$spacequalifierrest]);
1.620     albertel 13318: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      13319:    } elsif ($realm eq 'request') {
1.48      www      13320: # ------------------------------------------------------------- request.browser
                   13321:         if ($space eq 'browser') {
1.1145    bisitz   13322:             return $env{'browser.'.$qualifier};
1.57      www      13323: # ------------------------------------------------------------ request.filename
                   13324:         } else {
1.620     albertel 13325:             return $env{'request.'.$spacequalifierrest};
1.29      www      13326:         }
1.28      www      13327:     } elsif ($realm eq 'course') {
1.48      www      13328: # ---------------------------------------------------------- course.description
1.620     albertel 13329:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      13330:     } elsif ($realm eq 'resource') {
1.165     www      13331: 
1.620     albertel 13332: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 13333: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   13334: 	}
1.693     albertel 13335: 
1.1232    raeburn  13336:         if ($qualifier eq '') {
                   13337: 	    if ($space eq 'title') {
                   13338: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   13339: 	        return &gettitle($symbparm);
                   13340: 	    }
1.693     albertel 13341: 	
1.1232    raeburn  13342: 	    if ($space eq 'map') {
                   13343: 	        my ($map) = &decode_symb($symbparm);
                   13344: 	        return &symbread($map);
                   13345: 	    }
                   13346:             if ($space eq 'maptitle') {
                   13347:                 my ($map) = &decode_symb($symbparm);
                   13348:                 return &gettitle($map);
                   13349:             }
                   13350: 	    if ($space eq 'filename') {
                   13351: 	        if ($symbparm) {
                   13352: 		    return &clutter((&decode_symb($symbparm))[2]);
                   13353: 	        }
                   13354: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 13355: 	    }
1.1232    raeburn  13356: 
1.1233    raeburn  13357:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   13358:                 if ($space eq 'visibleparts') {
                   13359:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   13360:                     my $item;
                   13361:                     if (ref($navmap)) {
                   13362:                         my $res = $navmap->getBySymb($symbparm);
                   13363:                         my $parts = $res->parts();
                   13364:                         if (ref($parts) eq 'ARRAY') {
                   13365:                             $item = join(',',@{$parts});
                   13366:                         }
                   13367:                         undef($navmap);
1.1232    raeburn  13368:                     }
1.1233    raeburn  13369:                     return $item;
1.1232    raeburn  13370:                 }
                   13371:             }
                   13372:         }
1.693     albertel 13373: 
1.1301    raeburn  13374: 	my ($section, $group, @groups, @recurseup, $recursed);
1.1461    raeburn  13375:         if (ref($recurseupref) eq 'ARRAY') {
                   13376:             @recurseup = @{$recurseupref};
                   13377:             $recursed = 1;
                   13378:         }
1.1301    raeburn  13379: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  13380:         if (($courseid eq '') && ($cid)) {
                   13381:             $courseid = $cid;
                   13382:         }
                   13383: 	if (($symbparm && $courseid) && 
                   13384: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      13385: 
1.218     albertel 13386: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      13387: 
1.60      www      13388: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 13389: 	    my $symbp=$symbparm;
1.1301    raeburn  13390: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 13391: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  13392:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 13393: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 13394: 	    if (($env{'user.name'} eq $uname) &&
                   13395: 		($env{'user.domain'} eq $udom)) {
                   13396: 		$section=$env{'request.course.sec'};
1.733     raeburn  13397:                 @groups = split(/:/,$env{'request.course.groups'});  
                   13398:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 13399: 	    } else {
1.539     albertel 13400: 		if (! defined($usection)) {
1.551     albertel 13401: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 13402: 		} else {
                   13403: 		    $section = $usection;
                   13404: 		}
1.733     raeburn  13405:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 13406: 	    }
                   13407: 
                   13408: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   13409: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  13410:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 13411: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   13412: 
1.593     albertel 13413: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 13414: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  13415:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 13416: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      13417: 
1.60      www      13418: # ----------------------------------------------------------- first, check user
1.624     albertel 13419: 
1.1301    raeburn  13420: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   13421:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 13422: 				       ([$courselevelr,'resource'],
                   13423: 					[$courselevelm,'map'     ],
1.1301    raeburn  13424:                                         [$courseleveli,'map'     ],
1.927     albertel 13425: 					[$courselevel, 'course'  ]));
1.931     albertel 13426: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      13427: 
1.594     albertel 13428: # ------------------------------------------------ second, check some of course
1.684     raeburn  13429:             my $coursereply;
1.691     raeburn  13430:             if (@groups > 0) {
                   13431:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  13432:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   13433:                                        $mapp,\$recursed,\@recurseup);
                   13434:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  13435:             }
1.96      www      13436: 
1.684     raeburn  13437: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 13438: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  13439: 				  'course',$mapp,\$recursed,\@recurseup,
                   13440:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 13441: 				  ([$seclevelr,   'resource'],
                   13442: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  13443:                                    [$secleveli,   'map'     ],
1.927     albertel 13444: 				   [$seclevel,    'course'  ],
                   13445: 				   [$courselevelr,'resource']));
                   13446: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      13447: 
1.60      www      13448: # ------------------------------------------------------ third, check map parms
1.218     albertel 13449: 	    my %parmhash=();
                   13450: 	    my $thisparm='';
                   13451: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 13452: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 13453: 		    &GDBM_READER(),0640)) {
1.218     albertel 13454: 		$thisparm=$parmhash{$symbparm};
                   13455: 		untie(%parmhash);
                   13456: 	    }
1.927     albertel 13457: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 13458: 	}
1.594     albertel 13459: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  13460:  
                   13461:         my $what = $spacequalifierrest;
                   13462: 	$what=~s/\./\_/;
1.282     albertel 13463: 	my $filename;
                   13464: 	if (!$symbparm) { $symbparm=&symbread(); }
                   13465: 	if ($symbparm) {
1.409     www      13466: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 13467: 	} else {
1.620     albertel 13468: 	    $filename=$env{'request.filename'};
1.282     albertel 13469: 	}
1.1362    raeburn  13470:         my $toolsymb;
                   13471:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   13472:             $toolsymb = $symbparm;
                   13473:         }
                   13474: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 13475: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  13476: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 13477: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      13478: 
1.1301    raeburn  13479: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 13480: 	if ($symbparm && defined($courseid) && 
1.620     albertel 13481: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 13482: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   13483: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  13484: 				     'course',$mapp,\$recursed,\@recurseup,
                   13485:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 13486: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  13487:                                       [$courseleveli,'map'   ],
1.927     albertel 13488: 				      [$courselevel, 'course']));
                   13489: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 13490: 	}
1.145     www      13491: # ------------------------------------------------------------------ Cascade up
1.218     albertel 13492: 	unless ($space eq '0') {
1.336     albertel 13493: 	    my @parts=split(/_/,$space);
                   13494: 	    my $id=pop(@parts);
                   13495: 	    my $part=join('_',@parts);
                   13496: 	    if ($part eq '') { $part='0'; }
1.927     albertel 13497: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 13498: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  13499: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 13500: 	}
1.395     albertel 13501: 	if ($recurse) { return undef; }
1.1362    raeburn  13502: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 13503: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      13504: # ---------------------------------------------------- Any other user namespace
                   13505:     } elsif ($realm eq 'environment') {
                   13506: # ----------------------------------------------------------------- environment
1.620     albertel 13507: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   13508: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 13509: 	} else {
1.770     albertel 13510: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   13511: 		return '';
                   13512: 	    }
1.219     albertel 13513: 	    my %returnhash=&userenvironment($udom,$uname,
                   13514: 					    $spacequalifierrest);
                   13515: 	    return $returnhash{$spacequalifierrest};
                   13516: 	}
1.28      www      13517:     } elsif ($realm eq 'system') {
1.48      www      13518: # ----------------------------------------------------------------- system.time
                   13519: 	if ($space eq 'time') {
                   13520: 	    return time;
                   13521:         }
1.696     albertel 13522:     } elsif ($realm eq 'server') {
                   13523: # ----------------------------------------------------------------- system.time
                   13524: 	if ($space eq 'name') {
                   13525: 	    return $ENV{'SERVER_NAME'};
                   13526:         }
1.1415    raeburn  13527:     } elsif ($realm eq 'client') {
                   13528:         if ($space eq 'remote_addr') {
1.1441    raeburn  13529:             return &get_requestor_ip();
1.1415    raeburn  13530:         }
1.28      www      13531:     }
1.48      www      13532:     return '';
1.61      www      13533: }
                   13534: 
1.927     albertel 13535: sub get_reply {
                   13536:     my ($reply_value) = @_;
1.940     raeburn  13537:     if (ref($reply_value) eq 'ARRAY') {
                   13538:         if (wantarray) {
                   13539: 	    return @$reply_value;
                   13540:         }
                   13541:         return $reply_value->[0];
                   13542:     } else {
                   13543:         return $reply_value;
1.927     albertel 13544:     }
                   13545: }
                   13546: 
1.691     raeburn  13547: sub check_group_parms {
1.1301    raeburn  13548:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   13549:         $recursed,$recurseupref) = @_;
                   13550:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   13551:                   [$what,'course']);
                   13552:     my $coursereply;
1.691     raeburn  13553:     foreach my $group (@{$groups}) {
1.1301    raeburn  13554:         my @groupitems = ();
1.691     raeburn  13555:         foreach my $level (@levels) {
1.927     albertel 13556:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   13557:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  13558:         }
1.1301    raeburn  13559:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   13560:                                    $env{'course.'.$courseid.'.domain'},
                   13561:                                    'course',$mapp,$recursed,$recurseupref,
                   13562:                                    $courseid,'.['.$group.'].',$what,
                   13563:                                    @groupitems);
                   13564:         last if (defined($coursereply));
1.691     raeburn  13565:     }
                   13566:     return $coursereply;
                   13567: }
                   13568: 
1.1301    raeburn  13569: sub get_map_hierarchy {
1.1302    raeburn  13570:     my ($mapname,$courseid) = @_;
                   13571:     my @recurseup = ();
1.1301    raeburn  13572:     if ($mapname) {
1.1302    raeburn  13573:         if (($cachedmapkey eq $courseid) &&
                   13574:             (abs($cachedmaptime-time)<5)) {
                   13575:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   13576:                 return @{$cachedmaps{$mapname}};
                   13577:             }
                   13578:         }
1.1301    raeburn  13579:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13580:         if (ref($navmap)) {
                   13581:             @recurseup = $navmap->recurseup_maps($mapname);
                   13582:             undef($navmap);
1.1302    raeburn  13583:             $cachedmaps{$mapname} = \@recurseup;
                   13584:             $cachedmaptime=time;
                   13585:             $cachedmapkey=$courseid;
1.1301    raeburn  13586:         }
                   13587:     }
                   13588:     return @recurseup;
                   13589: }
                   13590: 
1.1302    raeburn  13591: }
                   13592: 
1.691     raeburn  13593: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  13594:     my ($courseid,@groups) = @_;
                   13595:     @groups = sort(@groups);
1.691     raeburn  13596:     return @groups;
                   13597: }
                   13598: 
1.395     albertel 13599: sub packages_tab_default {
1.1362    raeburn  13600:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 13601:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 13602: 
                   13603:     my (@extension,@specifics,$do_default);
1.1362    raeburn  13604:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 13605: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 13606: 	if ($pack_type eq 'default') {
                   13607: 	    $do_default=1;
                   13608: 	} elsif ($pack_type eq 'extension') {
                   13609: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 13610: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 13611: 	    # only look at packages defaults for packages that this id is
1.738     albertel 13612: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   13613: 	}
                   13614:     }
                   13615:     # first look for a package that matches the requested part id
                   13616:     foreach my $package (@specifics) {
                   13617: 	my (undef,$pack_type,$pack_part)=@{$package};
                   13618: 	next if ($pack_part ne $part);
                   13619: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   13620: 	    return $packagetab{"$pack_type&$name&default"};
                   13621: 	}
                   13622:     }
                   13623:     # look for any possible matching non extension_ package
                   13624:     foreach my $package (@specifics) {
                   13625: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 13626: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   13627: 	    return $packagetab{"$pack_type&$name&default"};
                   13628: 	}
1.585     albertel 13629: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 13630: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   13631: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 13632: 	}
                   13633:     }
1.738     albertel 13634:     # look for any posible extension_ match
                   13635:     foreach my $package (@extension) {
                   13636: 	my ($package,$pack_type)=@{$package};
                   13637: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   13638: 	    return $packagetab{"$pack_type&$name&default"};
                   13639: 	}
                   13640: 	if (defined($packagetab{$package."&$name&default"})) {
                   13641: 	    return $packagetab{$package."&$name&default"};
                   13642: 	}
                   13643:     }
                   13644:     # look for a global default setting
                   13645:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   13646: 	return $packagetab{"default&$name&default"};
                   13647:     }
1.395     albertel 13648:     return undef;
                   13649: }
                   13650: 
1.334     albertel 13651: sub add_prefix_and_part {
                   13652:     my ($prefix,$part)=@_;
                   13653:     my $keyroot;
                   13654:     if (defined($prefix) && $prefix !~ /^__/) {
                   13655: 	# prefix that has a part already
                   13656: 	$keyroot=$prefix;
                   13657:     } elsif (defined($prefix)) {
                   13658: 	# prefix that is missing a part
                   13659: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   13660:     } else {
                   13661: 	# no prefix at all
                   13662: 	if (defined($part)) { $keyroot='_'.$part; }
                   13663:     }
                   13664:     return $keyroot;
                   13665: }
                   13666: 
1.71      www      13667: # ---------------------------------------------------------------- Get metadata
                   13668: 
1.599     albertel 13669: my %metaentry;
1.1070    www      13670: my %importedpartids;
1.1369    raeburn  13671: my %importedrespids;
1.71      www      13672: sub metadata {
1.1362    raeburn  13673:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      13674:     $uri=&declutter($uri);
1.288     albertel 13675:     # if it is a non metadata possible uri return quickly
1.529     albertel 13676:     if (($uri eq '') || 
                   13677: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  13678: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  13679:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 13680: 	return undef;
                   13681:     }
1.1261    raeburn  13682:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 13683: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 13684: 	return undef;
1.288     albertel 13685:     }
1.73      www      13686:     my $filename=$uri;
                   13687:     $uri=~s/\.meta$//;
1.172     www      13688: #
                   13689: # Is the metadata already cached?
1.177     www      13690: # Look at timestamp of caching
1.172     www      13691: # Everything is cached by the main uri, libraries are never directly cached
                   13692: #
1.428     albertel 13693:     if (!defined($liburi)) {
1.599     albertel 13694: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 13695: 	if (defined($cached)) { return $result->{':'.$what}; }
                   13696:     }
1.1362    raeburn  13697: 
                   13698: #
                   13699: # If the uri is for an external tool the file from
                   13700: # which metadata should be retrieved depends on whether
                   13701: # the tool had been configured to be gradable (set in the Course
                   13702: # Editor or Resource Editor).
                   13703: #
                   13704: # If a valid symb has been included as the third arg in the call
                   13705: # to &metadata() that can be used to retrieve the value of
                   13706: # parameter_0_gradable set for the resource, and included in the
                   13707: # uploaded map containing the tool. The value is retrieved via
                   13708: # &EXT(), if a valid symb is available.  Otherwise the value of
                   13709: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  13710: # is retrieved via &get().
                   13711: #
                   13712: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   13713: # hiddenresource and encrypturl (during course initialization)
                   13714: # the map-level parameter for resource.0.gradable included in the 
                   13715: # uploaded map containing the tool will not yet have been stored
                   13716: # in the user_course_parms.db file for the user's session, so in 
                   13717: # this case fall back to retrieving gradable status from the
                   13718: # exttool_$marker.db file.
1.1362    raeburn  13719: #
                   13720: # In order to avoid an infinite loop, &metadata() will return
                   13721: # before a call to &EXT(), if the uri is for an external tool
                   13722: # and the $what for which metadata is being requested is
                   13723: # parameter_0_gradable or 0_gradable.
                   13724: #
                   13725: 
                   13726:     if ($uri =~ /ext\.tool$/) {
                   13727:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   13728:             return;
                   13729:         } else {
                   13730:             my ($checked,$use_passback);
                   13731:             if ($toolsymb ne '') {
                   13732:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  13733:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  13734:                     $checked = 1;
                   13735:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   13736:                         $use_passback = 1;
                   13737:                     }
                   13738:                 }
                   13739:             }
                   13740:             unless ($checked) {
                   13741:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   13742:                 $marker=~s/\D//g;
1.1363    raeburn  13743:                 if ($marker) {
1.1362    raeburn  13744:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   13745:                     $use_passback = $toolsettings{'gradable'};
                   13746:                 }
                   13747:             }
                   13748:             if ($use_passback) {
                   13749:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   13750:             } else {
                   13751:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   13752:             }
                   13753:         }
                   13754:     }
                   13755: 
1.428     albertel 13756:     {
1.1069    www      13757: # Imported parts would go here
1.1369    raeburn  13758:         my @origfiletagids=();
1.1069    www      13759:         my $importedparts=0;
1.1369    raeburn  13760: 
                   13761: # Imported responseids would go here
                   13762:         my $importedresponses=0;
1.172     www      13763: #
                   13764: # Is this a recursive call for a library?
                   13765: #
1.599     albertel 13766: #	if (! exists($metacache{$uri})) {
                   13767: #	    $metacache{$uri}={};
                   13768: #	}
1.924     albertel 13769: 	my $cachetime = 60*60;
1.171     www      13770:         if ($liburi) {
                   13771: 	    $liburi=&declutter($liburi);
                   13772:             $filename=$liburi;
1.401     bowersj2 13773:         } else {
1.599     albertel 13774: 	    &devalidate_cache_new('meta',$uri);
                   13775: 	    undef(%metaentry);
1.401     bowersj2 13776: 	}
1.140     www      13777:         my %metathesekeys=();
1.73      www      13778:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 13779: 	my $metastring;
1.1140    www      13780: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 13781: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 13782: 	    $metastring = 
1.929     albertel 13783: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 13784: 					  ('grade_target' => 'meta'));
                   13785: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  13786: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   13787:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 13788: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 13789: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 13790: 	    $metastring=&getfile($file);
1.489     albertel 13791: 	}
1.208     albertel 13792:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      13793:         my $token;
1.140     www      13794:         undef %metathesekeys;
1.71      www      13795:         while ($token=$parser->get_token) {
1.339     albertel 13796: 	    if ($token->[0] eq 'S') {
                   13797: 		if (defined($token->[2]->{'package'})) {
1.172     www      13798: #
                   13799: # This is a package - get package info
                   13800: #
1.339     albertel 13801: 		    my $package=$token->[2]->{'package'};
                   13802: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13803: 		    if (defined($token->[2]->{'id'})) { 
                   13804: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   13805: 		    }
1.599     albertel 13806: 		    if ($metaentry{':packages'}) {
                   13807: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 13808: 		    } else {
1.599     albertel 13809: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 13810: 		    }
1.736     albertel 13811: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 13812: 			my $part=$keyroot;
                   13813: 			$part=~s/^\_//;
1.736     albertel 13814: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   13815: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   13816: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 13817: 			    # ignore package.tab specified default values
                   13818:                             # here &package_tab_default() will fetch those
                   13819: 			    if ($subp eq 'default') { next; }
1.736     albertel 13820: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 13821: 			    my $unikey;
                   13822: 			    if ($pack =~ /_0$/) {
                   13823: 				$unikey='parameter_0_'.$name;
                   13824: 				$part=0;
                   13825: 			    } else {
                   13826: 				$unikey='parameter'.$keyroot.'_'.$name;
                   13827: 			    }
1.339     albertel 13828: 			    if ($subp eq 'display') {
                   13829: 				$value.=' [Part: '.$part.']';
                   13830: 			    }
1.599     albertel 13831: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 13832: 			    $metathesekeys{$unikey}=1;
1.599     albertel 13833: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13834: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 13835: 			    }
1.599     albertel 13836: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   13837: 				$metaentry{':'.$unikey}=
                   13838: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 13839: 			    }
1.339     albertel 13840: 			}
                   13841: 		    }
                   13842: 		} else {
1.172     www      13843: #
                   13844: # This is not a package - some other kind of start tag
1.339     albertel 13845: #
                   13846: 		    my $entry=$token->[1];
1.1068    www      13847: 		    my $unikey='';
1.175     www      13848: 
1.339     albertel 13849: 		    if ($entry eq 'import') {
1.175     www      13850: #
                   13851: # Importing a library here
1.339     albertel 13852: #
1.1067    www      13853:                         my $location=$parser->get_text('/import');
                   13854:                         my $dir=$filename;
                   13855:                         $dir=~s|[^/]*$||;
                   13856:                         $location=&filelocation($dir,$location);
1.1369    raeburn  13857: 
                   13858:                         my $importid=$token->[2]->{'id'};
1.1068    www      13859:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  13860: #
                   13861: # Check metadata for imported file to
                   13862: # see if it contained response items
                   13863: #
1.1372    raeburn  13864:                         my ($origfile,@libfilekeys);
1.1370    raeburn  13865:                         my %currmetaentry = %metaentry;
1.1372    raeburn  13866:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   13867:                                                            $depthcount+1));
                   13868:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   13869:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   13870:                                                              undef,$depthcount+1);
                   13871:                             if ($libresponseorder ne '') {
                   13872:                                 if ($#origfiletagids<0) {
                   13873:                                     undef(%importedrespids);
                   13874:                                     undef(%importedpartids);
                   13875:                                 }
1.1373    raeburn  13876:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   13877:                                 if (@respids) {
                   13878:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   13879:                                 }
                   13880:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  13881:                                     $importedresponses = 1;
1.1369    raeburn  13882: # We need to get the original file and the imported file to get the response order correct
                   13883: # Load and inspect original file
1.1372    raeburn  13884:                                     if ($#origfiletagids<0) {
                   13885:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13886:                                         $origfile=&getfile($origfilelocation);
                   13887:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13888:                                     }
1.1369    raeburn  13889:                                 }
                   13890:                             }
                   13891:                         }
1.1370    raeburn  13892: # Do not overwrite contents of %metaentry hash for resource itself with 
                   13893: # hash populated for imported library file
                   13894:                         %metaentry = %currmetaentry;
                   13895:                         undef(%currmetaentry);
1.1374    raeburn  13896:                         if ($importmode eq 'part') {
1.1068    www      13897: # Import as part(s)
1.1069    www      13898:                            $importedparts=1;
                   13899: # We need to get the original file and the imported file to get the part order correct
                   13900: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  13901: # Load and inspect original file if we didn't do that already
                   13902:                            if ($#origfiletagids<0) {
                   13903:                                undef(%importedrespids);
                   13904:                                undef(%importedpartids);
                   13905:                                if ($origfile eq '') {
                   13906:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13907:                                    $origfile=&getfile($origfilelocation);
                   13908:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13909:                                }
1.1070    www      13910:                            }
1.1372    raeburn  13911:                            my @impfilepartids;
                   13912: # If <partorder> tag is included in metadata for the imported file
                   13913: # get the parts in the imported file from that.
                   13914:                            if (grep(/^partorder$/,@libfilekeys)) {
                   13915:                                %currmetaentry = %metaentry;
                   13916:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13917:                                                             $depthcount+1);
                   13918:                                %metaentry = %currmetaentry;
                   13919:                                undef(%currmetaentry);
                   13920:                                if ($libpartorder ne '') {
                   13921:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   13922:                                }
                   13923:                            } else {
                   13924: # If no <partorder> tag available, load and inspect imported file
                   13925:                                my $impfile=&getfile($location);
                   13926:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13927:                            }
1.1069    www      13928:                            if ($#impfilepartids>=0) {
                   13929: # This problem had parts
1.1070    www      13930:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      13931:                            } else {
                   13932: # Importing by turning a single problem into a problem part
                   13933: # It gets the import-tags ID as part-ID
                   13934:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      13935:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      13936:                            }
1.1068    www      13937:                         } else {
1.1374    raeburn  13938: # Import as problem or as normal import
                   13939:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13940:                             unless ($importmode eq 'problem') {
1.1068    www      13941: # Normal import
1.1374    raeburn  13942:                                 if (defined($token->[2]->{'id'})) {
                   13943:                                     $unikey.='_'.$token->[2]->{'id'};
                   13944:                                 }
                   13945:                             }
                   13946: # Check metadata for imported file to
                   13947: # see if it contained parts
                   13948:                             if (grep(/^partorder$/,@libfilekeys)) {
                   13949:                                 %currmetaentry = %metaentry;
                   13950:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13951:                                                              $depthcount+1);
                   13952:                                 %metaentry = %currmetaentry;
                   13953:                                 undef(%currmetaentry);
                   13954:                                 if ($libpartorder ne '') {
                   13955:                                     $importedparts = 1;
                   13956:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   13957:                                 }
                   13958:                             }
1.1067    www      13959:                         }
1.339     albertel 13960: 			if ($depthcount<20) {
1.736     albertel 13961: 			    my $metadata = 
1.1362    raeburn  13962: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 13963: 					  $depthcount+1);
                   13964: 			    foreach my $meta (split(',',$metadata)) {
                   13965: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   13966: 				$metathesekeys{$meta}=1;
1.339     albertel 13967: 			    }
1.1068    www      13968:                         }
1.1067    www      13969: 		    } else {
                   13970: #
                   13971: # Not importing, some other kind of non-package, non-library start tag
                   13972: # 
                   13973:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13974:                         if (defined($token->[2]->{'id'})) {
                   13975:                             $unikey.='_'.$token->[2]->{'id'};
                   13976:                         }
1.339     albertel 13977: 			if (defined($token->[2]->{'name'})) { 
                   13978: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13979: 			}
                   13980: 			$metathesekeys{$unikey}=1;
1.736     albertel 13981: 			foreach my $param (@{$token->[3]}) {
                   13982: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13983: 				$token->[2]->{$param};
1.339     albertel 13984: 			}
                   13985: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13986: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13987: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13988: 		 # only ws inside the tag, and not in default, so use default
                   13989: 		 # as value
1.599     albertel 13990: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13991: 			} elsif ( $internaltext =~ /\S/ ) {
                   13992: 		  # something interesting inside the tag
                   13993: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13994: 			} else {
1.908     albertel 13995: 		  # no interesting values, don't set a default
1.339     albertel 13996: 			}
1.172     www      13997: # end of not-a-package not-a-library import
1.339     albertel 13998: 		    }
1.172     www      13999: # end of not-a-package start tag
1.339     albertel 14000: 		}
1.172     www      14001: # the next is the end of "start tag"
1.339     albertel 14002: 	    }
                   14003: 	}
1.483     albertel 14004: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 14005: 	$extension = lc($extension);
                   14006: 	if ($extension eq 'htm') { $extension='html'; }
                   14007: 
1.737     albertel 14008: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 14009: 	    #no specific packages #how's our extension
                   14010: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 14011: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 14012: 					 \%metathesekeys);
                   14013: 	}
1.883     albertel 14014: 
                   14015: 	if (!exists($metaentry{':packages'})
                   14016: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 14017: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 14018: 		#no specific packages well let's get default then
                   14019: 		if ($key!~/^default&/) { next; }
1.488     albertel 14020: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 14021: 					     \%metathesekeys);
                   14022: 	    }
                   14023: 	}
1.338     www      14024: # are there custom rights to evaluate
1.599     albertel 14025: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 14026: 
1.338     www      14027:     #
                   14028:     # Importing a rights file here
1.339     albertel 14029:     #
                   14030: 	    unless ($depthcount) {
1.599     albertel 14031: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 14032: 		my $dir=$filename;
                   14033: 		$dir=~s|[^/]*$||;
                   14034: 		$location=&filelocation($dir,$location);
1.736     albertel 14035: 		my $rights_metadata =
1.1362    raeburn  14036: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 14037: 			      $depthcount+1);
                   14038: 		foreach my $rights (split(',',$rights_metadata)) {
                   14039: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   14040: 		    $metathesekeys{$rights}=1;
1.339     albertel 14041: 		}
                   14042: 	    }
                   14043: 	}
1.737     albertel 14044: 	# uniqifiy package listing
                   14045: 	my %seen;
                   14046: 	my @uniq_packages =
                   14047: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   14048: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   14049: 
1.1369    raeburn  14050:         if (($importedresponses) || ($importedparts)) {
                   14051:             if ($importedparts) {
1.1070    www      14052: # We had imported parts and need to rebuild partorder
1.1369    raeburn  14053:                 $metaentry{':partorder'}='';
                   14054:                 $metathesekeys{'partorder'}=1;
                   14055:             }
                   14056:             if ($importedresponses) {
                   14057: # We had imported responses and need to rebuil responseorder
                   14058:                 $metaentry{':responseorder'}='';
                   14059:                 $metathesekeys{'responseorder'}=1;
                   14060:             }
                   14061:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   14062:                 my $origid = $origfiletagids[$index+1];
                   14063:                 if ($origfiletagids[$index] eq 'part') {
                   14064: # Original part, part of the problem
                   14065:                     if ($importedparts) {
                   14066:                         $metaentry{':partorder'}.=','.$origid;
                   14067:                     }
                   14068:                 } elsif ($origfiletagids[$index] eq 'import') {
                   14069:                     if ($importedparts) {
                   14070: # We have imported parts at this position
1.1373    raeburn  14071:                         if ($importedpartids{$origid} ne '') {
                   14072:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   14073:                         }
1.1369    raeburn  14074:                     }
                   14075:                     if ($importedresponses) {
                   14076: # We have imported responses at this position
1.1373    raeburn  14077:                         if ($importedrespids{$origid} ne '') {
                   14078:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  14079:                         }
                   14080:                     }
                   14081:                 } else {
                   14082: # Original response item, part of the problem
                   14083:                     if ($importedresponses) {
                   14084:                         $metaentry{':responseorder'}.=','.$origid;
                   14085:                     }
                   14086:                 }
                   14087:             }
                   14088:             if ($importedparts) {
                   14089:                 $metaentry{':partorder'}=~s/^\,//;
                   14090:             }
                   14091:             if ($importedresponses) {
                   14092:                 $metaentry{':responseorder'}=~s/^\,//;
                   14093:             }
1.1070    www      14094:         }
1.737     albertel 14095: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 14096: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  14097: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  14098:         unless ($liburi) {
                   14099: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   14100:         }
1.177     www      14101: # this is the end of "was not already recently cached
1.71      www      14102:     }
1.599     albertel 14103:     return $metaentry{':'.$what};
1.261     albertel 14104: }
                   14105: 
1.488     albertel 14106: sub metadata_create_package_def {
1.483     albertel 14107:     my ($uri,$key,$package,$metathesekeys)=@_;
                   14108:     my ($pack,$name,$subp)=split(/\&/,$key);
                   14109:     if ($subp eq 'default') { next; }
                   14110:     
1.599     albertel 14111:     if (defined($metaentry{':packages'})) {
                   14112: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 14113:     } else {
1.599     albertel 14114: 	$metaentry{':packages'}=$package;
1.483     albertel 14115:     }
                   14116:     my $value=$packagetab{$key};
                   14117:     my $unikey;
                   14118:     $unikey='parameter_0_'.$name;
1.599     albertel 14119:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 14120:     $$metathesekeys{$unikey}=1;
1.599     albertel 14121:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   14122: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 14123:     }
1.599     albertel 14124:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   14125: 	$metaentry{':'.$unikey}=
                   14126: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 14127:     }
                   14128: }
                   14129: 
1.261     albertel 14130: sub metadata_generate_part0 {
                   14131:     my ($metadata,$metacache,$uri) = @_;
                   14132:     my %allnames;
1.737     albertel 14133:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 14134: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 14135: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   14136: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 14137: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 14138: 	    $allnames{$name}=$part;
                   14139: 	  }
                   14140: 	}
                   14141:     }
                   14142:     foreach my $name (keys(%allnames)) {
                   14143:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 14144:       my $key=":parameter_0_$name";
1.261     albertel 14145:       $$metacache{"$key.part"}='0';
                   14146:       $$metacache{"$key.name"}=$name;
1.428     albertel 14147:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 14148: 					   $allnames{$name}.'_'.$name.
                   14149: 					   '.type'};
1.428     albertel 14150:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 14151: 			     '.display'};
1.644     www      14152:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 14153:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 14154:       $$metacache{"$key.display"}=$olddis;
                   14155:     }
1.71      www      14156: }
                   14157: 
1.764     albertel 14158: # ------------------------------------------------------ Devalidate title cache
                   14159: 
                   14160: sub devalidate_title_cache {
                   14161:     my ($url)=@_;
                   14162:     if (!$env{'request.course.id'}) { return; }
                   14163:     my $symb=&symbread($url);
                   14164:     if (!$symb) { return; }
                   14165:     my $key=$env{'request.course.id'}."\0".$symb;
                   14166:     &devalidate_cache_new('title',$key);
                   14167: }
                   14168: 
1.1014    droeschl 14169: # ------------------------------------------------- Get the title of a course
                   14170: 
                   14171: sub current_course_title {
                   14172:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   14173: }
1.301     www      14174: # ------------------------------------------------- Get the title of a resource
                   14175: 
                   14176: sub gettitle {
                   14177:     my $urlsymb=shift;
                   14178:     my $symb=&symbread($urlsymb);
1.534     albertel 14179:     if ($symb) {
1.620     albertel 14180: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 14181: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 14182: 	if (defined($cached)) { 
                   14183: 	    return $result;
                   14184: 	}
1.534     albertel 14185: 	my ($map,$resid,$url)=&decode_symb($symb);
                   14186: 	my $title='';
1.907     albertel 14187: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   14188: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   14189: 	} else {
                   14190: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   14191: 		    &GDBM_READER(),0640)) {
                   14192: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   14193: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   14194: 		untie(%bighash);
                   14195: 	    }
1.534     albertel 14196: 	}
                   14197: 	$title=~s/\&colon\;/\:/gs;
                   14198: 	if ($title) {
1.1159    www      14199: # Remember both $symb and $title for dynamic metadata
                   14200:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      14201:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      14202: # Cache this title and then return it
1.599     albertel 14203: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 14204: 	}
                   14205: 	$urlsymb=$url;
                   14206:     }
                   14207:     my $title=&metadata($urlsymb,'title');
                   14208:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   14209:     return $title;
1.301     www      14210: }
1.613     albertel 14211: 
1.614     albertel 14212: sub get_slot {
                   14213:     my ($which,$cnum,$cdom)=@_;
                   14214:     if (!$cnum || !$cdom) {
1.790     albertel 14215: 	(undef,my $courseid)=&whichuser();
1.620     albertel 14216: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   14217: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 14218:     }
1.703     albertel 14219:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   14220:     my %slotinfo;
                   14221:     if (exists($remembered{$key})) {
                   14222: 	$slotinfo{$which} = $remembered{$key};
                   14223:     } else {
                   14224: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   14225: 	&Apache::lonhomework::showhash(%slotinfo);
                   14226: 	my ($tmp)=keys(%slotinfo);
                   14227: 	if ($tmp=~/^error:/) { return (); }
                   14228: 	$remembered{$key} = $slotinfo{$which};
                   14229:     }
1.616     albertel 14230:     if (ref($slotinfo{$which}) eq 'HASH') {
                   14231: 	return %{$slotinfo{$which}};
                   14232:     }
                   14233:     return $slotinfo{$which};
1.614     albertel 14234: }
1.1150    raeburn  14235: 
                   14236: sub get_reservable_slots {
                   14237:     my ($cnum,$cdom,$uname,$udom) = @_;
                   14238:     my $now = time;
                   14239:     my $reservable_info;
                   14240:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   14241:     if (exists($remembered{$key})) {
                   14242:         $reservable_info = $remembered{$key};
                   14243:     } else {
                   14244:         my %resv;
                   14245:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   14246:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   14247:         $reservable_info = \%resv;
                   14248:         $remembered{$key} = $reservable_info;
                   14249:     }
                   14250:     return $reservable_info;
                   14251: }
                   14252: 
                   14253: sub get_course_slots {
                   14254:     my ($cnum,$cdom) = @_;
                   14255:     my $hashid=$cnum.':'.$cdom;
1.1494    raeburn  14256:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
1.1150    raeburn  14257:     if (defined($cached)) {
                   14258:         if (ref($result) eq 'HASH') {
                   14259:             return %{$result};
                   14260:         }
                   14261:     } else {
1.1494    raeburn  14262:         my %slots=&dump('slots',$cdom,$cnum);
1.1150    raeburn  14263:         my ($tmp) = keys(%slots);
                   14264:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  14265:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  14266:             return %slots;
                   14267:         }
                   14268:     }
                   14269:     return;
                   14270: }
                   14271: 
                   14272: sub devalidate_slots_cache {
                   14273:     my ($cnum,$cdom)=@_;
                   14274:     my $hashid=$cnum.':'.$cdom;
                   14275:     &devalidate_cache_new('allslots',$hashid);
                   14276: }
                   14277: 
1.1181    raeburn  14278: sub get_coursechange {
                   14279:     my ($cdom,$cnum) = @_;
                   14280:     if ($cdom eq '' || $cnum eq '') {
                   14281:         return unless ($env{'request.course.id'});
                   14282:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   14283:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   14284:     }
                   14285:     my $hashid=$cdom.'_'.$cnum;
                   14286:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   14287:     if ((defined($cached)) && ($change ne '')) {
                   14288:         return $change;
                   14289:     } else {
                   14290:         my %crshash;
                   14291:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   14292:         if ($crshash{'internal.contentchange'} eq '') {
                   14293:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   14294:             if ($change eq '') {
                   14295:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   14296:                 $change = $crshash{'internal.created'};
                   14297:             }
                   14298:         } else {
                   14299:             $change = $crshash{'internal.contentchange'};
                   14300:         }
                   14301:         my $cachetime = 600;
                   14302:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   14303:     }
                   14304:     return $change;
                   14305: }
                   14306: 
                   14307: sub devalidate_coursechange_cache {
1.1496    raeburn  14308:     my ($cdom,$cnum)=@_;
                   14309:     my $hashid=$cdom.'_'.$cnum;
1.1181    raeburn  14310:     &devalidate_cache_new('crschange',$hashid);
                   14311: }
                   14312: 
1.1496    raeburn  14313: sub get_suppchange {
                   14314:     my ($cdom,$cnum) = @_;
                   14315:     if ($cdom eq '' || $cnum eq '') {
                   14316:         return unless ($env{'request.course.id'});
                   14317:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   14318:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   14319:     }
                   14320:     my $hashid=$cdom.'_'.$cnum;
                   14321:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   14322:     if ((defined($cached)) && ($change ne '')) {
                   14323:         return $change;
                   14324:     } else {
                   14325:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   14326:         if ($crshash{'internal.supplementalchange'} eq '') {
                   14327:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   14328:             if ($change eq '') {
                   14329:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   14330:                 $change = $crshash{'internal.created'};
                   14331:             }
                   14332:         } else {
                   14333:             $change = $crshash{'internal.supplementalchange'};
                   14334:         }
                   14335:         my $cachetime = 600;
                   14336:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   14337:     }
                   14338:     return $change;
                   14339: }
                   14340: 
                   14341: sub devalidate_suppchange_cache {
                   14342:     my ($cdom,$cnum)=@_;
                   14343:     my $hashid=$cdom.'_'.$cnum;
                   14344:     &devalidate_cache_new('suppchange',$hashid);
                   14345: }
                   14346: 
1.1497    raeburn  14347: sub update_supp_caches {
                   14348:     my ($cdom,$cnum) = @_;
                   14349:     my %servers = &internet_dom_servers($cdom);
                   14350:     my @ids=&current_machine_ids();
                   14351:     foreach my $server (keys(%servers)) {
                   14352:         next if (grep(/^\Q$server\E$/,@ids));
                   14353:         my $hashid=$cnum.':'.$cdom;
                   14354:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   14355:         &remote_devalidate_cache($server,[$cachekey]);
                   14356:     }
                   14357:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   14358:     &count_supptools($cnum,$cdom,1);
                   14359:     my $now = time;
                   14360:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   14361:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   14362:     }
                   14363:     &put('environment',{'internal.supplementalchange' => $now},
                   14364:          $cdom,$cnum);
                   14365:     &Apache::lonnet::appenv(
                   14366:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   14367:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   14368: }
                   14369: 
1.31      www      14370: # ------------------------------------------------- Update symbolic store links
                   14371: 
                   14372: sub symblist {
                   14373:     my ($mapname,%newhash)=@_;
1.438     www      14374:     $mapname=&deversion(&declutter($mapname));
1.31      www      14375:     my %hash;
1.620     albertel 14376:     if (($env{'request.course.fn'}) && (%newhash)) {
                   14377:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 14378:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  14379: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 14380: 		next if ($url eq 'last_known'
                   14381: 			 && $env{'form.no_update_last_known'});
                   14382: 		$hash{declutter($url)}=&encode_symb($mapname,
                   14383: 						    $newhash{$url}->[1],
                   14384: 						    $newhash{$url}->[0]);
1.191     harris41 14385:             }
1.31      www      14386:             if (untie(%hash)) {
                   14387: 		return 'ok';
                   14388:             }
                   14389:         }
                   14390:     }
                   14391:     return 'error';
1.212     www      14392: }
                   14393: 
                   14394: # --------------------------------------------------------------- Verify a symb
                   14395: 
                   14396: sub symbverify {
1.1190    raeburn  14397:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      14398:     my $thisfn=$thisurl;
1.439     www      14399:     $thisfn=&declutter($thisfn);
1.215     www      14400: # direct jump to resource in page or to a sequence - will construct own symbs
                   14401:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   14402: # check URL part
1.409     www      14403:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      14404: 
1.431     www      14405:     unless ($url eq $thisfn) { return 0; }
1.213     www      14406: 
1.216     www      14407:     $symb=&symbclean($symb);
1.510     www      14408:     $thisurl=&deversion($thisurl);
1.439     www      14409:     $thisfn=&deversion($thisfn);
1.213     www      14410: 
                   14411:     my %bighash;
                   14412:     my $okay=0;
1.431     www      14413: 
1.620     albertel 14414:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 14415:                             &GDBM_READER(),0640)) {
1.1032    raeburn  14416:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   14417:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  14418:             if ($map =~ m{^uploaded/.+\.page$}) {
                   14419:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   14420:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   14421:             }
                   14422:         }
                   14423:         my $ids;
1.1419    raeburn  14424:         if ($map =~ m{^uploaded/.+\.page$}) {
                   14425:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  14426:         } else {
                   14427:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  14428:         }
1.1102    raeburn  14429:         unless ($ids) {
                   14430:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   14431:             $ids=$bighash{$idkey};
1.216     www      14432:         }
                   14433:         if ($ids) {
                   14434: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  14435:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  14436:                 $symb =~ s/\?.+$//;
1.1202    raeburn  14437:             }
1.800     albertel 14438: 	    foreach my $id (split(/\,/,$ids)) {
                   14439: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      14440:                if (
                   14441:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  14442:    eq $symb) {
                   14443:                    if (ref($encstate)) {
                   14444:                        $$encstate = $bighash{'encrypted_'.$id};
                   14445:                    }
1.620     albertel 14446: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  14447: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   14448:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  14449: 		       $okay=1;
1.1202    raeburn  14450:                        last;
1.582     albertel 14451: 		   }
                   14452: 	       }
1.216     www      14453: 	   }
                   14454:         }
1.213     www      14455: 	untie(%bighash);
                   14456:     }
                   14457:     return $okay;
1.31      www      14458: }
                   14459: 
1.210     www      14460: # --------------------------------------------------------------- Clean-up symb
                   14461: 
                   14462: sub symbclean {
                   14463:     my $symb=shift;
1.568     albertel 14464:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      14465: # remove version from map
                   14466:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      14467: 
1.210     www      14468: # remove version from URL
                   14469:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      14470: 
1.507     www      14471: # remove wrapper
                   14472: 
1.510     www      14473:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 14474:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      14475:     return $symb;
1.409     www      14476: }
                   14477: 
                   14478: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 14479: 
                   14480: sub encode_symb {
                   14481:     my ($map,$resid,$url)=@_;
                   14482:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   14483: }
1.409     www      14484: 
                   14485: sub decode_symb {
1.568     albertel 14486:     my $symb=shift;
                   14487:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   14488:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      14489:     return (&fixversion($map),$resid,&fixversion($url));
                   14490: }
                   14491: 
                   14492: sub fixversion {
                   14493:     my $fn=shift;
1.609     banghart 14494:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      14495:     my %bighash;
                   14496:     my $uri=&clutter($fn);
1.620     albertel 14497:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      14498: # is this cached?
1.599     albertel 14499:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      14500:     if (defined($cached)) { return $result; }
                   14501: # unfortunately not cached, or expired
1.620     albertel 14502:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      14503: 	    &GDBM_READER(),0640)) {
                   14504:  	if ($bighash{'version_'.$uri}) {
                   14505:  	    my $version=$bighash{'version_'.$uri};
1.444     www      14506:  	    unless (($version eq 'mostrecent') || 
                   14507: 		    ($version==&getversion($uri))) {
1.440     www      14508:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   14509:  	    }
                   14510:  	}
                   14511:  	untie %bighash;
1.413     www      14512:     }
1.599     albertel 14513:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      14514: }
                   14515: 
                   14516: sub deversion {
                   14517:     my $url=shift;
                   14518:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   14519:     return $url;
1.210     www      14520: }
                   14521: 
1.31      www      14522: # ------------------------------------------------------ Return symb list entry
                   14523: 
                   14524: sub symbread {
1.1424    raeburn  14525:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  14526:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  14527:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  14528:     if (defined($env{$cache_str})) {
1.1424    raeburn  14529:         unless (ref($possibles) eq 'HASH') {
                   14530:             if ($ignorecachednull) {
                   14531:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   14532:             } else {
                   14533:                 return $env{$cache_str};
                   14534:             }
1.1282    raeburn  14535:         }
                   14536:     }
1.242     www      14537: # no filename provided? try from environment
1.1265    raeburn  14538:     unless ($thisfn) {
1.620     albertel 14539:         if ($env{'request.symb'}) {
1.1427    raeburn  14540:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 14541: 	}
1.620     albertel 14542: 	$thisfn=$env{'request.filename'};
1.44      www      14543:     }
1.569     albertel 14544:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      14545: # is that filename actually a symb? Verify, clean, and return
                   14546:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 14547: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  14548: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 14549: 	}
1.242     www      14550:     }
1.44      www      14551:     $thisfn=declutter($thisfn);
1.31      www      14552:     my %hash;
1.37      www      14553:     my %bighash;
                   14554:     my $syval='';
1.620     albertel 14555:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427    raeburn  14556:         unless ($ignoresymbdb) {
1.1424    raeburn  14557:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   14558:                           &GDBM_READER(),0640)) {
1.1487    raeburn  14559: 	        $syval=$hash{$thisfn};
1.1424    raeburn  14560:                 untie(%hash);
                   14561:             }
1.1427    raeburn  14562:             if ($syval && $checkforblock) {
                   14563:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  14564:                 if (@blockers) {
                   14565:                     $syval='';
                   14566:                 }
                   14567:             }
1.37      www      14568:         }
                   14569: # ---------------------------------------------------------- There was an entry
                   14570:         if ($syval) {
1.601     albertel 14571: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 14572: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  14573: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 14574: 		    #return $env{$cache_str}='';
1.601     albertel 14575: 		#}    
                   14576: 		#$syval.=$1;
                   14577: 	    #}
1.37      www      14578:         } else {
                   14579: # ------------------------------------------------------- Was not in symb table
1.620     albertel 14580:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 14581:                             &GDBM_READER(),0640)) {
1.37      www      14582: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      14583:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      14584:               unless ($ids) { 
                   14585:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      14586:               }
                   14587:               unless ($ids) {
                   14588: # alias?
                   14589: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      14590:               }
1.37      www      14591:               if ($ids) {
                   14592: # ------------------------------------------------------------------- Has ID(s)
                   14593:                  my @possibilities=split(/\,/,$ids);
1.39      www      14594:                  if ($#possibilities==0) {
                   14595: # ----------------------------------------------- There is only one possibility
1.37      www      14596: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 14597: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   14598: 						    $resid,$thisfn);
1.1282    raeburn  14599:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  14600:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   14601:                              $possibles->{$syval} = 1;
                   14602:                          }
1.1282    raeburn  14603:                      }
                   14604:                      if ($checkforblock) {
1.1424    raeburn  14605:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  14606:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  14607:                              if (@blockers) {
                   14608:                                  $syval = '';
1.1425    raeburn  14609:                                  untie(%bighash);
                   14610:                                  return $env{$cache_str}='';
1.1424    raeburn  14611:                              }
1.1282    raeburn  14612:                          }
                   14613:                      }
                   14614:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      14615: # ------------------------------------------ There is more than one possibility
                   14616:                      my $realpossible=0;
1.800     albertel 14617:                      foreach my $id (@possibilities) {
                   14618: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  14619:                          my $canaccess;
                   14620:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   14621:                              $canaccess = 1;
                   14622:                          } else { 
                   14623:                              $canaccess = &allowed('bre',$file);
                   14624:                          }
                   14625:                          if ($canaccess) {
                   14626:          		     my ($mapid,$resid)=split(/\./,$id);
                   14627:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   14628:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   14629: 						             $resid,$thisfn);
1.1424    raeburn  14630:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  14631:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  14632:                                  if ($checkforblock) {
1.1426    raeburn  14633:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  14634:                                      if (@blockers > 0) {
                   14635:                                          $syval = '';
                   14636:                                      } else {
1.1282    raeburn  14637:                                          $syval = $poss_syval;
                   14638:                                          $realpossible++;
                   14639:                                      }
                   14640:                                  } else {
                   14641:                                      $syval = $poss_syval;
                   14642:                                      $realpossible++;
                   14643:                                  }
1.1424    raeburn  14644:                                  if ($syval) {
                   14645:                                      if (ref($possibles) eq 'HASH') {
                   14646:                                          $possibles->{$syval} = 1;
                   14647:                                      }
                   14648:                                  }
1.1282    raeburn  14649:                              }
1.39      www      14650: 			 }
1.191     harris41 14651:                      }
1.39      www      14652: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      14653:                  } else {
                   14654:                      $syval='';
1.37      www      14655:                  }
                   14656: 	      }
1.1282    raeburn  14657:               untie(%bighash);
1.481     raeburn  14658:            }
1.31      www      14659:         }
1.62      www      14660:         if ($syval) {
1.1427    raeburn  14661: 	    return $env{$cache_str}=$syval;
1.62      www      14662:         }
1.31      www      14663:     }
1.949     raeburn  14664:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 14665:     return $env{$cache_str}='';
1.31      www      14666: }
                   14667: 
                   14668: # ---------------------------------------------------------- Return random seed
                   14669: 
1.32      www      14670: sub numval {
                   14671:     my $txt=shift;
                   14672:     $txt=~tr/A-J/0-9/;
                   14673:     $txt=~tr/a-j/0-9/;
                   14674:     $txt=~tr/K-T/0-9/;
                   14675:     $txt=~tr/k-t/0-9/;
                   14676:     $txt=~tr/U-Z/0-5/;
                   14677:     $txt=~tr/u-z/0-5/;
                   14678:     $txt=~s/\D//g;
1.564     albertel 14679:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      14680:     return int($txt);
1.368     albertel 14681: }
                   14682: 
1.484     albertel 14683: sub numval2 {
                   14684:     my $txt=shift;
                   14685:     $txt=~tr/A-J/0-9/;
                   14686:     $txt=~tr/a-j/0-9/;
                   14687:     $txt=~tr/K-T/0-9/;
                   14688:     $txt=~tr/k-t/0-9/;
                   14689:     $txt=~tr/U-Z/0-5/;
                   14690:     $txt=~tr/u-z/0-5/;
                   14691:     $txt=~s/\D//g;
                   14692:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   14693:     my $total;
                   14694:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 14695:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 14696:     return int($total);
                   14697: }
                   14698: 
1.575     albertel 14699: sub numval3 {
                   14700:     use integer;
                   14701:     my $txt=shift;
                   14702:     $txt=~tr/A-J/0-9/;
                   14703:     $txt=~tr/a-j/0-9/;
                   14704:     $txt=~tr/K-T/0-9/;
                   14705:     $txt=~tr/k-t/0-9/;
                   14706:     $txt=~tr/U-Z/0-5/;
                   14707:     $txt=~tr/u-z/0-5/;
                   14708:     $txt=~s/\D//g;
                   14709:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   14710:     my $total;
                   14711:     foreach my $val (@txts) { $total+=$val; }
                   14712:     if ($_64bit) { $total=(($total<<32)>>32); }
                   14713:     return $total;
                   14714: }
                   14715: 
1.675     albertel 14716: sub digest {
                   14717:     my ($data)=@_;
                   14718:     my $digest=&Digest::MD5::md5($data);
                   14719:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   14720:     my ($e,$f);
                   14721:     {
                   14722:         use integer;
                   14723:         $e=($a+$b);
                   14724:         $f=($c+$d);
                   14725:         if ($_64bit) {
                   14726:             $e=(($e<<32)>>32);
                   14727:             $f=(($f<<32)>>32);
                   14728:         }
                   14729:     }
                   14730:     if (wantarray) {
                   14731: 	return ($e,$f);
                   14732:     } else {
                   14733: 	my $g;
                   14734: 	{
                   14735: 	    use integer;
                   14736: 	    $g=($e+$f);
                   14737: 	    if ($_64bit) {
                   14738: 		$g=(($g<<32)>>32);
                   14739: 	    }
                   14740: 	}
                   14741: 	return $g;
                   14742:     }
                   14743: }
                   14744: 
1.368     albertel 14745: sub latest_rnd_algorithm_id {
1.675     albertel 14746:     return '64bit5';
1.366     albertel 14747: }
1.32      www      14748: 
1.503     albertel 14749: sub get_rand_alg {
                   14750:     my ($courseid)=@_;
1.790     albertel 14751:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 14752:     if ($courseid) {
1.620     albertel 14753: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 14754:     }
                   14755:     return &latest_rnd_algorithm_id();
                   14756: }
                   14757: 
1.562     albertel 14758: sub validCODE {
                   14759:     my ($CODE)=@_;
                   14760:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   14761:     return 0;
                   14762: }
                   14763: 
1.491     albertel 14764: sub getCODE {
1.620     albertel 14765:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 14766:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   14767: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   14768: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 14769: 	return $Apache::lonhomework::history{'resource.CODE'};
                   14770:     }
                   14771:     return undef;
                   14772: }
1.1133    foxr     14773: #
                   14774: #  Determines the random seed for a specific context:
                   14775: #
                   14776: # parameters:
                   14777: #   symb      - in course context the symb for the seed.
                   14778: #   course_id - The course id of the form domain_coursenum.
                   14779: #   domain    - Domain for the user.
                   14780: #   course    - Course for the user.
                   14781: #   cenv      - environment of the course.
                   14782: #
                   14783: # NOTE:
                   14784: #   All parameters are picked out of the environment if missing
                   14785: #   or not defined.
                   14786: #   If a symb cannot be determined the current time is used instead.
                   14787: #
                   14788: #  For a given well defined symb, courside, domain, username,
                   14789: #  and course environment, the seed is reproducible.
                   14790: #
1.31      www      14791: sub rndseed {
1.1133    foxr     14792:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 14793:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 14794:     if (!defined($symb)) {
1.366     albertel 14795: 	unless ($symb=$wsymb) { return time; }
                   14796:     }
1.1146    foxr     14797:     if (!defined $courseid) { 
                   14798: 	$courseid=$wcourseid; 
                   14799:     }
                   14800:     if (!defined $domain) { $domain=$wdomain; }
                   14801:     if (!defined $username) { $username=$wusername }
1.1133    foxr     14802: 
                   14803:     my $which;
                   14804:     if (defined($cenv->{'rndseed'})) {
                   14805: 	$which = $cenv->{'rndseed'};
                   14806:     } else {
                   14807: 	$which =&get_rand_alg($courseid);
                   14808:     }
1.491     albertel 14809:     if (defined(&getCODE())) {
1.1133    foxr     14810: 
1.675     albertel 14811: 	if ($which eq '64bit5') {
                   14812: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   14813: 	} elsif ($which eq '64bit4') {
1.575     albertel 14814: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   14815: 	} else {
                   14816: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   14817: 	}
1.675     albertel 14818:     } elsif ($which eq '64bit5') {
                   14819: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 14820:     } elsif ($which eq '64bit4') {
                   14821: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 14822:     } elsif ($which eq '64bit3') {
                   14823: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 14824:     } elsif ($which eq '64bit2') {
                   14825: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 14826:     } elsif ($which eq '64bit') {
                   14827: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   14828:     }
                   14829:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   14830: }
                   14831: 
                   14832: sub rndseed_32bit {
                   14833:     my ($symb,$courseid,$domain,$username)=@_;
                   14834:     {
                   14835: 	use integer;
                   14836: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   14837: 	my $symbseed=numval($symb) << 22;
                   14838: 	my $namechck=unpack("%32C*",$username) << 17;
                   14839: 	my $nameseed=numval($username) << 12;
                   14840: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   14841: 	my $courseseed=unpack("%32C*",$courseid);
                   14842: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 14843: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14844: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14845: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 14846: 	return $num;
                   14847:     }
                   14848: }
                   14849: 
                   14850: sub rndseed_64bit {
                   14851:     my ($symb,$courseid,$domain,$username)=@_;
                   14852:     {
                   14853: 	use integer;
                   14854: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   14855: 	my $symbseed=numval($symb) << 10;
                   14856: 	my $namechck=unpack("%32S*",$username);
                   14857: 	
                   14858: 	my $nameseed=numval($username) << 21;
                   14859: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   14860: 	my $courseseed=unpack("%32S*",$courseid);
                   14861: 	
                   14862: 	my $num1=$symbchck+$symbseed+$namechck;
                   14863: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14864: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14865: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14866: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 14867: 	return "$num1,$num2";
1.155     albertel 14868:     }
1.366     albertel 14869: }
                   14870: 
1.443     albertel 14871: sub rndseed_64bit2 {
                   14872:     my ($symb,$courseid,$domain,$username)=@_;
                   14873:     {
                   14874: 	use integer;
                   14875: 	# strings need to be an even # of cahracters long, it it is odd the
                   14876:         # last characters gets thrown away
                   14877: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14878: 	my $symbseed=numval($symb) << 10;
                   14879: 	my $namechck=unpack("%32S*",$username.' ');
                   14880: 	
                   14881: 	my $nameseed=numval($username) << 21;
1.501     albertel 14882: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14883: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14884: 	
                   14885: 	my $num1=$symbchck+$symbseed+$namechck;
                   14886: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14887: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14888: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 14889: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 14890: 	return "$num1,$num2";
                   14891:     }
                   14892: }
                   14893: 
                   14894: sub rndseed_64bit3 {
                   14895:     my ($symb,$courseid,$domain,$username)=@_;
                   14896:     {
                   14897: 	use integer;
                   14898: 	# strings need to be an even # of cahracters long, it it is odd the
                   14899:         # last characters gets thrown away
                   14900: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14901: 	my $symbseed=numval2($symb) << 10;
                   14902: 	my $namechck=unpack("%32S*",$username.' ');
                   14903: 	
                   14904: 	my $nameseed=numval2($username) << 21;
1.443     albertel 14905: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14906: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14907: 	
                   14908: 	my $num1=$symbchck+$symbseed+$namechck;
                   14909: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14910: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14911: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 14912: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14913: 	
1.503     albertel 14914: 	return "$num1:$num2";
1.443     albertel 14915:     }
                   14916: }
                   14917: 
1.575     albertel 14918: sub rndseed_64bit4 {
                   14919:     my ($symb,$courseid,$domain,$username)=@_;
                   14920:     {
                   14921: 	use integer;
                   14922: 	# strings need to be an even # of cahracters long, it it is odd the
                   14923:         # last characters gets thrown away
                   14924: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14925: 	my $symbseed=numval3($symb) << 10;
                   14926: 	my $namechck=unpack("%32S*",$username.' ');
                   14927: 	
                   14928: 	my $nameseed=numval3($username) << 21;
                   14929: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14930: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14931: 	
                   14932: 	my $num1=$symbchck+$symbseed+$namechck;
                   14933: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14934: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14935: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 14936: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14937: 	
1.575     albertel 14938: 	return "$num1:$num2";
                   14939:     }
                   14940: }
                   14941: 
1.675     albertel 14942: sub rndseed_64bit5 {
                   14943:     my ($symb,$courseid,$domain,$username)=@_;
                   14944:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   14945:     return "$num1:$num2";
                   14946: }
                   14947: 
1.366     albertel 14948: sub rndseed_CODE_64bit {
                   14949:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 14950:     {
1.366     albertel 14951: 	use integer;
1.443     albertel 14952: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 14953: 	my $symbseed=numval2($symb);
1.491     albertel 14954: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14955: 	my $CODEseed=numval(&getCODE());
1.443     albertel 14956: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 14957: 	my $num1=$symbseed+$CODEchck;
                   14958: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14959: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14960: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 14961: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14962: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 14963: 	return "$num1:$num2";
1.366     albertel 14964:     }
                   14965: }
                   14966: 
1.575     albertel 14967: sub rndseed_CODE_64bit4 {
                   14968:     my ($symb,$courseid,$domain,$username)=@_;
                   14969:     {
                   14970: 	use integer;
                   14971: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   14972: 	my $symbseed=numval3($symb);
                   14973: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14974: 	my $CODEseed=numval3(&getCODE());
                   14975: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14976: 	my $num1=$symbseed+$CODEchck;
                   14977: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14978: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14979: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14980: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14981: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14982: 	return "$num1:$num2";
                   14983:     }
                   14984: }
                   14985: 
1.675     albertel 14986: sub rndseed_CODE_64bit5 {
                   14987:     my ($symb,$courseid,$domain,$username)=@_;
                   14988:     my $code = &getCODE();
                   14989:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14990:     return "$num1:$num2";
                   14991: }
                   14992: 
1.366     albertel 14993: sub setup_random_from_rndseed {
                   14994:     my ($rndseed)=@_;
1.503     albertel 14995:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  14996:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14997:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14998:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14999:         } else {
                   15000:             &Math::Random::random_set_seed($num1,$num2);
                   15001:         }
1.366     albertel 15002:     } else {
                   15003: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 15004:     }
1.36      albertel 15005: }
                   15006: 
1.474     albertel 15007: sub latest_receipt_algorithm_id {
1.835     albertel 15008:     return 'receipt3';
1.474     albertel 15009: }
                   15010: 
1.480     www      15011: sub recunique {
                   15012:     my $fucourseid=shift;
                   15013:     my $unique;
1.835     albertel 15014:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   15015: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 15016: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      15017:     } else {
                   15018: 	$unique=$perlvar{'lonReceipt'};
                   15019:     }
                   15020:     return unpack("%32C*",$unique);
                   15021: }
                   15022: 
                   15023: sub recprefix {
                   15024:     my $fucourseid=shift;
                   15025:     my $prefix;
1.835     albertel 15026:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   15027: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 15028: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      15029:     } else {
                   15030: 	$prefix=$perlvar{'lonHostID'};
                   15031:     }
                   15032:     return unpack("%32C*",$prefix);
                   15033: }
                   15034: 
1.76      www      15035: sub ireceipt {
1.474     albertel 15036:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 15037: 
                   15038:     my $return =&recprefix($fucourseid).'-';
                   15039: 
                   15040:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   15041: 	$env{'request.state'} eq 'construct') {
                   15042: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   15043: 	return $return;
                   15044:     }
                   15045: 
1.76      www      15046:     my $cuname=unpack("%32C*",$funame);
                   15047:     my $cudom=unpack("%32C*",$fudom);
                   15048:     my $cucourseid=unpack("%32C*",$fucourseid);
                   15049:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      15050:     my $cunique=&recunique($fucourseid);
1.474     albertel 15051:     my $cpart=unpack("%32S*",$part);
1.835     albertel 15052:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   15053: 
1.790     albertel 15054: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 15055: 			       
                   15056: 	$return.= ($cunique%$cuname+
                   15057: 		   $cunique%$cudom+
                   15058: 		   $cusymb%$cuname+
                   15059: 		   $cusymb%$cudom+
                   15060: 		   $cucourseid%$cuname+
                   15061: 		   $cucourseid%$cudom+
                   15062: 		   $cpart%$cuname+
                   15063: 		   $cpart%$cudom);
                   15064:     } else {
                   15065: 	$return.= ($cunique%$cuname+
                   15066: 		   $cunique%$cudom+
                   15067: 		   $cusymb%$cuname+
                   15068: 		   $cusymb%$cudom+
                   15069: 		   $cucourseid%$cuname+
                   15070: 		   $cucourseid%$cudom);
                   15071:     }
                   15072:     return $return;
1.76      www      15073: }
                   15074: 
                   15075: sub receipt {
1.474     albertel 15076:     my ($part)=@_;
1.790     albertel 15077:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 15078:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      15079: }
1.260     ng       15080: 
1.790     albertel 15081: sub whichuser {
                   15082:     my ($passedsymb)=@_;
                   15083:     my ($symb,$courseid,$domain,$name,$publicuser);
                   15084:     if (defined($env{'form.grade_symb'})) {
                   15085: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   15086: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   15087: 	if (!$allowed &&
                   15088: 	    exists($env{'request.course.sec'}) &&
                   15089: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   15090: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   15091: 			      '/'.$env{'request.course.sec'});
                   15092: 	}
                   15093: 	if ($allowed) {
                   15094: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   15095: 	    $courseid=$tmp_courseid;
                   15096: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   15097: 	    ($name)=&get_env_multiple('form.grade_username');
                   15098: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   15099: 	}
                   15100:     }
                   15101:     if (!$passedsymb) {
                   15102: 	$symb=&symbread();
                   15103:     } else {
                   15104: 	$symb=$passedsymb;
                   15105:     }
                   15106:     $courseid=$env{'request.course.id'};
                   15107:     $domain=$env{'user.domain'};
                   15108:     $name=$env{'user.name'};
                   15109:     if ($name eq 'public' && $domain eq 'public') {
                   15110: 	if (!defined($env{'form.username'})) {
                   15111: 	    $env{'form.username'}.=time.rand(10000000);
                   15112: 	}
                   15113: 	$name.=$env{'form.username'};
                   15114:     }
                   15115:     return ($symb,$courseid,$domain,$name,$publicuser);
                   15116: 
                   15117: }
                   15118: 
1.36      albertel 15119: # ------------------------------------------------------------ Serves up a file
1.472     albertel 15120: # returns either the contents of the file or 
                   15121: # -1 if the file doesn't exist
1.481     raeburn  15122: #
                   15123: # if the target is a file that was uploaded via DOCS, 
                   15124: # a check will be made to see if a current copy exists on the local server,
                   15125: # if it does this will be served, otherwise a copy will be retrieved from
                   15126: # the home server for the course and stored in /home/httpd/html/userfiles on
                   15127: # the local server.   
1.472     albertel 15128: 
1.36      albertel 15129: sub getfile {
1.538     albertel 15130:     my ($file) = @_;
1.609     banghart 15131:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 15132:     &repcopy($file);
                   15133:     return &readfile($file);
                   15134: }
                   15135: 
                   15136: sub repcopy_userfile {
                   15137:     my ($file)=@_;
1.1142    raeburn  15138:     my $londocroot = $perlvar{'lonDocRoot'};
                   15139:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  15140:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 15141:     my ($cdom,$cnum,$filename) = 
1.811     albertel 15142: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 15143:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   15144:     if (-e "$file") {
1.828     www      15145: # we already have a local copy, check it out
1.538     albertel 15146: 	my @fileinfo = stat($file);
1.828     www      15147: 	my $rtncode;
                   15148: 	my $info;
1.538     albertel 15149: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 15150: 	if ($lwpresp ne 'ok') {
1.828     www      15151: # there is no such file anymore, even though we had a local copy
1.482     albertel 15152: 	    if ($rtncode eq '404') {
1.538     albertel 15153: 		unlink($file);
1.482     albertel 15154: 	    }
                   15155: 	    return -1;
                   15156: 	}
                   15157: 	if ($info < $fileinfo[9]) {
1.828     www      15158: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  15159: 	    return 'ok';
1.828     www      15160: 	} else {
                   15161: # the file is outdated, get rid of it
                   15162: 	    unlink($file);
1.482     albertel 15163: 	}
1.828     www      15164:     }
                   15165: # one way or the other, at this point, we don't have the file
                   15166: # construct the correct path for the file
                   15167:     my @parts = ($cdom,$cnum); 
                   15168:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   15169: 	push @parts, split(/\//,$1);
                   15170:     }
                   15171:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   15172:     foreach my $part (@parts) {
                   15173: 	$path .= '/'.$part;
                   15174: 	if (!-e $path) {
                   15175: 	    mkdir($path,0770);
1.482     albertel 15176: 	}
                   15177:     }
1.828     www      15178: # now the path exists for sure
                   15179: # get a user agent
                   15180:     my $transferfile=$file.'.in.transfer';
                   15181: # FIXME: this should flock
                   15182:     if (-e $transferfile) { return 'ok'; }
                   15183:     my $request;
                   15184:     $uri=~s/^\///;
1.980     raeburn  15185:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  15186:     my $hostname = &hostname($homeserver);
1.980     raeburn  15187:     my $protocol = $protocol{$homeserver};
                   15188:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  15189:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  15190:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      15191: # did it work?
                   15192:     if ($response->is_error()) {
                   15193: 	unlink($transferfile);
                   15194: 	&logthis("Userfile repcopy failed for $uri");
                   15195: 	return -1;
                   15196:     }
                   15197: # worked, rename the transfer file
                   15198:     rename($transferfile,$file);
1.607     raeburn  15199:     return 'ok';
1.481     raeburn  15200: }
                   15201: 
1.1532    raeburn  15202: sub repcopy_crsprivfile {
                   15203:     my ($src,$dest) = @_;
                   15204:     my $result;
                   15205:     if ($src =~ m{^/priv/($match_domain)/($match_courseid)/(.+)$}) {
                   15206:         my ($cdom,$cnum,$filepath) = ($1,$2,$3);
                   15207:         $filepath =~ s/\.{2,}//g;
                   15208:         my $chome = &homeserver($cnum,$cdom);
                   15209:         unless ($chome eq 'no_host') {
                   15210:             my @ids=&current_machine_ids();
                   15211:             unless (grep(/^\Q$chome\E$/,@ids)) {
                   15212:                 if (&is_course($cdom,$cnum)) {
                   15213:                     my $londocroot = $perlvar{'lonDocRoot'};
                   15214:                     if ($dest =~ m{^\Q$londocroot/priv/\E$match_domain/$match_username/.*\Q$filepath\E$}) {
                   15215:                         my $cmd = 'crsfilefrompriv:'.&escape($filepath).':'.&escape($cnum).':'.&escape($cdom);
                   15216:                         $result = &reply($cmd,$chome);
                   15217:                         unless (($result eq 'unknown_cmd') || ($result =~ /^error:/)) {
                   15218:                             my $url = &unescape($result);
                   15219:                             if ($url =~ m{^https?://[^/]+\Q/userfiles/$cdom/$cnum/priv/$filepath\E$}) {
                   15220:                                 my $request=new HTTP::Request('GET',$url);
                   15221:                                 my $response=&LONCAPA::LWPReq::makerequest($chome,$request,'',\%perlvar,1200,1);
                   15222:                                 if ($response->is_error()) {
                   15223:                                     $result = 'error: '.$response->status_line;
                   15224:                                 } else {
                   15225:                                     if (open(my $fh,'>',$dest)) {
                   15226:                                         print $fh $response->content;
                   15227:                                         close($fh);
                   15228:                                         $result = 'ok';
                   15229:                                     } else {
                   15230:                                         $result = 'error: nowrite';
                   15231:                                     }
                   15232:                                 }
                   15233:                             } else {
                   15234:                                 $result = 'error: invalidurl';
                   15235:                             }
                   15236:                         }
                   15237:                     }
                   15238:                 }
                   15239:             }
                   15240:         }
                   15241:     }
                   15242:     return $result;
                   15243: }
                   15244: 
1.517     albertel 15245: sub tokenwrapper {
                   15246:     my $uri=shift;
1.980     raeburn  15247:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 15248:     $uri=~s|^/||;
1.620     albertel 15249:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 15250:     my $token=$1;
1.552     albertel 15251:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   15252:     if ($udom && $uname && $file) {
                   15253: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  15254:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  15255:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  15256:         my $hostname = &hostname($homeserver);
1.980     raeburn  15257:         my $protocol = $protocol{$homeserver};
                   15258:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  15259:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 15260:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   15261:                                '&tokenissued='.$perlvar{'lonHostID'};
                   15262:     } else {
                   15263:         return '/adm/notfound.html';
                   15264:     }
                   15265: }
                   15266: 
1.828     www      15267: # call with reqtype HEAD: get last modification time
                   15268: # call with reqtype GET: get the file contents
                   15269: # Do not call this with reqtype GET for large files! It loads everything into memory
                   15270: #
1.481     raeburn  15271: sub getuploaded {
                   15272:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   15273:     $uri=~s/^\///;
1.980     raeburn  15274:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  15275:     my $hostname = &hostname($homeserver);
1.980     raeburn  15276:     my $protocol = $protocol{$homeserver};
                   15277:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  15278:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  15279:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  15280:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  15281:     $$rtncode = $response->code;
1.482     albertel 15282:     if (! $response->is_success()) {
                   15283: 	return 'failed';
                   15284:     }      
                   15285:     if ($reqtype eq 'HEAD') {
1.486     www      15286: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 15287:     } elsif ($reqtype eq 'GET') {
                   15288: 	$$info = $response->content;
1.472     albertel 15289:     }
1.482     albertel 15290:     return 'ok';
1.36      albertel 15291: }
                   15292: 
1.481     raeburn  15293: sub readfile {
                   15294:     my $file = shift;
                   15295:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   15296:     my $fh;
1.1359    raeburn  15297:     open($fh,"<",$file);
1.481     raeburn  15298:     my $a='';
1.800     albertel 15299:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  15300:     return $a;
                   15301: }
                   15302: 
1.36      albertel 15303: sub filelocation {
1.590     banghart 15304:     my ($dir,$file) = @_;
                   15305:     my $location;
                   15306:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 15307: 
                   15308:     if ($file =~ m-^/adm/-) {
                   15309: 	$file=~s-^/adm/wrapper/-/-;
                   15310: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   15311:     }
1.882     albertel 15312: 
1.1139    www      15313:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  15314:         $location = $file;
1.609     banghart 15315:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 15316:         my ($udom,$uname,$filename)=
1.811     albertel 15317:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 15318:         my $home=&homeserver($uname,$udom);
                   15319:         my $is_me=0;
                   15320:         my @ids=&current_machine_ids();
                   15321:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   15322:         if ($is_me) {
1.1117    foxr     15323:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 15324:         } else {
                   15325:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   15326:   	      $udom.'/'.$uname.'/'.$filename;
                   15327:         }
1.882     albertel 15328:     } elsif ($file =~ m-^/adm/-) {
                   15329: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 15330:     } else {
                   15331:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      15332:         $file=~s:^/(res|priv)/:/:;
                   15333:         my $space=$1;
1.590     banghart 15334:         if ( !( $file =~ m:^/:) ) {
                   15335:             $location = $dir. '/'.$file;
                   15336:         } else {
1.1142    raeburn  15337:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 15338:         }
1.59      albertel 15339:     }
1.590     banghart 15340:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 15341:     while ($location=~m{/\.\./}) {
                   15342: 	if ($location =~ m{/[^/]+/\.\./}) {
                   15343: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   15344: 	} else {
                   15345: 	    $location=~ s{/\.\./}{/}g;
                   15346: 	}
                   15347:     } #remove dir/..
1.590     banghart 15348:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   15349:     return $location;
1.46      www      15350: }
1.36      albertel 15351: 
1.46      www      15352: sub hreflocation {
                   15353:     my ($dir,$file)=@_;
1.980     raeburn  15354:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 15355: 	$file=filelocation($dir,$file);
1.700     albertel 15356:     } elsif ($file=~m-^/adm/-) {
                   15357: 	$file=~s-^/adm/wrapper/-/-;
                   15358: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 15359:     }
                   15360:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   15361: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   15362:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  15363: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   15364: 	        {/uploaded/$1/$2/}x;
1.46      www      15365:     }
1.913     albertel 15366:     if ($file=~ m{^/userfiles/}) {
                   15367: 	$file =~ s{^/userfiles/}{/uploaded/};
                   15368:     }
1.462     albertel 15369:     return $file;
1.465     albertel 15370: }
                   15371: 
1.1139    www      15372: 
                   15373: 
                   15374: 
                   15375: 
1.465     albertel 15376: sub current_machine_domains {
1.853     albertel 15377:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   15378: }
                   15379: 
                   15380: sub machine_domains {
                   15381:     my ($hostname) = @_;
1.465     albertel 15382:     my @domains;
1.838     albertel 15383:     my %hostname = &all_hostnames();
1.465     albertel 15384:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  15385: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 15386: 	if ($hostname eq $name) {
1.844     albertel 15387: 	    push(@domains,&host_domain($id));
1.465     albertel 15388: 	}
                   15389:     }
                   15390:     return @domains;
                   15391: }
                   15392: 
                   15393: sub current_machine_ids {
1.853     albertel 15394:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   15395: }
                   15396: 
                   15397: sub machine_ids {
                   15398:     my ($hostname) = @_;
                   15399:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 15400:     my @ids;
1.888     albertel 15401:     my %name_to_host = &all_names();
1.889     albertel 15402:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   15403: 	return @{ $name_to_host{$hostname} };
                   15404:     }
                   15405:     return;
1.31      www      15406: }
                   15407: 
1.824     raeburn  15408: sub additional_machine_domains {
                   15409:     my @domains;
1.1466    raeburn  15410:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   15411:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   15412:             while (my $line = <$fh>) {
                   15413:                 chomp($line);           
                   15414:                 $line =~ s/\s//g;
                   15415:                 push(@domains,$line);
                   15416:             }
                   15417:             close($fh);
                   15418:         }
1.824     raeburn  15419:     }
                   15420:     return @domains;
                   15421: }
                   15422: 
                   15423: sub default_login_domain {
                   15424:     my $domain = $perlvar{'lonDefDomain'};
                   15425:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   15426:     foreach my $posdom (&current_machine_domains(),
                   15427:                         &additional_machine_domains()) {
                   15428:         if (lc($posdom) eq lc($testdomain)) {
                   15429:             $domain=$posdom;
                   15430:             last;
                   15431:         }
                   15432:     }
                   15433:     return $domain;
                   15434: }
                   15435: 
1.1414    raeburn  15436: sub shared_institution {
1.1439    raeburn  15437:     my ($dom,$lonhost) = @_;
                   15438:     if ($lonhost eq '') {
                   15439:         $lonhost = $perlvar{'lonHostID'};
                   15440:     }
1.1414    raeburn  15441:     my $same_intdom;
1.1439    raeburn  15442:     my $hostintdom = &internet_dom($lonhost);
1.1414    raeburn  15443:     if ($hostintdom ne '') {
                   15444:         my %iphost = &get_iphost();
                   15445:         my $primary_id = &domain($dom,'primary');
                   15446:         my $primary_ip = &get_host_ip($primary_id);
                   15447:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   15448:             foreach my $id (@{$iphost{$primary_ip}}) {
                   15449:                 my $intdom = &internet_dom($id);
                   15450:                 if ($intdom eq $hostintdom) {
                   15451:                     $same_intdom = 1;
                   15452:                     last;
                   15453:                 }
                   15454:             }
                   15455:         }
                   15456:     }
                   15457:     return $same_intdom;
                   15458: }
                   15459: 
1.1398    raeburn  15460: sub uses_sts {
                   15461:     my ($ignore_cache) = @_;
                   15462:     my $lonhost = $perlvar{'lonHostID'};
                   15463:     my $hostname = &hostname($lonhost);
                   15464:     my $sts_on;
                   15465:     if ($protocol{$lonhost} eq 'https') {
                   15466:         my $cachetime = 12*3600;
                   15467:         if (!$ignore_cache) {
                   15468:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   15469:             if (defined($cached)) {
                   15470:                 return $sts_on;
                   15471:             }
                   15472:         }
                   15473:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   15474:         my $request=new HTTP::Request('HEAD',$url);
                   15475:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   15476:         if ($response->is_success) {
                   15477:             my $has_sts = $response->header('Strict-Transport-Security');
                   15478:             if ($has_sts eq '') {
                   15479:                 $sts_on = 0;
                   15480:             } else {
                   15481:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   15482:                     my $maxage = $1;
                   15483:                     if ($maxage) {
                   15484:                         $sts_on = 1;
                   15485:                     } else {
                   15486:                         $sts_on = 0;
                   15487:                     }
                   15488:                 } else {
                   15489:                     $sts_on = 0;
                   15490:                 }
                   15491:             }
                   15492:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   15493:         }
                   15494:     }
                   15495:     return;
                   15496: }
                   15497: 
1.1449    raeburn  15498: sub waf_allssl {
                   15499:     my ($host_name) = @_;
                   15500:     my $alias = &get_proxy_alias();
                   15501:     if ($host_name eq '') {
                   15502:         $host_name = $ENV{'SERVER_NAME'};
                   15503:     }
                   15504:     if (($host_name ne '') && ($alias eq $host_name)) {
                   15505:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   15506:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   15507:         if ($defdomdefaults{'waf_sslopt'}) {
                   15508:             return $defdomdefaults{'waf_sslopt'};
                   15509:         }
                   15510:     }
                   15511:     return;
                   15512: }
                   15513: 
1.1434    raeburn  15514: sub get_requestor_ip {
                   15515:     my ($r,$nolookup,$noproxy) = @_;
                   15516:     my $from_ip;
                   15517:     if (ref($r)) {
1.1447    raeburn  15518:         if ($r->can('useragent_ip')) {
                   15519:             if ($noproxy && $r->can('client_ip')) {
                   15520:                 $from_ip = $r->client_ip();
                   15521:             } else {
                   15522:                 $from_ip = $r->useragent_ip();
                   15523:             }
                   15524:         } elsif ($r->connection->can('remote_ip')) {
                   15525:             $from_ip = $r->connection->remote_ip();
                   15526:         } else {
                   15527:             $from_ip = $r->get_remote_host($nolookup);
                   15528:         }
1.1434    raeburn  15529:     } else {
                   15530:         $from_ip = $ENV{'REMOTE_ADDR'};
                   15531:     }
                   15532:     return $from_ip if ($noproxy); 
                   15533:     # Who controls proxy settings for server
                   15534:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15535:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   15536:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437    raeburn  15537:         if ($proxyinfo->{'vpnint'}) {
                   15538:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434    raeburn  15539:                 return $from_ip;
                   15540:             }
                   15541:         }
                   15542:         if ($proxyinfo->{'trusted'}) {
                   15543:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   15544:                 my $ipheader = $proxyinfo->{'ipheader'};
                   15545:                 my ($ip,$xfor);
                   15546:                 if (ref($r)) {
                   15547:                     if ($ipheader) {
                   15548:                         $ip = $r->headers_in->{$ipheader};
                   15549:                     }
                   15550:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   15551:                 } else {
                   15552:                     if ($ipheader) {
                   15553:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   15554:                     }
                   15555:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   15556:                 }
                   15557:                 if (($ip eq '') && ($xfor ne '')) {
                   15558:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   15559:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   15560:                             $ip = $poss_ip;
1.1435    raeburn  15561:                             last;
1.1434    raeburn  15562:                         }
                   15563:                     }
                   15564:                 }
                   15565:                 if ($ip ne '') {
                   15566:                     return $ip;
                   15567:                 }
                   15568:             }
                   15569:         }
                   15570:     }
                   15571:     return $from_ip;
                   15572: }
                   15573: 
                   15574: sub get_proxy_settings {
                   15575:     my ($dom_in_use) = @_;
1.1494    raeburn  15576:     my %domdefaults = &get_domain_defaults($dom_in_use);
1.1434    raeburn  15577:     my $proxyinfo = {
                   15578:                        ipheader => $domdefaults{'waf_ipheader'},
                   15579:                        trusted  => $domdefaults{'waf_trusted'},
1.1437    raeburn  15580:                        vpnint   => $domdefaults{'waf_vpnint'},
1.1438    raeburn  15581:                        vpnext   => $domdefaults{'waf_vpnext'},
1.1449    raeburn  15582:                        sslopt   => $domdefaults{'waf_sslopt'},
1.1434    raeburn  15583:                     };
                   15584:     return $proxyinfo;
                   15585: }
                   15586: 
                   15587: sub ip_match {
                   15588:     my ($ip,$pattern_str) = @_;
                   15589:     $ip=Net::CIDR::cidrvalidate($ip);
                   15590:     if ($ip) {
                   15591:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   15592:     }
                   15593:     return;
                   15594: }
                   15595: 
                   15596: sub get_proxy_alias {
1.1450    raeburn  15597:     my ($lonid) = @_;
                   15598:     if ($lonid eq '') {
                   15599:         $lonid = $perlvar{'lonHostID'};
                   15600:     }
                   15601:     if (!defined(&hostname($lonid))) {
                   15602:         return;
                   15603:     }
                   15604:     if ($lonid ne '') {
                   15605:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434    raeburn  15606:         if ($cached) {
                   15607:             return $alias;
                   15608:         }
1.1494    raeburn  15609:         my $dom = &host_domain($lonid);
1.1434    raeburn  15610:         if ($dom ne '') {
                   15611:             my $cachetime = 60*60*24;
                   15612:             my %domconfig =
1.1494    raeburn  15613:                 &get_dom('configuration',['wafproxy'],$dom);
1.1437    raeburn  15614:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   15615:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450    raeburn  15616:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   15617:                 }
                   15618:             }
                   15619:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   15620:         }
                   15621:     }
                   15622:     return;
                   15623: }
                   15624: 
                   15625: sub use_proxy_alias {
                   15626:     my ($r,$lonid) = @_;
                   15627:     my $alias = &get_proxy_alias($lonid);
                   15628:     if ($alias) {
                   15629:         my $dom = &host_domain($lonid);
                   15630:         if ($dom ne '') {
1.1467    raeburn  15631:             my $proxyinfo = &get_proxy_settings($dom);
1.1450    raeburn  15632:             my ($vpnint,$remote_ip);
                   15633:             if (ref($proxyinfo) eq 'HASH') {
                   15634:                 $vpnint = $proxyinfo->{'vpnint'};
                   15635:                 if ($vpnint) {
                   15636:                     $remote_ip = &get_requestor_ip($r,1,1);
1.1434    raeburn  15637:                 }
                   15638:             }
1.1450    raeburn  15639:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   15640:                 return $alias;
                   15641:             }
1.1434    raeburn  15642:         }
                   15643:     }
                   15644:     return;
                   15645: }
                   15646: 
1.1474    raeburn  15647: sub alias_sso {
1.1467    raeburn  15648:     my ($lonid) = @_;
                   15649:     if ($lonid eq '') {
                   15650:         $lonid = $perlvar{'lonHostID'};
                   15651:     }
                   15652:     if (!defined(&hostname($lonid))) {
                   15653:         return;
                   15654:     }
                   15655:     if ($lonid ne '') {
                   15656:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   15657:         if ($cached) {
                   15658:             return $use_alias;
                   15659:         }
1.1494    raeburn  15660:         my $dom = &host_domain($lonid);
1.1467    raeburn  15661:         if ($dom ne '') {
                   15662:             my $cachetime = 60*60*24;
                   15663:             my %domconfig =
1.1494    raeburn  15664:                 &get_dom('configuration',['wafproxy'],$dom);
1.1467    raeburn  15665:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   15666:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   15667:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   15668:                 }
                   15669:             }
                   15670:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   15671:         }
                   15672:     }
                   15673:     return;
                   15674: }
                   15675: 
1.1465    raeburn  15676: sub get_saml_landing {
                   15677:     my ($lonid) = @_;
                   15678:     if ($lonid eq '') {
                   15679:         my $defdom = &default_login_domain();
                   15680:         my @hosts = &current_machine_ids();
                   15681:         if (@hosts > 1) {
                   15682:             foreach my $hostid (@hosts) {
                   15683:                 if (&host_domain($hostid) eq $defdom) {
                   15684:                     $lonid = $hostid;
                   15685:                     last;
                   15686:                 }
                   15687:             }
                   15688:         } else {
                   15689:             $lonid = $perlvar{'lonHostID'};
                   15690:         }
                   15691:         if ($lonid) {
1.1494    raeburn  15692:             unless (&host_domain($lonid) eq $defdom) {
1.1465    raeburn  15693:                 return;
                   15694:             }
                   15695:         } else {
                   15696:             return;
                   15697:         }
                   15698:     } elsif (!defined(&hostname($lonid))) {
                   15699:         return;
                   15700:     }
                   15701:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   15702:     if ($cached) {
                   15703:         return $landing;
                   15704:     }
1.1494    raeburn  15705:     my $dom = &host_domain($lonid);
1.1465    raeburn  15706:     if ($dom ne '') {
                   15707:         my $cachetime = 60*60*24;
                   15708:         my %domconfig =
1.1494    raeburn  15709:             &get_dom('configuration',['login'],$dom);
1.1465    raeburn  15710:         if (ref($domconfig{'login'}) eq 'HASH') {
                   15711:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   15712:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   15713:                     $landing = 1;
                   15714:                 }
                   15715:             }
                   15716:         }
                   15717:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   15718:     }
                   15719:     return;
                   15720: }
                   15721: 
1.31      www      15722: # ------------------------------------------------------------- Declutters URLs
                   15723: 
                   15724: sub declutter {
                   15725:     my $thisfn=shift;
1.569     albertel 15726:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  15727:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   15728:         $thisfn=~s{^/home/httpd/html}{};
                   15729:     }
1.31      www      15730:     $thisfn=~s/^\///;
1.697     albertel 15731:     $thisfn=~s|^adm/wrapper/||;
                   15732:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      15733:     $thisfn=~s/^res\///;
1.1172    bisitz   15734:     $thisfn=~s/^priv\///;
1.1032    raeburn  15735:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   15736:         $thisfn=~s/\?.+$//;
                   15737:     }
1.268     www      15738:     return $thisfn;
                   15739: }
                   15740: 
                   15741: # ------------------------------------------------------------- Clutter up URLs
                   15742: 
                   15743: sub clutter {
                   15744:     my $thisfn='/'.&declutter(shift);
1.887     albertel 15745:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 15746: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      15747:        $thisfn='/res'.$thisfn; 
                   15748:     }
1.1031    raeburn  15749:     if ($thisfn !~m|^/adm|) {
                   15750: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 15751: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 15752: 	} else {
                   15753: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   15754: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 15755: 	    if ($embstyle eq 'ssi'
                   15756: 		|| ($embstyle eq 'hdn')
                   15757: 		|| ($embstyle eq 'rat')
                   15758: 		|| ($embstyle eq 'prv')
                   15759: 		|| ($embstyle eq 'ign')) {
                   15760: 		#do nothing with these
                   15761: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 15762: 		|| ($embstyle eq 'emb')
                   15763: 		|| ($embstyle eq 'wrp')) {
                   15764: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 15765: 	    } elsif ($embstyle eq 'unk'
                   15766: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 15767: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 15768: 	    } else {
1.718     www      15769: #		&logthis("Got a blank emb style");
1.695     albertel 15770: 	    }
1.694     albertel 15771: 	}
1.1343    raeburn  15772:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  15773:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 15774:     }
1.31      www      15775:     return $thisfn;
1.12      www      15776: }
                   15777: 
1.787     albertel 15778: sub clutter_with_no_wrapper {
                   15779:     my $uri = &clutter(shift);
                   15780:     if ($uri =~ m-^/adm/-) {
                   15781: 	$uri =~ s-^/adm/wrapper/-/-;
                   15782: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   15783:     }
                   15784:     return $uri;
                   15785: }
                   15786: 
1.557     albertel 15787: sub freeze_escape {
                   15788:     my ($value)=@_;
                   15789:     if (ref($value)) {
                   15790: 	$value=&nfreeze($value);
                   15791: 	return '__FROZEN__'.&escape($value);
                   15792:     }
                   15793:     return &escape($value);
                   15794: }
                   15795: 
1.11      www      15796: 
1.557     albertel 15797: sub thaw_unescape {
                   15798:     my ($value)=@_;
                   15799:     if ($value =~ /^__FROZEN__/) {
                   15800: 	substr($value,0,10,undef);
                   15801: 	$value=&unescape($value);
                   15802: 	return &thaw($value);
                   15803:     }
                   15804:     return &unescape($value);
                   15805: }
                   15806: 
1.436     albertel 15807: sub correct_line_ends {
                   15808:     my ($result)=@_;
                   15809:     $$result =~s/\r\n/\n/mg;
                   15810:     $$result =~s/\r/\n/mg;
1.415     albertel 15811: }
1.1       albertel 15812: # ================================================================ Main Program
                   15813: 
1.184     www      15814: sub goodbye {
1.204     albertel 15815:    &logthis("Starting Shut down");
1.443     albertel 15816: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 15817:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 15818: #converted
1.599     albertel 15819: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 15820:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   15821: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   15822: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 15823: #1.1 only
1.870     albertel 15824: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   15825: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   15826: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   15827: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   15828:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 15829:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   15830:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      15831:    &flushcourselogs();
                   15832:    &logthis("Shutting down");
                   15833: }
                   15834: 
1.852     albertel 15835: sub get_dns {
1.1210    raeburn  15836:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 15837:     if (!$ignore_cache) {
                   15838: 	my ($content,$cached)=
1.1494    raeburn  15839: 	    &is_cached_new('dns',$url);
1.869     albertel 15840: 	if ($cached) {
1.1210    raeburn  15841: 	    &$func($content,$hashref);
1.869     albertel 15842: 	    return;
                   15843: 	}
                   15844:     }
                   15845: 
                   15846:     my %alldns;
1.1379    raeburn  15847:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   15848:         foreach my $dns (<$config>) {
                   15849: 	    next if ($dns !~ /^\^(\S*)/x);
                   15850:             my $line = $1;
                   15851:             my ($host,$protocol) = split(/:/,$line);
                   15852:             if ($protocol ne 'https') {
                   15853:                 $protocol = 'http';
                   15854:             }
                   15855: 	    $alldns{$host} = $protocol;
1.979     raeburn  15856:         }
1.1379    raeburn  15857:         close($config);
1.869     albertel 15858:     }
                   15859:     while (%alldns) {
1.1263    raeburn  15860: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456    raeburn  15861:         my ($contents,@content);
                   15862:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   15863:             my $command = (split('/',$url))[3];
                   15864:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   15865:             delete($alldns{$dns});
                   15866:             next if (($dir eq '') || ($file eq ''));
                   15867:             if (open(my $config,'<',"$dir/$file")) {
1.1457    raeburn  15868:                 @content = <$config>;
1.1456    raeburn  15869:                 close($config);
                   15870:             }
                   15871:             if ($url eq '/adm/dns/loncapaCRL') {
                   15872:                 $contents = join('',@content);
                   15873:             }
                   15874:         } else {
                   15875: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   15876:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
                   15877:             delete($alldns{$dns});
                   15878: 	    next if ($response->is_error());
                   15879:             if ($url eq '/adm/dns/loncapaCRL') {
                   15880:                 $contents = $response->content;
                   15881:             } else {
                   15882:                 @content = split("\n",$response->content);
                   15883:             }
                   15884:         }
1.1379    raeburn  15885:         if ($url eq '/adm/dns/loncapaCRL') {
1.1456    raeburn  15886:             return &$func($contents);
1.1379    raeburn  15887:         } else {
                   15888: 	    unless ($nocache) {
                   15889: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   15890: 	    }
                   15891: 	    &$func(\@content,$hashref);
                   15892:             return;
                   15893:         }
                   15894:     }
                   15895:     my $which = (split('/',$url,4))[3];
                   15896:     if ($which eq 'loncapaCRL') {
                   15897:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   15898:         if (-e $diskfile) {
                   15899:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   15900:         } else {
                   15901:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   15902:         }
                   15903:     } else {
                   15904:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   15905:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   15906:             my @content = <$config>;
                   15907:             close($config);
                   15908:             &$func(\@content,$hashref);
                   15909:         }
1.852     albertel 15910:     }
1.1210    raeburn  15911:     return;
                   15912: }
                   15913: 
                   15914: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  15915: sub parse_dns_checksums_tab {
1.1210    raeburn  15916:     my ($lines,$hashref) = @_;
1.1264    raeburn  15917:     my $lonhost = $perlvar{'lonHostID'};
1.1494    raeburn  15918:     my $machine_dom = &host_domain($lonhost);
1.1210    raeburn  15919:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  15920:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   15921:     my $webconfdir = '/etc/httpd/conf';
                   15922:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   15923:         $webconfdir = '/etc/apache2';
                   15924:     } elsif ($distro =~ /^sles(\d+)$/) {
                   15925:         if ($1 >= 10) {
                   15926:             $webconfdir = '/etc/apache2';
                   15927:         }
                   15928:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   15929:         if ($1 >= 10.0) {
                   15930:             $webconfdir = '/etc/apache2';
                   15931:         }
                   15932:     }
1.1210    raeburn  15933:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15934:     my (%chksum,%revnum);
                   15935:     if (ref($lines) eq 'ARRAY') {
                   15936:         chomp(@{$lines});
1.1238    raeburn  15937:         my $version = shift(@{$lines});
                   15938:         if ($version eq $release) {  
1.1210    raeburn  15939:             foreach my $line (@{$lines}) {
1.1238    raeburn  15940:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  15941:                 if ($file =~ m{^/etc/httpd/conf}) {
                   15942:                     if ($webconfdir eq '/etc/apache2') {
                   15943:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   15944:                     }
                   15945:                 }
1.1238    raeburn  15946:                 $chksum{$file} = $shasum;
                   15947:                 $revnum{$file} = $version;
1.1210    raeburn  15948:             }
                   15949:             if (ref($hashref) eq 'HASH') {
                   15950:                 %{$hashref} = (
                   15951:                                 sums     => \%chksum,
                   15952:                                 versions => \%revnum,
                   15953:                               );
                   15954:             }
                   15955:         }
                   15956:     }
1.869     albertel 15957:     return;
1.852     albertel 15958: }
1.1210    raeburn  15959: 
                   15960: sub fetch_dns_checksums {
1.1238    raeburn  15961:     my %checksums;
1.1494    raeburn  15962:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
1.1260    raeburn  15963:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  15964:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15965:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  15966:              \%checksums);
1.1210    raeburn  15967:     return \%checksums;
                   15968: }
                   15969: 
1.1379    raeburn  15970: sub fetch_crl_pemfile {
                   15971:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   15972: }
                   15973: 
                   15974: sub save_crl_pem {
1.1456    raeburn  15975:     my ($content) = @_;
1.1380    raeburn  15976:     my ($msg,$hadchanges);
1.1456    raeburn  15977:     if ($content ne '') {
1.1379    raeburn  15978:         my $now = time;
                   15979:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   15980:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   15981:         if (open(my $fh,'>',"$tmpcrl")) {
1.1456    raeburn  15982:             print $fh $content;
1.1379    raeburn  15983:             close($fh);
                   15984:             if (-e $lonca) {
                   15985:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   15986:                     my $check = <PIPE>;
                   15987:                     close(PIPE);
                   15988:                     chomp($check);
                   15989:                     if ($check eq 'verify OK') {
                   15990:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  15991:                         my $backup;
1.1379    raeburn  15992:                         if (-e $dest) {
1.1380    raeburn  15993:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   15994:                                 $backup = 'ok';
                   15995:                             }
1.1379    raeburn  15996:                         }
                   15997:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   15998:                             $msg = 'ok';
1.1380    raeburn  15999:                             if ($backup) {
                   16000:                                 my (%oldnums,%newnums);
                   16001:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   16002:                                     while (<PIPE>) {
                   16003:                                         $oldnums{(split(/:/))[1]} = 1;
                   16004:                                     }
                   16005:                                     close(PIPE);
                   16006:                                 }
                   16007:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   16008:                                     while(<PIPE>) {
                   16009:                                         $newnums{(split(/:/))[1]} = 1;
                   16010:                                     }
                   16011:                                     close(PIPE);
                   16012:                                 }
                   16013:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   16014:                                     unless (exists($oldnums{$key})) {
                   16015:                                         $hadchanges = 1;
                   16016:                                         last;
                   16017:                                     }
                   16018:                                 }
                   16019:                                 unless ($hadchanges) {
                   16020:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   16021:                                         unless (exists($newnums{$key})) {
                   16022:                                             $hadchanges = 1;
                   16023:                                             last;
                   16024:                                         }
                   16025:                                     }
                   16026:                                 }
                   16027:                             }
1.1379    raeburn  16028:                         }
                   16029:                     } else {
                   16030:                         unlink($tmpcrl);
                   16031:                     }
                   16032:                 } else {
                   16033:                     unlink($tmpcrl);
                   16034:                 }
                   16035:             } else {
                   16036:                 unlink($tmpcrl);
                   16037:             }
                   16038:         }
                   16039:     }
1.1380    raeburn  16040:     return ($msg,$hadchanges);
1.1379    raeburn  16041: }
                   16042: 
1.1456    raeburn  16043: sub parse_getdns_url {
                   16044:     my ($command,$url) = @_;
                   16045:     my $dir = $perlvar{'lonTabDir'};
                   16046:     my $file;
                   16047:     if ($command eq 'hosts') {
                   16048:         $file = 'dns_hosts.tab';
                   16049:     } elsif ($command eq 'domain') {
                   16050:         $file = 'dns_domain.tab';
                   16051:     } elsif ($command eq 'checksums') {
                   16052:         my $version = (split('/',$url))[4];
                   16053:         $file = "dns_checksums/$version.tab",
                   16054:     } elsif ($command eq 'loncapaCRL') {
                   16055:         $dir = $perlvar{'lonCertificateDirectory'};
                   16056:         $file = $perlvar{'lonnetCertRevocationList'};
                   16057:     }
                   16058:     return ($dir,$file);
                   16059: }
                   16060: 
1.327     albertel 16061: # ------------------------------------------------------------ Read domain file
                   16062: {
1.852     albertel 16063:     my $loaded;
1.846     albertel 16064:     my %domain;
                   16065: 
1.852     albertel 16066:     sub parse_domain_tab {
                   16067: 	my ($lines) = @_;
                   16068: 	foreach my $line (@$lines) {
                   16069: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      16070: 
1.846     albertel 16071: 	    chomp($line);
1.852     albertel 16072: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 16073: 	    my %this_domain;
                   16074: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   16075: 			       'lang_def', 'city', 'longi', 'lati',
                   16076: 			       'primary') {
                   16077: 		$this_domain{$field} = shift(@elements);
                   16078: 	    }
                   16079: 	    $domain{$name} = \%this_domain;
1.852     albertel 16080: 	}
                   16081:     }
1.864     albertel 16082: 
                   16083:     sub reset_domain_info {
                   16084: 	undef($loaded);
                   16085: 	undef(%domain);
                   16086:     }
                   16087: 
1.852     albertel 16088:     sub load_domain_tab {
1.1293    raeburn  16089: 	my ($ignore_cache,$nocache) = @_;
                   16090: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 16091: 	my $fh;
1.1359    raeburn  16092: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 16093: 	    my @lines = <$fh>;
                   16094: 	    &parse_domain_tab(\@lines);
1.448     albertel 16095: 	}
1.852     albertel 16096: 	close($fh);
                   16097: 	$loaded = 1;
1.327     albertel 16098:     }
1.846     albertel 16099: 
                   16100:     sub domain {
1.852     albertel 16101: 	&load_domain_tab() if (!$loaded);
                   16102: 
1.846     albertel 16103: 	my ($name,$what) = @_;
                   16104: 	return if ( !exists($domain{$name}) );
                   16105: 
                   16106: 	if (!$what) {
                   16107: 	    return $domain{$name}{'description'};
                   16108: 	}
                   16109: 	return $domain{$name}{$what};
                   16110:     }
1.974     raeburn  16111: 
                   16112:     sub domain_info {
                   16113:         &load_domain_tab() if (!$loaded);
                   16114:         return %domain;
                   16115:     }
                   16116: 
1.327     albertel 16117: }
                   16118: 
                   16119: 
1.1       albertel 16120: # ------------------------------------------------------------- Read hosts file
                   16121: {
1.838     albertel 16122:     my %hostname;
1.844     albertel 16123:     my %hostdom;
1.845     albertel 16124:     my %libserv;
1.852     albertel 16125:     my $loaded;
1.888     albertel 16126:     my %name_to_host;
1.1074    raeburn  16127:     my %internetdom;
1.1107    raeburn  16128:     my %LC_dns_serv;
1.852     albertel 16129: 
                   16130:     sub parse_hosts_tab {
                   16131: 	my ($file) = @_;
                   16132: 	foreach my $configline (@$file) {
                   16133: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  16134:             chomp($configline);
                   16135: 	    if ($configline =~ /^\^/) {
                   16136:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   16137:                     $LC_dns_serv{$1} = 1;
                   16138:                 }
                   16139:                 next;
                   16140:             }
1.1074    raeburn  16141: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 16142: 	    $name=~s/\s//g;
                   16143: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  16144:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   16145:                     my $curr = $hostname{$id};
                   16146:                     my $skip;
                   16147:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   16148:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   16149:                             $skip = 1;
                   16150:                         } else {
                   16151:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   16152:                         }
                   16153:                     }
                   16154:                     unless ($skip) {
                   16155:                         push(@{$name_to_host{$name}},$id);
                   16156:                     }
                   16157:                 } else {
                   16158:                     push(@{$name_to_host{$name}},$id);
                   16159:                 }
1.852     albertel 16160: 		$hostname{$id}=$name;
                   16161: 		$hostdom{$id}=$domain;
                   16162: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  16163:                 if (defined($protocol)) {
                   16164:                     if ($protocol eq 'https') {
                   16165:                         $protocol{$id} = $protocol;
                   16166:                     } else {
                   16167:                         $protocol{$id} = 'http'; 
                   16168:                     }
1.968     raeburn  16169:                 } else {
1.969     raeburn  16170:                     $protocol{$id} = 'http';
1.968     raeburn  16171:                 }
1.1074    raeburn  16172:                 if (defined($intdom)) {
                   16173:                     $internetdom{$id} = $intdom;
                   16174:                 }
1.852     albertel 16175: 	    }
                   16176: 	}
                   16177:     }
1.864     albertel 16178:     
                   16179:     sub reset_hosts_info {
1.897     albertel 16180: 	&purge_remembered();
1.864     albertel 16181: 	&reset_domain_info();
                   16182: 	&reset_hosts_ip_info();
1.1339    raeburn  16183:         undef(%internetdom);
1.892     albertel 16184: 	undef(%name_to_host);
1.864     albertel 16185: 	undef(%hostname);
                   16186: 	undef(%hostdom);
                   16187: 	undef(%libserv);
                   16188: 	undef($loaded);
                   16189:     }
1.1       albertel 16190: 
1.852     albertel 16191:     sub load_hosts_tab {
1.1293    raeburn  16192: 	my ($ignore_cache,$nocache) = @_;
                   16193: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  16194: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 16195: 	my @config = <$config>;
                   16196: 	&parse_hosts_tab(\@config);
                   16197: 	close($config);
                   16198: 	$loaded=1;
1.1       albertel 16199:     }
1.852     albertel 16200: 
1.838     albertel 16201:     sub hostname {
1.852     albertel 16202: 	&load_hosts_tab() if (!$loaded);
                   16203: 
1.838     albertel 16204: 	my ($lonid) = @_;
                   16205: 	return $hostname{$lonid};
                   16206:     }
1.845     albertel 16207: 
1.838     albertel 16208:     sub all_hostnames {
1.852     albertel 16209: 	&load_hosts_tab() if (!$loaded);
                   16210: 
1.838     albertel 16211: 	return %hostname;
                   16212:     }
1.845     albertel 16213: 
1.888     albertel 16214:     sub all_names {
1.1293    raeburn  16215:         my ($ignore_cache,$nocache) = @_;
                   16216: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 16217: 
                   16218: 	return %name_to_host;
                   16219:     }
                   16220: 
1.974     raeburn  16221:     sub all_host_domain {
                   16222:         &load_hosts_tab() if (!$loaded);
                   16223:         return %hostdom;
                   16224:     }
                   16225: 
1.1339    raeburn  16226:     sub all_host_intdom {
                   16227:         &load_hosts_tab() if (!$loaded);
                   16228:         return %internetdom;
                   16229:     }
                   16230: 
1.845     albertel 16231:     sub is_library {
1.852     albertel 16232: 	&load_hosts_tab() if (!$loaded);
                   16233: 
1.845     albertel 16234: 	return exists($libserv{$_[0]});
                   16235:     }
                   16236: 
                   16237:     sub all_library {
1.852     albertel 16238: 	&load_hosts_tab() if (!$loaded);
                   16239: 
1.845     albertel 16240: 	return %libserv;
                   16241:     }
                   16242: 
1.1062    droeschl 16243:     sub unique_library {
                   16244: 	#2x reverse removes all hostnames that appear more than once
                   16245:         my %unique = reverse &all_library();
                   16246:         return reverse %unique;
                   16247:     }
                   16248: 
1.841     albertel 16249:     sub get_servers {
1.852     albertel 16250: 	&load_hosts_tab() if (!$loaded);
                   16251: 
1.841     albertel 16252: 	my ($domain,$type) = @_;
                   16253: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   16254: 	                                          : %hostname;
                   16255: 	my %result;
1.842     albertel 16256: 	if (ref($domain) eq 'ARRAY') {
                   16257: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 16258: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 16259: 		    $result{$host} = $hostname;
                   16260: 		}
                   16261: 	    }
                   16262: 	} else {
                   16263: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   16264: 		if ($hostdom{$host} eq $domain) {
                   16265: 		    $result{$host} = $hostname;
                   16266: 		}
1.841     albertel 16267: 	    }
                   16268: 	}
                   16269: 	return %result;
                   16270:     }
1.845     albertel 16271: 
1.1062    droeschl 16272:     sub get_unique_servers {
                   16273:         my %unique = reverse &get_servers(@_);
                   16274: 	return reverse %unique;
                   16275:     }
                   16276: 
1.844     albertel 16277:     sub host_domain {
1.852     albertel 16278: 	&load_hosts_tab() if (!$loaded);
                   16279: 
1.844     albertel 16280: 	my ($lonid) = @_;
                   16281: 	return $hostdom{$lonid};
                   16282:     }
                   16283: 
1.841     albertel 16284:     sub all_domains {
1.852     albertel 16285: 	&load_hosts_tab() if (!$loaded);
                   16286: 
1.841     albertel 16287: 	my %seen;
                   16288: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   16289: 	return @uniq;
                   16290:     }
1.1074    raeburn  16291: 
                   16292:     sub internet_dom {
                   16293:         &load_hosts_tab() if (!$loaded);
                   16294: 
                   16295:         my ($lonid) = @_;
                   16296:         return $internetdom{$lonid};
                   16297:     }
1.1107    raeburn  16298: 
                   16299:     sub is_LC_dns {
                   16300:         &load_hosts_tab() if (!$loaded);
                   16301: 
                   16302:         my ($hostname) = @_;
                   16303:         return exists($LC_dns_serv{$hostname});
                   16304:     }
                   16305: 
1.1       albertel 16306: }
                   16307: 
1.847     albertel 16308: { 
                   16309:     my %iphost;
1.856     albertel 16310:     my %name_to_ip;
                   16311:     my %lonid_to_ip;
1.869     albertel 16312: 
1.847     albertel 16313:     sub get_hosts_from_ip {
                   16314: 	my ($ip) = @_;
                   16315: 	my %iphosts = &get_iphost();
                   16316: 	if (ref($iphosts{$ip})) {
                   16317: 	    return @{$iphosts{$ip}};
                   16318: 	}
                   16319: 	return;
1.839     albertel 16320:     }
1.864     albertel 16321:     
                   16322:     sub reset_hosts_ip_info {
                   16323: 	undef(%iphost);
                   16324: 	undef(%name_to_ip);
                   16325: 	undef(%lonid_to_ip);
                   16326:     }
1.856     albertel 16327: 
                   16328:     sub get_host_ip {
                   16329: 	my ($lonid) = @_;
                   16330: 	if (exists($lonid_to_ip{$lonid})) {
                   16331: 	    return $lonid_to_ip{$lonid};
                   16332: 	}
                   16333: 	my $name=&hostname($lonid);
                   16334:    	my $ip = gethostbyname($name);
                   16335: 	return if (!$ip || length($ip) ne 4);
                   16336: 	$ip=inet_ntoa($ip);
                   16337: 	$name_to_ip{$name}   = $ip;
                   16338: 	$lonid_to_ip{$lonid} = $ip;
                   16339: 	return $ip;
                   16340:     }
1.847     albertel 16341:     
                   16342:     sub get_iphost {
1.1293    raeburn  16343: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 16344: 
1.869     albertel 16345: 	if (!$ignore_cache) {
                   16346: 	    if (%iphost) {
                   16347: 		return %iphost;
                   16348: 	    }
                   16349: 	    my ($ip_info,$cached)=
1.1494    raeburn  16350: 		&is_cached_new('iphost','iphost');
1.869     albertel 16351: 	    if ($cached) {
                   16352: 		%iphost      = %{$ip_info->[0]};
                   16353: 		%name_to_ip  = %{$ip_info->[1]};
                   16354: 		%lonid_to_ip = %{$ip_info->[2]};
                   16355: 		return %iphost;
                   16356: 	    }
                   16357: 	}
1.894     albertel 16358: 
                   16359: 	# get yesterday's info for fallback
                   16360: 	my %old_name_to_ip;
                   16361: 	my ($ip_info,$cached)=
1.1495    raeburn  16362: 	    &is_cached_new('iphost','iphost');
1.894     albertel 16363: 	if ($cached) {
                   16364: 	    %old_name_to_ip = %{$ip_info->[1]};
                   16365: 	}
                   16366: 
1.1293    raeburn  16367: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 16368: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 16369: 	    my $ip;
                   16370: 	    if (!exists($name_to_ip{$name})) {
                   16371: 		$ip = gethostbyname($name);
                   16372: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 16373: 		    if (defined($old_name_to_ip{$name})) {
                   16374: 			$ip = $old_name_to_ip{$name};
                   16375: 			&logthis("Can't find $name defaulting to old $ip");
                   16376: 		    } else {
                   16377: 			&logthis("Name $name no IP found");
                   16378: 			next;
                   16379: 		    }
                   16380: 		} else {
                   16381: 		    $ip=inet_ntoa($ip);
1.847     albertel 16382: 		}
                   16383: 		$name_to_ip{$name} = $ip;
                   16384: 	    } else {
                   16385: 		$ip = $name_to_ip{$name};
1.653     albertel 16386: 	    }
1.888     albertel 16387: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   16388: 		$lonid_to_ip{$id} = $ip;
                   16389: 	    }
                   16390: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 16391: 	}
1.1293    raeburn  16392:         unless ($nocache) {
                   16393: 	    &do_cache_new('iphost','iphost',
                   16394: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   16395: 		          48*60*60);
                   16396:         }
1.869     albertel 16397: 
1.847     albertel 16398: 	return %iphost;
1.598     albertel 16399:     }
                   16400: 
1.992     raeburn  16401:     #
                   16402:     #  Given a DNS returns the loncapa host name for that DNS 
                   16403:     # 
                   16404:     sub host_from_dns {
                   16405:         my ($dns) = @_;
                   16406:         my @hosts;
                   16407:         my $ip;
                   16408: 
1.993     raeburn  16409:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  16410:             $ip = $name_to_ip{$dns};
                   16411:         }
                   16412:         if (!$ip) {
                   16413:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   16414:             if (length($ip) == 4) { 
                   16415: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   16416:             }
                   16417:         }
                   16418:         if ($ip) {
                   16419: 	    @hosts = get_hosts_from_ip($ip);
                   16420: 	    return $hosts[0];
                   16421:         }
                   16422:         return undef;
1.986     foxr     16423:     }
1.992     raeburn  16424: 
1.1074    raeburn  16425:     sub get_internet_names {
                   16426:         my ($lonid) = @_;
                   16427:         return if ($lonid eq '');
                   16428:         my ($idnref,$cached)=
1.1494    raeburn  16429:             &is_cached_new('internetnames',$lonid);
1.1074    raeburn  16430:         if ($cached) {
                   16431:             return $idnref;
                   16432:         }
                   16433:         my $ip = &get_host_ip($lonid);
                   16434:         my @hosts = &get_hosts_from_ip($ip);
                   16435:         my %iphost = &get_iphost();
                   16436:         my (@idns,%seen);
                   16437:         foreach my $id (@hosts) {
                   16438:             my $dom = &host_domain($id);
                   16439:             my $prim_id = &domain($dom,'primary');
                   16440:             my $prim_ip = &get_host_ip($prim_id);
                   16441:             next if ($seen{$prim_ip});
                   16442:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   16443:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   16444:                     my $intdom = &internet_dom($id);
                   16445:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   16446:                         push(@idns,$intdom);
                   16447:                     }
                   16448:                 }
                   16449:             }
                   16450:             $seen{$prim_ip} = 1;
                   16451:         }
1.1219    raeburn  16452:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  16453:     }
                   16454: 
1.986     foxr     16455: }
                   16456: 
1.1079    raeburn  16457: sub all_loncaparevs {
1.1249    raeburn  16458:     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  16459: }
                   16460: 
1.1227    raeburn  16461: # ---------------------------------------------------------- Read loncaparev table
                   16462: {
                   16463:     sub load_loncaparevs { 
                   16464:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  16465:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  16466:                 while (my $configline=<$config>) {
                   16467:                     chomp($configline);
                   16468:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   16469:                     $loncaparevs{$hostid}=$loncaparev;
                   16470:                 }
                   16471:                 close($config);
                   16472:             }
                   16473:         }
                   16474:     }
                   16475: }
                   16476: 
                   16477: # ---------------------------------------------------------- Read serverhostID table
                   16478: {
                   16479:     sub load_serverhomeIDs {
                   16480:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  16481:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  16482:                 while (my $configline=<$config>) {
                   16483:                     chomp($configline);
                   16484:                     my ($name,$id)=split(/:/,$configline);
                   16485:                     $serverhomeIDs{$name}=$id;
                   16486:                 }
                   16487:                 close($config);
                   16488:             }
                   16489:         }
                   16490:     }
                   16491: }
                   16492: 
                   16493: 
1.862     albertel 16494: BEGIN {
                   16495: 
                   16496: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   16497:     unless ($readit) {
                   16498: {
                   16499:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   16500:     %perlvar = (%perlvar,%{$configvars});
                   16501: }
                   16502: 
                   16503: 
1.1       albertel 16504: # ------------------------------------------------------ Read spare server file
                   16505: {
1.1359    raeburn  16506:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 16507: 
                   16508:     while (my $configline=<$config>) {
                   16509:        chomp($configline);
1.284     matthew  16510:        if ($configline) {
1.784     albertel 16511: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 16512: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 16513: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 16514:        }
                   16515:     }
1.448     albertel 16516:     close($config);
1.1       albertel 16517: }
1.11      www      16518: # ------------------------------------------------------------ Read permissions
                   16519: {
1.1359    raeburn  16520:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      16521: 
                   16522:     while (my $configline=<$config>) {
1.448     albertel 16523: 	chomp($configline);
                   16524: 	if ($configline) {
                   16525: 	    my ($role,$perm)=split(/ /,$configline);
                   16526: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   16527: 	}
1.11      www      16528:     }
1.448     albertel 16529:     close($config);
1.11      www      16530: }
                   16531: 
                   16532: # -------------------------------------------- Read plain texts for permissions
                   16533: {
1.1359    raeburn  16534:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      16535: 
                   16536:     while (my $configline=<$config>) {
1.448     albertel 16537: 	chomp($configline);
                   16538: 	if ($configline) {
1.742     raeburn  16539: 	    my ($short,@plain)=split(/:/,$configline);
                   16540:             %{$prp{$short}} = ();
                   16541: 	    if (@plain > 0) {
                   16542:                 $prp{$short}{'std'} = $plain[0];
                   16543:                 for (my $i=1; $i<@plain; $i++) {
                   16544:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   16545:                 }
                   16546:             }
1.448     albertel 16547: 	}
1.135     www      16548:     }
1.448     albertel 16549:     close($config);
1.135     www      16550: }
                   16551: 
                   16552: # ---------------------------------------------------------- Read package table
                   16553: {
1.1359    raeburn  16554:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      16555: 
                   16556:     while (my $configline=<$config>) {
1.483     albertel 16557: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 16558: 	chomp($configline);
                   16559: 	my ($short,$plain)=split(/:/,$configline);
                   16560: 	my ($pack,$name)=split(/\&/,$short);
                   16561: 	if ($plain ne '') {
                   16562: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   16563: 	    $packagetab{$short}=$plain; 
                   16564: 	}
1.11      www      16565:     }
1.448     albertel 16566:     close($config);
1.329     matthew  16567: }
                   16568: 
1.1073    raeburn  16569: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  16570: 
                   16571: &load_loncaparevs();
1.1073    raeburn  16572: 
1.1074    raeburn  16573: # ---------------------------------------------------------- Read serverhostID table
                   16574: 
1.1227    raeburn  16575: &load_serverhomeIDs();
                   16576: 
                   16577: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  16578: {
                   16579:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   16580:     if (-e $file) {
                   16581:         my $parser = HTML::LCParser->new($file);
                   16582:         while (my $token = $parser->get_token()) {
                   16583:             if ($token->[0] eq 'S') {
                   16584:                 my $item = $token->[1];
                   16585:                 my $name = $token->[2]{'name'};
                   16586:                 my $value = $token->[2]{'value'};
1.1285    raeburn  16587:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  16588:                 my $namematch = $token->[2]{'namematch'};
                   16589:                 if ($item eq 'parameter') {
                   16590:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   16591:                         my $release = $parser->get_text();
                   16592:                         $release =~ s/(^\s*|\s*$ )//gx;
                   16593:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   16594:                     }
                   16595:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  16596:                     my $release = $parser->get_text();
                   16597:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  16598:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  16599:                 }
                   16600:             }
                   16601:         }
                   16602:     }
1.1073    raeburn  16603: }
                   16604: 
1.1138    raeburn  16605: # ---------------------------------------------------------- Read managers table
                   16606: {
                   16607:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  16608:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  16609:             while (my $configline=<$config>) {
                   16610:                 chomp($configline);
                   16611:                 next if ($configline =~ /^\#/);
                   16612:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   16613:                     $managerstab{$configline} = 1;
                   16614:                 }
                   16615:             }
                   16616:             close($config);
                   16617:         }
                   16618:     }
                   16619: }
                   16620: 
1.329     matthew  16621: # ------------- set up temporary directory
                   16622: {
1.1117    foxr     16623:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  16624: 
1.11      www      16625: }
                   16626: 
1.1405    raeburn  16627: # ------------- set default texengine (domain default overrides this)
                   16628: {
                   16629:     $deftex = LONCAPA::texengine();
                   16630: }
                   16631: 
1.1416    raeburn  16632: # ------------- set default minimum length for passwords for internal auth users
                   16633: {
                   16634:     $passwdmin = LONCAPA::passwd_min();
                   16635: }
                   16636: 
1.794     albertel 16637: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   16638: 				'compress_threshold'=> 20_000,
                   16639:  			        });
1.185     www      16640: 
1.281     www      16641: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      16642: $dumpcount=0;
1.958     www      16643: $locknum=0;
1.22      www      16644: 
1.163     harris41 16645: &logtouch();
1.672     albertel 16646: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      16647: $readit=1;
1.564     albertel 16648:     {
                   16649: 	use integer;
                   16650: 	my $test=(2**32)+1;
1.568     albertel 16651: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 16652: 	&logthis(" Detected 64bit platform ($_64bit)");
                   16653:     }
1.195     www      16654: }
1.1       albertel 16655: }
1.179     www      16656: 
1.1       albertel 16657: 1;
1.191     harris41 16658: __END__
                   16659: 
1.243     albertel 16660: =pod
                   16661: 
1.191     harris41 16662: =head1 NAME
                   16663: 
1.243     albertel 16664: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 16665: 
                   16666: =head1 SYNOPSIS
                   16667: 
1.243     albertel 16668: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 16669: 
                   16670:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   16671: 
1.243     albertel 16672: Common parameters:
                   16673: 
                   16674: =over 4
                   16675: 
                   16676: =item *
                   16677: 
                   16678: $uname : an internal username (if $cname expecting a course Id specifically)
                   16679: 
                   16680: =item *
                   16681: 
                   16682: $udom : a domain (if $cdom expecting a course's domain specifically)
                   16683: 
                   16684: =item *
                   16685: 
                   16686: $symb : a resource instance identifier
                   16687: 
                   16688: =item *
                   16689: 
                   16690: $namespace : the name of a .db file that contains the data needed or
                   16691: being set.
                   16692: 
                   16693: =back
                   16694: 
1.394     bowersj2 16695: =head1 OVERVIEW
1.191     harris41 16696: 
1.394     bowersj2 16697: lonnet provides subroutines which interact with the
                   16698: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   16699: about classes, users, and resources.
1.243     albertel 16700: 
                   16701: For many of these objects you can also use this to store data about
                   16702: them or modify them in various ways.
1.191     harris41 16703: 
1.394     bowersj2 16704: =head2 Symbs
1.191     harris41 16705: 
1.394     bowersj2 16706: To identify a specific instance of a resource, LON-CAPA uses symbols
                   16707: or "symbs"X<symb>. These identifiers are built from the URL of the
                   16708: map, the resource number of the resource in the map, and the URL of
                   16709: the resource itself. The latter is somewhat redundant, but might help
                   16710: if maps change.
                   16711: 
                   16712: An example is
                   16713: 
                   16714:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   16715: 
                   16716: The respective map entry is
                   16717: 
                   16718:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   16719:   title="Problem 2">
                   16720:  </resource>
                   16721: 
                   16722: Symbs are used by the random number generator, as well as to store and
                   16723: restore data specific to a certain instance of for example a problem.
                   16724: 
                   16725: =head2 Storing And Retrieving Data
                   16726: 
                   16727: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   16728: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   16729: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   16730: is is the non-critical message twin of cstore. These functions are for
                   16731: handlers to store a perl hash to a user's permanent data space in an
                   16732: easy manner, and to retrieve it again on another call. It is expected
                   16733: that a handler would use this once at the beginning to retrieve data,
                   16734: and then again once at the end to send only the new data back.
                   16735: 
                   16736: The data is stored in the user's data directory on the user's
                   16737: homeserver under the ID of the course.
                   16738: 
                   16739: The hash that is returned by restore will have all of the previous
                   16740: value for all of the elements of the hash.
                   16741: 
                   16742: Example:
                   16743: 
                   16744:  #creating a hash
                   16745:  my %hash;
                   16746:  $hash{'foo'}='bar';
                   16747: 
                   16748:  #storing it
                   16749:  &Apache::lonnet::cstore(\%hash);
                   16750: 
                   16751:  #changing a value
                   16752:  $hash{'foo'}='notbar';
                   16753: 
                   16754:  #adding a new value
                   16755:  $hash{'bar'}='foo';
                   16756:  &Apache::lonnet::cstore(\%hash);
                   16757: 
                   16758:  #retrieving the hash
                   16759:  my %history=&Apache::lonnet::restore();
                   16760: 
                   16761:  #print the hash
                   16762:  foreach my $key (sort(keys(%history))) {
                   16763:    print("\%history{$key} = $history{$key}");
                   16764:  }
                   16765: 
                   16766: Will print out:
1.191     harris41 16767: 
1.394     bowersj2 16768:  %history{1:foo} = bar
                   16769:  %history{1:keys} = foo:timestamp
                   16770:  %history{1:timestamp} = 990455579
                   16771:  %history{2:bar} = foo
                   16772:  %history{2:foo} = notbar
                   16773:  %history{2:keys} = foo:bar:timestamp
                   16774:  %history{2:timestamp} = 990455580
                   16775:  %history{bar} = foo
                   16776:  %history{foo} = notbar
                   16777:  %history{timestamp} = 990455580
                   16778:  %history{version} = 2
                   16779: 
                   16780: Note that the special hash entries C<keys>, C<version> and
                   16781: C<timestamp> were added to the hash. C<version> will be equal to the
                   16782: total number of versions of the data that have been stored. The
                   16783: C<timestamp> attribute will be the UNIX time the hash was
                   16784: stored. C<keys> is available in every historical section to list which
                   16785: keys were added or changed at a specific historical revision of a
                   16786: hash.
                   16787: 
                   16788: B<Warning>: do not store the hash that restore returns directly. This
                   16789: will cause a mess since it will restore the historical keys as if the
                   16790: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 16791: 
1.394     bowersj2 16792: Calling convention:
1.191     harris41 16793: 
1.1225    raeburn  16794:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  16795:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 16796: 
1.394     bowersj2 16797: For more detailed information, see lonnet specific documentation.
1.191     harris41 16798: 
1.394     bowersj2 16799: =head1 RETURN MESSAGES
1.191     harris41 16800: 
1.394     bowersj2 16801: =over 4
1.191     harris41 16802: 
1.394     bowersj2 16803: =item * B<con_lost>: unable to contact remote host
1.191     harris41 16804: 
1.394     bowersj2 16805: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   16806: when the connection is brought back up
1.191     harris41 16807: 
1.394     bowersj2 16808: =item * B<con_failed>: unable to contact remote host and unable to save message
                   16809: for later delivery
1.191     harris41 16810: 
1.967     bisitz   16811: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 16812: 
1.394     bowersj2 16813: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 16814: that was requested
1.191     harris41 16815: 
1.243     albertel 16816: =back
1.191     harris41 16817: 
1.243     albertel 16818: =head1 PUBLIC SUBROUTINES
1.191     harris41 16819: 
1.243     albertel 16820: =head2 Session Environment Functions
1.191     harris41 16821: 
1.243     albertel 16822: =over 4
1.191     harris41 16823: 
1.394     bowersj2 16824: =item * 
                   16825: X<appenv()>
1.949     raeburn  16826: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 16827: the user envirnoment file, and will be restored for each access this
1.620     albertel 16828: user makes during this session, also modifies the %env for the current
1.949     raeburn  16829: process. Optional rolesarrayref - if defined contains a reference to an array
                   16830: of roles which are exempt from the restriction on modifying user.role entries 
                   16831: in the user's environment.db and in %env.    
1.191     harris41 16832: 
                   16833: =item *
1.394     bowersj2 16834: X<delenv()>
1.987     raeburn  16835: B<delenv($delthis,$regexp)>: removes all items from the session
                   16836: environment file that begin with $delthis. If the 
                   16837: optional second arg - $regexp - is true, $delthis is treated as a 
                   16838: regular expression, otherwise \Q$delthis\E is used. 
                   16839: The values are also deleted from the current processes %env.
1.191     harris41 16840: 
1.795     albertel 16841: =item * get_env_multiple($name) 
                   16842: 
                   16843: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   16844: values may be defined and end up as an array ref.
                   16845: 
                   16846: returns an array of values
                   16847: 
1.243     albertel 16848: =back
                   16849: 
                   16850: =head2 User Information
1.191     harris41 16851: 
1.243     albertel 16852: =over 4
1.191     harris41 16853: 
                   16854: =item *
1.394     bowersj2 16855: X<queryauthenticate()>
                   16856: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 16857: authentication scheme
                   16858: 
                   16859: =item *
1.394     bowersj2 16860: X<authenticate()>
1.1073    raeburn  16861: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 16862: authenticate user from domain's lib servers (first use the current
                   16863: one). C<$upass> should be the users password.
1.1073    raeburn  16864: $checkdefauth is optional (value is 1 if a check should be made to
                   16865:    authenticate user using default authentication method, and allow
                   16866:    account creation if username does not have account in the domain).
                   16867: $clientcancheckhost is optional (value is 1 if checking whether the
                   16868:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 16869: 
                   16870: =item *
1.394     bowersj2 16871: X<homeserver()>
                   16872: B<homeserver($uname,$udom)>: find the server which has
                   16873: the user's directory and files (there must be only one), this caches
                   16874: the answer, and also caches if there is a borken connection.
1.191     harris41 16875: 
                   16876: =item *
1.394     bowersj2 16877: X<idget()>
1.1300    raeburn  16878: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   16879: a list of student/employee IDs or clicker IDs
                   16880: (student/employee IDs are a unique resource in a domain, there must be 
                   16881: only 1 ID per username, and only 1 username per ID in a specific domain).
                   16882: clickerIDs are not necessarily unique, as students might share clickers.
                   16883: (returns hash: id=>name,id=>name)
1.191     harris41 16884: 
                   16885: =item *
1.394     bowersj2 16886: X<idrget()>
                   16887: B<idrget($udom,@unames)>: find the IDs behind a list of
                   16888: usernames (returns hash: name=>id,name=>id)
1.191     harris41 16889: 
                   16890: =item *
1.394     bowersj2 16891: X<idput()>
1.1300    raeburn  16892: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   16893: names and associated student/employee IDs or clicker IDs.
                   16894: 
                   16895: =item *
                   16896: X<iddel()>
                   16897: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   16898: student/employee ID or clicker ID username look-ups from domain.
                   16899: The homeserver ($uhome) and namespace ($namespace) are optional.
                   16900: If no $uhome is provided, it will be determined usig &homeserver()
                   16901: for each user.  If no $namespace is provided, the default is ids.
                   16902: 
                   16903: =item *
                   16904: X<updateclickers()>
                   16905: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   16906: clicker ID-to-username look-ups in clickers.db on library server.
                   16907: Permitted actions are add or del (i.e., add or delete). The 
                   16908: clickers.db contains clickerID as keys (escaped), and each corresponding
                   16909: value is an escaped comma-separated list of usernames (for whom the
                   16910: library server is the homeserver), who registered that particular ID.
                   16911: If $critical is true, the update will be sent via &critical, otherwise
                   16912: &reply() will be used.
1.191     harris41 16913: 
                   16914: =item *
1.394     bowersj2 16915: X<rolesinit()>
1.1169    droeschl 16916: B<rolesinit($udom,$username)>: get user privileges.
                   16917: returns user role, first access and timer interval hashes
1.243     albertel 16918: 
                   16919: =item *
1.1171    droeschl 16920: X<privileged()>
                   16921: B<privileged($username,$domain)>: returns a true if user has a
                   16922: privileged and active role (i.e. su or dc), false otherwise.
                   16923: 
                   16924: =item *
1.551     albertel 16925: X<getsection()>
                   16926: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 16927: course $cname, return section name/number or '' for "not in course"
                   16928: and '-1' for "no section"
                   16929: 
                   16930: =item *
1.394     bowersj2 16931: X<userenvironment()>
                   16932: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 16933: passed in @what from the requested user's environment, returns a hash
                   16934: 
1.858     raeburn  16935: =item * 
                   16936: X<userlog_query()>
1.859     albertel 16937: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   16938: activity.log file. %filters defines filters applied when parsing the
                   16939: log file. These can be start or end timestamps, or the type of action
                   16940: - log to look for Login or Logout events, check for Checkin or
                   16941: Checkout, role for role selection. The response is in the form
                   16942: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   16943: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  16944: 
1.243     albertel 16945: =back
                   16946: 
                   16947: =head2 User Roles
                   16948: 
                   16949: =over 4
                   16950: 
                   16951: =item *
                   16952: 
1.1284    raeburn  16953: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   16954: returns codes for allowed actions.
                   16955: 
                   16956: The first argument is required, all others are optional.
                   16957: 
                   16958: $priv is the privilege being checked.
                   16959: $uri contains additional information about what is being checked for access (e.g.,
                   16960: URL, course ID etc.). 
                   16961: $symb is the unique resource instance identifier in a course; if needed,
                   16962: but not provided, it will be retrieved via a call to &symbread(). 
                   16963: $role is the role for which a priv is being checked (only used if priv is evb). 
                   16964: $clientip is the user's IP address (only used when checking for access to portfolio 
                   16965: files).
                   16966: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   16967: prevents recursive calls to &allowed.
                   16968: 
1.243     albertel 16969:  F: full access
                   16970:  U,I,K: authentication modes (cxx only)
                   16971:  '': forbidden
                   16972:  1: user needs to choose course
                   16973:  2: browse allowed
1.766     albertel 16974:  A: passphrase authentication needed
1.1284    raeburn  16975:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  16976:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 16977: 
                   16978: =item *
                   16979: 
1.1192    raeburn  16980: constructaccess($url,$setpriv) : check for access to construction space URL
                   16981: 
                   16982: See if the owner domain and name in the URL match those in the
                   16983: expected environment.  If so, return three element list
                   16984: ($ownername,$ownerdomain,$ownerhome).
                   16985: 
                   16986: Otherwise return the null string.
                   16987: 
                   16988: If second argument 'setpriv' is true, it assigns the privileges,
                   16989: and returns the same three element list, unless the owner has
                   16990: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   16991: in which case the null string is returned.
                   16992: 
                   16993: =item *
                   16994: 
1.1326    raeburn  16995: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   16996: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   16997: for system, domain, and course level. $uname and $udom are optional (current
                   16998: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 16999: 
                   17000: =item *
                   17001: 
1.988     raeburn  17002: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   17003: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  17004: $type is Course (default) or Community.
1.988     raeburn  17005: If $forcedefault evaluates to true, text returned will be default 
                   17006: text for $type. Otherwise, if this is a course, the text returned 
                   17007: will be a custom name for the role (if defined in the course's 
                   17008: environment).  If no custom name is defined the default is returned.
                   17009:    
1.832     raeburn  17010: =item *
                   17011: 
1.1219    raeburn  17012: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  17013: All arguments are optional. Returns a hash of a roles, either for
                   17014: co-author/assistant author roles for a user's Construction Space
1.906     albertel 17015: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  17016: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   17017: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   17018: For each key, value is set to colon-separated start and end times for
                   17019: the role.  If no username and domain are specified, will default to
1.934     raeburn  17020: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  17021: of role statuses (active, future or previous), roles 
                   17022: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   17023: to restrict the list of roles reported. If no array ref is 
                   17024: provided for types, will default to return only active roles.
1.834     albertel 17025: 
1.1195    raeburn  17026: =item *
                   17027: 
                   17028: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  17029: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   17030: 
                   17031: Additional optional arguments are: $type (if role checking is to be restricted 
                   17032: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  17033: available roles) or future (roles available in the future), and
                   17034: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  17035: have active Domain Coordinator role in course's domain or in additional
                   17036: domains (specified in 'Domains to check for privileged users' in course
                   17037: environment -- set via:  Course Settings -> Classlists and staff listing).
                   17038: 
                   17039: =item *
                   17040: 
                   17041: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   17042: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   17043: $possdomains and $possroles are optional array refs -- to domains to check and
                   17044: roles to check.  If $possdomains is not specified, a dump will be done of the
                   17045: users' roles.db to check for a dc or su role in any domain. This can be
                   17046: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   17047: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   17048: this then allows &privileged_by_domain() to be used, which caches the identity
                   17049: of privileged users, eliminating the need for repeated calls to &dump().
                   17050: 
                   17051: =item *
                   17052: 
                   17053: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   17054: where the outer hash keys are domains specified in the $possdomains array ref,
                   17055: next inner hash keys are privileged roles specified in the $roles array ref,
                   17056: and the innermost hash contains key = value pairs for username:domain = end:start
                   17057: for active or future "privileged" users with that role in that domain. To avoid
                   17058: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   17059: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  17060: 
1.243     albertel 17061: =back
                   17062: 
                   17063: =head2 User Modification
                   17064: 
                   17065: =over 4
                   17066: 
                   17067: =item *
                   17068: 
1.957     raeburn  17069: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 17070: user for the level given by URL.  Optional start and end dates (leave empty
                   17071: string or zero for "no date")
1.191     harris41 17072: 
                   17073: =item *
                   17074: 
1.243     albertel 17075: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   17076: change a users, password, possible return values are: ok,
                   17077: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   17078: refused
1.191     harris41 17079: 
                   17080: =item *
                   17081: 
1.243     albertel 17082: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 17083: 
                   17084: =item *
                   17085: 
1.1058    raeburn  17086: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   17087:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   17088: 
                   17089: will update user information (firstname,middlename,lastname,generation,
                   17090: permanentemail), and if forceid is true, student/employee ID also.
                   17091: A user's institutional affiliation(s) can also be updated.
                   17092: User information fields will not be overwritten with empty entries 
                   17093: unless the field is included in the $candelete array reference.
                   17094: This array is included when a single user is modified via "Manage Users",
                   17095: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 17096: 
                   17097: =item *
                   17098: 
1.286     matthew  17099: modifystudent
                   17100: 
1.957     raeburn  17101: modify a student's enrollment and identification information.
1.1235    raeburn  17102: The course id is resolved based on the current user's environment.  
                   17103: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  17104: associated with a course.
                   17105: 
1.297     matthew  17106: This call is essentially a wrapper for lonnet::modifyuser and
                   17107: lonnet::modify_student_enrollment
1.286     matthew  17108: 
                   17109: Inputs: 
                   17110: 
                   17111: =over 4
                   17112: 
1.957     raeburn  17113: =item B<$udom> Student's loncapa domain
1.286     matthew  17114: 
1.957     raeburn  17115: =item B<$uname> Student's loncapa login name
1.286     matthew  17116: 
1.964     bisitz   17117: =item B<$uid> Student/Employee ID
1.286     matthew  17118: 
1.957     raeburn  17119: =item B<$umode> Student's authentication mode
1.286     matthew  17120: 
1.957     raeburn  17121: =item B<$upass> Student's password
1.286     matthew  17122: 
1.957     raeburn  17123: =item B<$first> Student's first name
1.286     matthew  17124: 
1.957     raeburn  17125: =item B<$middle> Student's middle name
1.286     matthew  17126: 
1.957     raeburn  17127: =item B<$last> Student's last name
1.286     matthew  17128: 
1.957     raeburn  17129: =item B<$gene> Student's generation
1.286     matthew  17130: 
1.957     raeburn  17131: =item B<$usec> Student's section in course
1.286     matthew  17132: 
                   17133: =item B<$end> Unix time of the roles expiration
                   17134: 
                   17135: =item B<$start> Unix time of the roles start date
                   17136: 
                   17137: =item B<$forceid> If defined, allow $uid to be changed
                   17138: 
                   17139: =item B<$desiredhome> server to use as home server for student
                   17140: 
1.957     raeburn  17141: =item B<$email> Student's permanent e-mail address
                   17142: 
                   17143: =item B<$type> Type of enrollment (auto or manual)
                   17144: 
1.963     raeburn  17145: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   17146: 
                   17147: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  17148: 
1.963     raeburn  17149: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  17150: 
1.963     raeburn  17151: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  17152: 
1.1216    raeburn  17153: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   17154: 
                   17155: =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  17156: 
1.286     matthew  17157: =back
1.297     matthew  17158: 
                   17159: =item *
                   17160: 
                   17161: modify_student_enrollment
                   17162: 
1.1235    raeburn  17163: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  17164: 'role.request.course' must be defined for this function to proceed.
                   17165: 
                   17166: Inputs:
                   17167: 
                   17168: =over 4
                   17169: 
1.1235    raeburn  17170: =item $udom, student's domain
1.297     matthew  17171: 
1.1235    raeburn  17172: =item $uname, student's name
1.297     matthew  17173: 
1.1235    raeburn  17174: =item $uid, student's user id
1.297     matthew  17175: 
1.1235    raeburn  17176: =item $first, student's first name
1.297     matthew  17177: 
                   17178: =item $middle
                   17179: 
                   17180: =item $last
                   17181: 
                   17182: =item $gene
                   17183: 
                   17184: =item $usec
                   17185: 
                   17186: =item $end
                   17187: 
                   17188: =item $start
                   17189: 
1.957     raeburn  17190: =item $type
                   17191: 
                   17192: =item $locktype
                   17193: 
                   17194: =item $cid
                   17195: 
                   17196: =item $selfenroll
                   17197: 
                   17198: =item $context
                   17199: 
1.1216    raeburn  17200: =item $credits, number of credits student will earn from this class
                   17201: 
1.1314    raeburn  17202: =item $instsec, institutional course section code for student
                   17203: 
1.297     matthew  17204: =back
                   17205: 
1.191     harris41 17206: 
                   17207: =item *
                   17208: 
1.243     albertel 17209: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   17210: custom role; give a custom role to a user for the level given by URL.  Specify
                   17211: name and domain of role author, and role name
1.191     harris41 17212: 
                   17213: =item *
                   17214: 
1.243     albertel 17215: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 17216: 
                   17217: =item *
                   17218: 
1.243     albertel 17219: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   17220: 
                   17221: =back
                   17222: 
                   17223: =head2 Course Infomation
                   17224: 
                   17225: =over 4
1.191     harris41 17226: 
                   17227: =item *
                   17228: 
1.1118    foxr     17229: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 17230: specified course id, including all environment settings for the
                   17231: course, the description of the course will be in the hash under the
                   17232: key 'description'
1.191     harris41 17233: 
1.1118    foxr     17234: $options is an optional parameter that if supplied is a hash reference that controls
                   17235: what how this function works.  It has the following key/values:
                   17236: 
                   17237: =over 4
                   17238: 
                   17239: =item freshen_cache
                   17240: 
                   17241: If defined, and the environment cache for the course is valid, it is 
                   17242: returned in the returned hash.
                   17243: 
                   17244: =item one_time
                   17245: 
                   17246: If defined, the last cache time is set to _now_
                   17247: 
                   17248: =item user
                   17249: 
                   17250: If defined, the supplied username is used instead of the current user.
                   17251: 
                   17252: 
                   17253: =back
                   17254: 
1.191     harris41 17255: =item *
                   17256: 
1.624     albertel 17257: resdata($name,$domain,$type,@which) : request for current parameter
                   17258: setting for a specific $type, where $type is either 'course' or 'user',
                   17259: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  17260: answers for 10 minutes.
1.243     albertel 17261: 
1.877     foxr     17262: =item *
                   17263: 
                   17264: get_courseresdata($courseid, $domain) : dump the entire course resource
                   17265: data base, returning a hash that is keyed by the resource name and has
                   17266: values that are the resource value.  I believe that the timestamps and
                   17267: versions are also returned.
                   17268: 
1.243     albertel 17269: =back
                   17270: 
                   17271: =head2 Course Modification
                   17272: 
                   17273: =over 4
1.191     harris41 17274: 
                   17275: =item *
                   17276: 
1.243     albertel 17277: writecoursepref($courseid,%prefs) : write preferences (environment
                   17278: database) for a course
1.191     harris41 17279: 
                   17280: =item *
                   17281: 
1.1011    raeburn  17282: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   17283: 
                   17284: =item *
                   17285: 
1.1038    raeburn  17286: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 17287: 
1.1167    droeschl 17288: =item *
                   17289: 
                   17290: is_course($courseid), is_course($cdom, $cnum)
                   17291: 
                   17292: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   17293: two component version $cdom, $cnum. It checks if the specified course exists.
                   17294: 
                   17295: Returns:
                   17296:     undef if the course doesn't exist, otherwise
                   17297:     in scalar context the combined courseid.
                   17298:     in list context the two components of the course identifier, domain and 
                   17299:     courseid.    
                   17300: 
1.243     albertel 17301: =back
                   17302: 
1.1401    raeburn  17303: =head2 Bubblesheet Configuration
                   17304: 
                   17305: =over 4
                   17306: 
                   17307: =item *
                   17308: 
                   17309: get_scantron_config($which)
                   17310: 
                   17311: $which - the name of the configuration to parse from the file.
                   17312: 
                   17313: Parses and returns the bubblesheet configuration line selected as a
                   17314: hash of configuration file fields.
                   17315: 
                   17316: 
                   17317: Returns:
                   17318:     If the named configuration is not in the file, an empty
                   17319:     hash is returned.
                   17320: 
                   17321:     a hash with the fields
                   17322:       name         - internal name for the this configuration setup
                   17323:       description  - text to display to operator that describes this config
                   17324:       CODElocation - if 0 or the string 'none'
                   17325:                           - no CODE exists for this config
                   17326:                      if -1 || the string 'letter'
                   17327:                           - a CODE exists for this config and is
                   17328:                             a string of letters
                   17329:                      Unsupported value (but planned for future support)
                   17330:                           if a positive integer
                   17331:                                - The CODE exists as the first n items from
                   17332:                                  the question section of the form
                   17333:                           if the string 'number'
                   17334:                                - The CODE exists for this config and is
                   17335:                                  a string of numbers
                   17336:       CODEstart   - (only matter if a CODE exists) column in the line where
                   17337:                      the CODE starts
                   17338:       CODElength  - length of the CODE
                   17339:       IDstart     - column where the student/employee ID starts
                   17340:       IDlength    - length of the student/employee ID info
                   17341:       Qstart      - column where the information from the bubbled
                   17342:                     'questions' start
                   17343:       Qlength     - number of columns comprising a single bubble line from
                   17344:                     the sheet. (usually either 1 or 10)
                   17345:       Qon         - either a single character representing the character used
                   17346:                     to signal a bubble was chosen in the positional setup, or
                   17347:                     the string 'letter' if the letter of the chosen bubble is
                   17348:                     in the final, or 'number' if a number representing the
                   17349:                     chosen bubble is in the file (1->A 0->J)
                   17350:       Qoff        - the character used to represent that a bubble was
                   17351:                     left blank
                   17352:       PaperID     - if the scanning process generates a unique number for each
                   17353:                     sheet scanned the column that this ID number starts in
                   17354:       PaperIDlength - number of columns that comprise the unique ID number
                   17355:                       for the sheet of paper
                   17356:       FirstName   - column that the first name starts in
                   17357:       FirstNameLength - number of columns that the first name spans
                   17358:       LastName    - column that the last name starts in
                   17359:       LastNameLength - number of columns that the last name spans
                   17360:       BubblesPerRow - number of bubbles available in each row used to
                   17361:                       bubble an answer. (If not specified, 10 assumed).
                   17362: 
                   17363: 
                   17364: =item *
                   17365: 
                   17366: get_scantronformat_file($cdom)
                   17367: 
                   17368: $cdom - the course's domain (optional); if not supplied, uses
                   17369: domain for current $env{'request.course.id'}.
                   17370: 
                   17371: Returns an array containing lines from the scantron format file for
                   17372: the domain of the course.
                   17373: 
                   17374: If a url for a custom.tab file is listed in domain's configuration.db,
                   17375: lines are from this file.
                   17376: 
                   17377: Otherwise, if a default.tab has been published in RES space by the
                   17378: domainconfig user, lines are from this file.
                   17379: 
                   17380: Otherwise, fall back to getting lines from the legacy file on the
                   17381: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   17382: 
                   17383: =back
                   17384: 
1.243     albertel 17385: =head2 Resource Subroutines
                   17386: 
                   17387: =over 4
1.191     harris41 17388: 
                   17389: =item *
                   17390: 
1.243     albertel 17391: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 17392: 
                   17393: =item *
                   17394: 
1.243     albertel 17395: repcopy($filename) : subscribes to the requested file, and attempts to
                   17396: replicate from the owning library server, Might return
1.607     raeburn  17397: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   17398: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 17399: resource. Expects the local filesystem pathname
                   17400: (/home/httpd/html/res/....)
                   17401: 
                   17402: =back
                   17403: 
                   17404: =head2 Resource Information
                   17405: 
                   17406: =over 4
1.191     harris41 17407: 
                   17408: =item *
                   17409: 
1.1228    raeburn  17410: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   17411: and returns the value of a variety of different possible values,
                   17412: $varname should be a request string, and the other parameters can be
                   17413: used to specify who and what one is asking about. Ordinarily, $cid 
                   17414: does not need to be specified, as it is retrived from 
                   17415: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   17416: within lonuserstate::loadmap() when initializing a course, before
                   17417: $env{'request.course.id'} has been set, so it needs to be provided
                   17418: in that one case.
1.243     albertel 17419: 
                   17420: Possible values for $varname are environment.lastname (or other item
                   17421: from the envirnment hash), user.name (or someother aspect about the
                   17422: user), resource.0.maxtries (or some other part and parameter of a
                   17423: resource)
1.204     albertel 17424: 
                   17425: =item *
                   17426: 
1.243     albertel 17427: directcondval($number) : get current value of a condition; reads from a state
                   17428: string
1.204     albertel 17429: 
                   17430: =item *
                   17431: 
1.243     albertel 17432: condval($condidx) : value of condition index based on state
1.204     albertel 17433: 
                   17434: =item *
                   17435: 
1.1362    raeburn  17436: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 17437: resource's metadata, $what should be either a specific key, or either
                   17438: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  17439: packages that this resource currently uses, the last 3 arguments are 
                   17440: only used internally for recursive metadata.
                   17441: 
                   17442: the toolsymb is only used where the uri is for an external tool (for which
                   17443: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 17444: 
1.1371    raeburn  17445: this function automatically caches all requests except any made recursively
                   17446: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   17447: defined).
1.191     harris41 17448: 
                   17449: =item *
                   17450: 
1.243     albertel 17451: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   17452: network of library servers; returns file handle of where SQL and regex results
                   17453: will be stored for query
1.191     harris41 17454: 
                   17455: =item *
                   17456: 
1.1282    raeburn  17457: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   17458: return symbolic list entry (all arguments optional). 
                   17459: 
                   17460: Args: filename is the filename (including path) for the file for which a symb 
                   17461: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   17462: to check access status if more than one resource was found in the bighash 
                   17463: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   17464: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   17465: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   17466: cause possible symbs to be checked to determine if they are subject to content
                   17467: blocking, if so they will not be included as possible symbs; possibles is a
                   17468: ref to a hash, which, as a side effect, will be populated with all possible 
                   17469: symbs (content blocking not tested).
                   17470:  
1.243     albertel 17471: returns the data handle
1.191     harris41 17472: 
                   17473: =item *
                   17474: 
1.1190    raeburn  17475: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   17476: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 17477: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  17478: on failure, user must be in a course, as it assumes the existence of
                   17479: the course initial hash, and uses $env('request.course.id'}.  The third
                   17480: arg is an optional reference to a scalar.  If this arg is passed in the 
                   17481: call to symbverify, it will be set to 1 if the symb has been set to be 
                   17482: encrypted; otherwise it will be null.  
1.191     harris41 17483: 
                   17484: =item *
                   17485: 
1.243     albertel 17486: symbclean($symb) : removes versions numbers from a symb, returns the
                   17487: cleaned symb
1.191     harris41 17488: 
                   17489: =item *
                   17490: 
1.243     albertel 17491: is_on_map($uri) : checks if the $uri is somewhere on the current
                   17492: course map, user must be in a course for it to work.
1.191     harris41 17493: 
                   17494: =item *
                   17495: 
1.243     albertel 17496: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 17497: 
                   17498: =item *
                   17499: 
1.243     albertel 17500: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   17501: a random seed, all arguments are optional, if they aren't sent it uses the
                   17502: environment to derive them. Note: if symb isn't sent and it can't get one
                   17503: from &symbread it will use the current time as its return value
1.191     harris41 17504: 
                   17505: =item *
                   17506: 
1.243     albertel 17507: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   17508: unfakeable, receipt
1.191     harris41 17509: 
                   17510: =item *
                   17511: 
1.620     albertel 17512: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 17513: 
                   17514: =item *
                   17515: 
1.243     albertel 17516: countacc($url) : count the number of accesses to a given URL
1.191     harris41 17517: 
                   17518: =item *
                   17519: 
1.243     albertel 17520: 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 17521: 
                   17522: =item *
                   17523: 
1.243     albertel 17524: 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 17525: 
                   17526: =item *
                   17527: 
1.243     albertel 17528: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 17529: 
                   17530: =item *
                   17531: 
1.243     albertel 17532: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   17533: forcing spreadsheet to reevaluate the resource scores next time.
                   17534: 
1.1195    raeburn  17535: =item * 
                   17536: 
1.1196    raeburn  17537: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   17538: when viewing in course context.
1.1195    raeburn  17539: 
1.1196    raeburn  17540:  input: six args -- filename (decluttered), course number, course domain,
                   17541:                     url, symb (if registered) and group (if this is a 
                   17542:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  17543: 
1.1196    raeburn  17544:  output: array of five scalars --
1.1195    raeburn  17545:          $cfile -- url for file editing if editable on current server
                   17546:          $home -- homeserver of resource (i.e., for author if published,
                   17547:                                           or course if uploaded.).
                   17548:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  17549:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   17550:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  17551: 
                   17552: =item *
                   17553: 
                   17554: is_course_upload($file,$cnum,$cdom)
                   17555: 
                   17556: Used in course context to determine if current file was uploaded to 
                   17557: the course (i.e., would be found in /userfiles/docs on the course's 
                   17558: homeserver.
                   17559: 
                   17560:   input: 3 args -- filename (decluttered), course number and course domain.
                   17561:   output: boolean -- 1 if file was uploaded.
                   17562: 
1.243     albertel 17563: =back
                   17564: 
                   17565: =head2 Storing/Retreiving Data
                   17566: 
                   17567: =over 4
1.191     harris41 17568: 
                   17569: =item *
                   17570: 
1.1269    raeburn  17571: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   17572: permanently for this url; hashref needs to be given and should be a \%hashname;
                   17573: the remaining args aren't required and if they aren't passed or are '' they will
                   17574: be derived from the env (with the exception of $laststore, which is an 
                   17575: optional arg used when a user's submission is stored in grading).
                   17576: $laststore is $version=$timestamp, where $version is the most recent version
                   17577: number retrieved for the corresponding $symb in the $namespace db file, and
                   17578: $timestamp is the timestamp for that transaction (UNIX time).
                   17579: $laststore is currently only passed when cstore() is called by 
                   17580: structuretags::finalize_storage().
1.191     harris41 17581: 
                   17582: =item *
                   17583: 
1.1269    raeburn  17584: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   17585: but uses critical subroutine
1.191     harris41 17586: 
                   17587: =item *
                   17588: 
1.243     albertel 17589: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   17590: all args are optional
1.191     harris41 17591: 
                   17592: =item *
                   17593: 
1.717     albertel 17594: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   17595: dumps the complete (or key matching regexp) namespace into a hash
                   17596: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   17597: normally &store()ed into
                   17598: 
                   17599: $range should be either an integer '100' (give me the first 100
                   17600:                                            matching records)
                   17601:               or be  two integers sperated by a - with no spaces
                   17602:                  '30-50' (give me the 30th through the 50th matching
                   17603:                           records)
                   17604: 
                   17605: 
                   17606: =item *
                   17607: 
1.1269    raeburn  17608: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 17609: replaces a &store() version of data with a replacement set of data
                   17610: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  17611: reference. If $tolog is true, the transaction is logged in the courselog
                   17612: with an action=PUTSTORE.
1.717     albertel 17613: 
                   17614: =item *
                   17615: 
1.243     albertel 17616: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   17617: works very similar to store/cstore, but all data is stored in a
                   17618: temporary location and can be reset using tmpreset, $storehash should
                   17619: be a hash reference, returns nothing on success
1.191     harris41 17620: 
                   17621: =item *
                   17622: 
1.243     albertel 17623: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   17624: similar to restore, but all data is stored in a temporary location and
                   17625: can be reset using tmpreset. Returns a hash of values on success,
                   17626: error string otherwise.
1.191     harris41 17627: 
                   17628: =item *
                   17629: 
1.243     albertel 17630: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   17631: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 17632: 
                   17633: =item *
                   17634: 
1.243     albertel 17635: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   17636: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 17637: 
                   17638: =item *
                   17639: 
1.243     albertel 17640: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   17641: namesp ($udom and $uname are optional)
1.191     harris41 17642: 
                   17643: =item *
                   17644: 
1.702     albertel 17645: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 17646: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 17647: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  17648: 
1.702     albertel 17649: $range should be either an integer '100' (give me the first 100
                   17650:                                            matching records)
                   17651:               or be  two integers sperated by a - with no spaces
                   17652:                  '30-50' (give me the 30th through the 50th matching
                   17653:                           records)
1.449     matthew  17654: =item *
                   17655: 
                   17656: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   17657: $store can be a scalar, an array reference, or if the amount to be 
                   17658: incremented is > 1, a hash reference.
                   17659: 
                   17660: ($udom and $uname are optional)
1.191     harris41 17661: 
                   17662: =item *
                   17663: 
1.243     albertel 17664: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   17665: ($udom and $uname are optional)
1.191     harris41 17666: 
                   17667: =item *
                   17668: 
1.243     albertel 17669: cput($namespace,$storehash,$udom,$uname) : critical put
                   17670: ($udom and $uname are optional)
1.191     harris41 17671: 
                   17672: =item *
                   17673: 
1.748     albertel 17674: newput($namespace,$storehash,$udom,$uname) :
                   17675: 
                   17676: Attempts to store the items in the $storehash, but only if they don't
                   17677: currently exist, if this succeeds you can be certain that you have 
                   17678: successfully created a new key value pair in the $namespace db.
                   17679: 
                   17680: 
                   17681: Args:
                   17682:  $namespace: name of database to store values to
                   17683:  $storehash: hashref to store to the db
                   17684:  $udom: (optional) domain of user containing the db
                   17685:  $uname: (optional) name of user caontaining the db
                   17686: 
                   17687: Returns:
                   17688:  'ok' -> succeeded in storing all keys of $storehash
                   17689:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   17690:                         least <key> already existed in the db (other
                   17691:                         requested keys may also already exist)
1.967     bisitz   17692:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 17693:  'con_lost' -> unable to contact request server
                   17694:  'refused' -> action was not allowed by remote machine
                   17695: 
                   17696: 
                   17697: =item *
                   17698: 
1.243     albertel 17699: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   17700: reference filled in from namesp (encrypts the return communication)
                   17701: ($udom and $uname are optional)
1.191     harris41 17702: 
                   17703: =item *
                   17704: 
1.243     albertel 17705: log($udom,$name,$home,$message) : write to permanent log for user; use
                   17706: critical subroutine
                   17707: 
1.806     raeburn  17708: =item *
                   17709: 
1.860     raeburn  17710: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   17711: array reference filled in from namespace found in domain level on either
                   17712: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  17713: 
                   17714: =item *
                   17715: 
1.860     raeburn  17716: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   17717: domain level either on specified domain server ($uhome) or primary domain 
                   17718: server ($udom and $uhome are optional)
1.806     raeburn  17719: 
1.943     raeburn  17720: =item * 
                   17721: 
1.1240    raeburn  17722: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   17723: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   17724: the target domain.
                   17725: 
                   17726: May also include additional key => value pairs for the following groups:
                   17727: 
                   17728: =over
                   17729: 
                   17730: =item
                   17731: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   17732: 
                   17733: =over
                   17734: 
                   17735: =item defaultquota, authorquota
                   17736: 
                   17737: =back
                   17738: 
                   17739: =item
                   17740: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   17741: portfolio for users).
                   17742: 
                   17743: =over
                   17744: 
                   17745: =item
                   17746: aboutme, blog, webdav, portfolio
                   17747: 
                   17748: =back
                   17749: 
                   17750: =item
                   17751: requestcourses: ability to request courses, and how requests are processed.
                   17752: 
                   17753: =over
                   17754: 
                   17755: =item
1.1305    raeburn  17756: official, unofficial, community, textbook, placement
1.1240    raeburn  17757: 
                   17758: =back
                   17759: 
                   17760: =item
                   17761: inststatus: types of institutional affiliation, and order in which they are displayed.
                   17762: 
                   17763: =over
                   17764: 
                   17765: =item
1.1256    raeburn  17766: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  17767: 
                   17768: =back
                   17769: 
                   17770: =item
                   17771: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   17772: for course's uploaded content.
                   17773: 
                   17774: =over
                   17775: 
                   17776: =item
1.1246    raeburn  17777: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  17778: communityquota, textbookquota, placementquota
1.1240    raeburn  17779: 
                   17780: =back
                   17781: 
                   17782: =item
                   17783: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   17784: on your servers.
                   17785: 
                   17786: =over
                   17787: 
                   17788: =item 
                   17789: remotesessions, hostedsessions
                   17790: 
                   17791: =back
                   17792: 
                   17793: =back
                   17794: 
                   17795: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   17796: utility to create a configuration.db file on a domain's primary library server 
                   17797: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   17798: -- corresponding values are authentication type (internal, krb4, krb5,
                   17799: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   17800: will be available. Values are retrieved from cache (if current), unless the
                   17801: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   17802: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   17803: 
                   17804: Typical usage:
1.943     raeburn  17805: 
1.1240    raeburn  17806: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  17807: 
1.243     albertel 17808: =back
                   17809: 
                   17810: =head2 Network Status Functions
                   17811: 
                   17812: =over 4
1.191     harris41 17813: 
                   17814: =item *
                   17815: 
1.1137    raeburn  17816: dirlist() : return directory list based on URI (first arg).
                   17817: 
                   17818: Inputs: 1 required, 5 optional.
                   17819: 
                   17820: =over
                   17821: 
                   17822: =item 
                   17823: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   17824: 
                   17825: =item
                   17826: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   17827: 
                   17828: =item
                   17829: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   17830: 
                   17831: =item
                   17832: $getpropath - boolean: 1 if prepend path using &propath(). 
                   17833: 
                   17834: =item
                   17835: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   17836: 
                   17837: =item 
                   17838: $alternateRoot - path to prepend in place of path from $uri.
                   17839: 
                   17840: =back
                   17841: 
                   17842: Returns: Array of up to two items.
                   17843: 
                   17844: =over
                   17845: 
                   17846: a reference to an array of files/subdirectories
                   17847: 
                   17848: =over
                   17849: 
                   17850: Each element in the array of files/subdirectories is a & separated list of
                   17851: item name and the result of running stat on the item.  If dirlist was requested
                   17852: for a file instead of a directory, the item name will be ''. For a directory 
                   17853: listing, if the item is a metadata file, the element will end &N&M 
                   17854: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   17855: default copyright set (1).  
                   17856: 
                   17857: =back
                   17858: 
                   17859: a scalar containing error condition (if encountered).
                   17860: 
                   17861: =over
                   17862: 
                   17863: =item 
                   17864: no_host (no homeserver identified for $username:$domain).
                   17865: 
                   17866: =item 
                   17867: no_such_host (server contacted for listing not identified as valid host).
                   17868: 
                   17869: =item 
                   17870: con_lost (connection to remote server failed).
                   17871: 
                   17872: =item 
                   17873: refused (invalid $username:$domain received on lond side).
                   17874: 
                   17875: =item 
                   17876: no_such_dir (directory at specified path on lond side does not exist). 
                   17877: 
                   17878: =item 
                   17879: empty (directory at specified path on lond side is empty).
                   17880: 
                   17881: =over
                   17882: 
                   17883: This is currently not encountered because the &ls3, &ls2, 
                   17884: &ls (_handler) routines on the lond side do not filter out
                   17885: . and .. from a directory listing. 
                   17886: 
                   17887: =back
                   17888: 
                   17889: =back
                   17890: 
                   17891: =back
1.191     harris41 17892: 
                   17893: =item *
                   17894: 
1.243     albertel 17895: spareserver() : find server with least workload from spare.tab
                   17896: 
1.986     foxr     17897: 
                   17898: =item *
                   17899: 
                   17900: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   17901: if there is no corresponding loncapa host.
                   17902: 
1.243     albertel 17903: =back
                   17904: 
1.986     foxr     17905: 
1.243     albertel 17906: =head2 Apache Request
                   17907: 
                   17908: =over 4
1.191     harris41 17909: 
                   17910: =item *
                   17911: 
1.243     albertel 17912: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   17913: localhost, posts hash
                   17914: 
                   17915: =back
                   17916: 
                   17917: =head2 Data to String to Data
                   17918: 
                   17919: =over 4
1.191     harris41 17920: 
                   17921: =item *
                   17922: 
1.243     albertel 17923: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   17924: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 17925: 
                   17926: =item *
                   17927: 
1.243     albertel 17928: hashref2str($hashref) : convert a hashref into a string complete with
                   17929: escaping and '=' and '&' separators, supports elements that are
                   17930: arrayrefs and hashrefs
1.191     harris41 17931: 
                   17932: =item *
                   17933: 
1.243     albertel 17934: arrayref2str($arrayref) : convert an arrayref into a string complete
                   17935: with escaping and '&' separators, supports elements that are arrayrefs
                   17936: and hashrefs
1.191     harris41 17937: 
                   17938: =item *
                   17939: 
1.243     albertel 17940: str2hash($string) : convert string to hash using unescaping and
                   17941: splitting on '=' and '&', supports elements that are arrayrefs and
                   17942: hashrefs
1.191     harris41 17943: 
                   17944: =item *
                   17945: 
1.243     albertel 17946: str2array($string) : convert string to hash using unescaping and
                   17947: splitting on '&', supports elements that are arrayrefs and hashrefs
                   17948: 
                   17949: =back
                   17950: 
                   17951: =head2 Logging Routines
                   17952: 
                   17953: 
                   17954: These routines allow one to make log messages in the lonnet.log and
                   17955: lonnet.perm logfiles.
1.191     harris41 17956: 
1.1119    foxr     17957: =over 4
                   17958: 
1.191     harris41 17959: =item *
                   17960: 
1.243     albertel 17961: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 17962: 
                   17963: =item *
                   17964: 
1.243     albertel 17965: logthis() : append message to the normal lonnet.log file, it gets
                   17966: preiodically rolled over and deleted.
1.191     harris41 17967: 
                   17968: =item *
                   17969: 
1.243     albertel 17970: logperm() : append a permanent message to lonnet.perm.log, this log
                   17971: file never gets deleted by any automated portion of the system, only
                   17972: messages of critical importance should go in here.
                   17973: 
1.1119    foxr     17974: 
1.243     albertel 17975: =back
                   17976: 
                   17977: =head2 General File Helper Routines
                   17978: 
                   17979: =over 4
1.191     harris41 17980: 
                   17981: =item *
                   17982: 
1.481     raeburn  17983: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   17984: (a) files in /uploaded
                   17985:   (i) If a local copy of the file exists - 
                   17986:       compares modification date of local copy with last-modified date for 
                   17987:       definitive version stored on home server for course. If local copy is 
                   17988:       stale, requests a new version from the home server and stores it. 
                   17989:       If the original has been removed from the home server, then local copy 
                   17990:       is unlinked.
                   17991:   (ii) If local copy does not exist -
                   17992:       requests the file from the home server and stores it. 
                   17993:   
                   17994:   If $caller is 'uploadrep':  
                   17995:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   17996:     for request for files originally uploaded via DOCS. 
                   17997:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   17998:   
                   17999:   Otherwise:
                   18000:      This indicates a call from the content generation phase of the request.
                   18001:      -  returns the entire contents of the file or -1.
                   18002:      
                   18003: (b) files in /res
                   18004:    - returns the entire contents of a file or -1; 
                   18005:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 18006: 
1.712     albertel 18007: 
                   18008: =item *
                   18009: 
                   18010: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   18011:                   reference
                   18012: 
                   18013: returns either a stat() list of data about the file or an empty list
                   18014: if the file doesn't exist or couldn't find out about it (connection
                   18015: problems or user unknown)
                   18016: 
1.191     harris41 18017: =item *
                   18018: 
1.243     albertel 18019: filelocation($dir,$file) : returns file system location of a file
                   18020: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   18021: directory that relative $file lookups are to looked in ($dir of /a/dir
                   18022: and a file of ../bob will become /a/bob)
1.191     harris41 18023: 
                   18024: =item *
                   18025: 
                   18026: hreflocation($dir,$file) : returns file system location or a URL; same as
                   18027: filelocation except for hrefs
                   18028: 
                   18029: =item *
                   18030: 
1.1261    raeburn  18031: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   18032: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 18033: 
1.243     albertel 18034: =back
                   18035: 
1.608     albertel 18036: =head2 Usererfile file routines (/uploaded*)
                   18037: 
                   18038: =over 4
                   18039: 
                   18040: =item *
                   18041: 
                   18042: userfileupload(): main rotine for putting a file in a user or course's
                   18043:                   filespace, arguments are,
                   18044: 
1.620     albertel 18045:  formname - required - this is the name of the element in $env where the
1.608     albertel 18046:            filename, and the contents of the file to create/modifed exist
1.620     albertel 18047:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   18048:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  18049:  context - if coursedoc, store the file in the course of the active role
                   18050:              of the current user; 
                   18051:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   18052:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 18053:  subdir - required - subdirectory to put the file in under ../userfiles/
                   18054:          if undefined, it will be placed in "unknown"
                   18055: 
                   18056:  (This routine calls clean_filename() to remove any dangerous
                   18057:  characters from the filename, and then calls finuserfileupload() to
                   18058:  complete the transaction)
                   18059: 
                   18060:  returns either the url of the uploaded file (/uploaded/....) if successful
                   18061:  and /adm/notfound.html if unsuccessful
                   18062: 
                   18063: =item *
                   18064: 
                   18065: clean_filename(): routine for cleaing a filename up for storage in
                   18066:                  userfile space, argument is:
                   18067: 
                   18068:  filename - proposed filename
                   18069: 
                   18070: returns: the new clean filename
                   18071: 
                   18072: =item *
                   18073: 
1.1090    raeburn  18074: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 18075: userspace, probably shouldn't be called directly
                   18076: 
                   18077:   docuname: username or courseid of destination for the file
                   18078:   docudom: domain of user/course of destination for the file
                   18079:   formname: same as for userfileupload()
1.1090    raeburn  18080:   fname: filename (including subdirectories) for the file
                   18081:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  18082:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  18083:   allfiles: reference to hash used to store objects found by parser
                   18084:   codebase: reference to hash used for codebases of java objects found by parser
                   18085:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   18086:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   18087:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   18088:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   18089:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   18090:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  18091:   mimetype: reference to scalar to accommodate mime type determined
                   18092:             from File::MMagic if $parser = parse.
1.608     albertel 18093: 
                   18094:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  18095:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   18096:  was 'overwrite').
                   18097:  
1.608     albertel 18098: 
                   18099: =item *
                   18100: 
                   18101: renameuserfile(): renames an existing userfile to a new name
                   18102: 
                   18103:   Args:
                   18104:    docuname: username or courseid of destination for the file
                   18105:    docudom: domain of user/course of destination for the file
                   18106:    old: current file name (including any subdirs under userfiles)
                   18107:    new: desired file name (including any subdirs under userfiles)
                   18108: 
                   18109: =item *
                   18110: 
                   18111: mkdiruserfile(): creates a directory is a userfiles dir
                   18112: 
                   18113:   Args:
                   18114:    docuname: username or courseid of destination for the file
                   18115:    docudom: domain of user/course of destination for the file
                   18116:    dir: dir to create (including any subdirs under userfiles)
                   18117: 
                   18118: =item *
                   18119: 
                   18120: removeuserfile(): removes a file that exists in userfiles
                   18121: 
                   18122:   Args:
                   18123:    docuname: username or courseid of destination for the file
                   18124:    docudom: domain of user/course of destination for the file
                   18125:    fname: filname to delete (including any subdirs under userfiles)
                   18126: 
                   18127: =item *
                   18128: 
                   18129: removeuploadedurl(): convience function for removeuserfile()
                   18130: 
                   18131:   Args:
                   18132:    url:  a full /uploaded/... url to delete
                   18133: 
1.747     albertel 18134: =item * 
                   18135: 
                   18136: get_portfile_permissions():
                   18137:   Args:
                   18138:     domain: domain of user or course contain the portfolio files
                   18139:     user: name of user or num of course contain the portfolio files
                   18140:   Returns:
                   18141:     hashref of a dump of the proper file_permissions.db
                   18142:    
                   18143: 
                   18144: =item * 
                   18145: 
                   18146: get_access_controls():
                   18147: 
                   18148: Args:
                   18149:   current_permissions: the hash ref returned from get_portfile_permissions()
                   18150:   group: (optional) the group you want the files associated with
                   18151:   file: (optional) the file you want access info on
                   18152: 
                   18153: Returns:
1.749     raeburn  18154:     a hash (keys are file names) of hashes containing
                   18155:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   18156:         values are XML containing access control settings (see below) 
1.747     albertel 18157: 
                   18158: Internal notes:
                   18159: 
1.749     raeburn  18160:  access controls are stored in file_permissions.db as key=value pairs.
                   18161:     key -> path to file/file_name\0uniqueID:scope_end_start
                   18162:         where scope -> public,guest,course,group,domains or users.
                   18163:               end -> UNIX time for end of access (0 -> no end date)
                   18164:               start -> UNIX time for start of access
                   18165: 
                   18166:     value -> XML description of access control
                   18167:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   18168:             <start></start>
                   18169:             <end></end>
                   18170: 
                   18171:             <password></password>  for scope type = guest
                   18172: 
                   18173:             <domain></domain>     for scope type = course or group
                   18174:             <number></number>
                   18175:             <roles id="">
                   18176:              <role></role>
                   18177:              <access></access>
                   18178:              <section></section>
                   18179:              <group></group>
                   18180:             </roles>
                   18181: 
                   18182:             <dom></dom>         for scope type = domains
                   18183: 
                   18184:             <users>             for scope type = users
                   18185:              <user>
                   18186:               <uname></uname>
                   18187:               <udom></udom>
                   18188:              </user>
                   18189:             </users>
                   18190:            </scope> 
                   18191:               
                   18192:  Access data is also aggregated for each file in an additional key=value pair:
                   18193:  key -> path to file/file_name\0accesscontrol 
                   18194:  value -> reference to hash
                   18195:           hash contains key = value pairs
                   18196:           where key = uniqueID:scope_end_start
                   18197:                 value = UNIX time record was last updated
                   18198: 
                   18199:           Used to improve speed of look-ups of access controls for each file.  
                   18200:  
                   18201:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   18202: 
1.1198    raeburn  18203: =item *
                   18204: 
1.749     raeburn  18205: modify_access_controls():
                   18206: 
                   18207: Modifies access controls for a portfolio file
                   18208: Args
                   18209: 1. file name
                   18210: 2. reference to hash of required changes,
                   18211: 3. domain
                   18212: 4. username
                   18213:   where domain,username are the domain of the portfolio owner 
                   18214:   (either a user or a course) 
                   18215: 
                   18216: Returns:
                   18217: 1. result of additions or updates ('ok' or 'error', with error message). 
                   18218: 2. result of deletions ('ok' or 'error', with error message).
                   18219: 3. reference to hash of any new or updated access controls.
                   18220: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   18221:    key = integer (inbound ID)
1.1198    raeburn  18222:    value = uniqueID
                   18223: 
                   18224: =item *
                   18225: 
                   18226: get_timebased_id():
                   18227: 
                   18228: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   18229: course via the Course Editor (e.g., folders, composite pages, 
                   18230: group bulletin boards).
                   18231: 
                   18232: Args: (first three required; six others optional)
                   18233: 
                   18234: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   18235:    docssequence, or name of group
                   18236: 
                   18237: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   18238:    e.g., num, boardids
                   18239: 
                   18240: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   18241:    file will be named nohist_namespace.db
                   18242: 
                   18243: 4. cdom: domain of course; default is current course domain from %env
                   18244: 
                   18245: 5. cnum: course number; default is current course number from %env
                   18246: 
                   18247: 6. idtype: set to concat if an additional digit is to be appended to the 
                   18248:    unix timestamp to form the suffix, if the plain timestamp is already
                   18249:    in use.  Default is to not do this, but simply increment the unix 
                   18250:    timestamp by 1 until a unique key is obtained.
                   18251: 
                   18252: 7. who: holder of locking key; defaults to user:domain for user.
                   18253: 
                   18254: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   18255:    retrying); default is 3.
                   18256: 
                   18257: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   18258: 
                   18259: Returns:
                   18260: 
                   18261: 1. suffix obtained (numeric)
                   18262: 
                   18263: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   18264: 
                   18265: 3. error: contains (localized) error message if an error occurred.
                   18266: 
1.747     albertel 18267: 
1.608     albertel 18268: =back
                   18269: 
1.243     albertel 18270: =head2 HTTP Helper Routines
                   18271: 
                   18272: =over 4
                   18273: 
1.191     harris41 18274: =item *
                   18275: 
                   18276: escape() : unpack non-word characters into CGI-compatible hex codes
                   18277: 
                   18278: =item *
                   18279: 
                   18280: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   18281: 
1.243     albertel 18282: =back
                   18283: 
                   18284: =head1 PRIVATE SUBROUTINES
                   18285: 
                   18286: =head2 Underlying communication routines (Shouldn't call)
                   18287: 
                   18288: =over 4
                   18289: 
                   18290: =item *
                   18291: 
                   18292: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   18293: 
                   18294: =item *
                   18295: 
                   18296: reply() : uses subreply to send a message to remote machine, logs all failures
                   18297: 
                   18298: =item *
                   18299: 
                   18300: critical() : passes a critical message to another server; if cannot
                   18301: get through then place message in connection buffer directory and
                   18302: returns con_delayed, if incapable of saving message, returns
                   18303: con_failed
                   18304: 
                   18305: =item *
                   18306: 
                   18307: reconlonc() : tries to reconnect lonc client processes.
                   18308: 
                   18309: =back
                   18310: 
                   18311: =head2 Resource Access Logging
                   18312: 
                   18313: =over 4
                   18314: 
                   18315: =item *
                   18316: 
                   18317: flushcourselogs() : flush (save) buffer logs and access logs
                   18318: 
                   18319: =item *
                   18320: 
                   18321: courselog($what) : save message for course in hash
                   18322: 
                   18323: =item *
                   18324: 
                   18325: courseacclog($what) : save message for course using &courselog().  Perform
                   18326: special processing for specific resource types (problems, exams, quizzes, etc).
                   18327: 
1.191     harris41 18328: =item *
                   18329: 
                   18330: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   18331: as a PerlChildExitHandler
1.243     albertel 18332: 
                   18333: =back
                   18334: 
                   18335: =head2 Other
                   18336: 
                   18337: =over 4
                   18338: 
                   18339: =item *
                   18340: 
                   18341: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 18342: 
                   18343: =back
                   18344: 
                   18345: =cut
1.877     foxr     18346: 

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