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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1527  ! raeburn     4: # $Id: lonnet.pm,v 1.1526 2024/05/01 12:06:25 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
1.1389    raeburn    76: use CGI::Cookie;
1.1182    foxr       77: 
1.1173    foxr       78: use Encode;
                     79: 
1.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.1399    raeburn   191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850     albertel  192:     my $result = <$client>;
                    193:     chomp($result);
                    194:     return 1 if ($result eq 'done');
                    195:     return 0;
                    196: }
                    197: 
1.983     raeburn   198: sub get_server_timezone {
                    199:     my ($cnum,$cdom) = @_;
                    200:     my $home=&homeserver($cnum,$cdom);
                    201:     if ($home ne 'no_host') {
                    202:         my $cachetime = 24*3600;
                    203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    204:         if (defined($cached)) {
                    205:             return $timezone;
                    206:         } else {
                    207:             my $timezone = &reply('servertimezone',$home);
                    208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    209:         }
                    210:     }
                    211: }
1.850     albertel  212: 
1.1106    raeburn   213: sub get_server_distarch {
                    214:     my ($lonhost,$ignore_cache) = @_;
                    215:     if (defined($lonhost)) {
                    216:         if (!defined(&hostname($lonhost))) {
                    217:             return;
                    218:         }
                    219:         my $cachetime = 12*3600;
                    220:         if (!$ignore_cache) {
                    221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    222:             if (defined($cached)) {
                    223:                 return $distarch;
                    224:             }
                    225:         }
                    226:         my $rep = &reply('serverdistarch',$lonhost);
                    227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    229:                 $rep eq '') {
                    230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    231:         }
                    232:     }
                    233:     return;
                    234: }
                    235: 
1.1315    raeburn   236: sub get_servercerts_info {
1.1383    raeburn   237:     my ($lonhost,$hostname,$context) = @_;
                    238:     return if ($lonhost eq '');
                    239:     if ($hostname eq '') {
                    240:         $hostname = &hostname($lonhost);
                    241:     }
                    242:     return if ($hostname eq '');
1.1315    raeburn   243:     my ($rep,$uselocal);
1.1388    raeburn   244:     if ($context eq 'install') {
1.1387    raeburn   245:         $uselocal = 1;
                    246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   247:         $uselocal = 1;
                    248:     }
1.1387    raeburn   249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   251:         if ($distro eq '') {
                    252:             $uselocal = 0;
                    253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   254:             if ($1 < 6) {
                    255:                 $uselocal = 0;
                    256:             }
1.1346    raeburn   257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    258:             if ($1 < 12) {
                    259:                 $uselocal = 0;
                    260:             }
1.1315    raeburn   261:         }
                    262:     }
                    263:     if ($uselocal) {
1.1383    raeburn   264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   265:     } else {
                    266:         $rep=&reply('servercerts',$lonhost);
                    267:     }
                    268:     my ($result,%returnhash);
                    269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    270:         ($rep eq 'unknown_cmd')) {
                    271:         $result = $rep;
                    272:     } else {
                    273:         $result = 'ok';
                    274:         my @pairs=split(/\&/,$rep);
                    275:         foreach my $item (@pairs) {
                    276:             my ($key,$value)=split(/=/,$item,2);
                    277:             my $what = &unescape($key);
                    278:             $returnhash{$what}=&thaw_unescape($value);
                    279:         }
                    280:     }
                    281:     return ($result,\%returnhash);
                    282: }
                    283: 
1.993     raeburn   284: sub get_server_loncaparev {
1.1073    raeburn   285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   286:     if (defined($lonhost)) {
                    287:         if (!defined(&hostname($lonhost))) {
                    288:             undef($lonhost);
                    289:         }
                    290:     }
                    291:     if (!defined($lonhost)) {
                    292:         if (defined(&domain($dom,'primary'))) {
                    293:             $lonhost=&domain($dom,'primary');
                    294:             if ($lonhost eq 'no_host') {
                    295:                 undef($lonhost);
                    296:             }
                    297:         }
                    298:     }
                    299:     if (defined($lonhost)) {
1.1073    raeburn   300:         my $cachetime = 12*3600;
                    301:         if (!$ignore_cache) {
                    302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    303:             if (defined($cached)) {
                    304:                 return $loncaparev;
                    305:             }
                    306:         }
                    307:         my ($answer,$loncaparev);
                    308:         my @ids=&current_machine_ids();
                    309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    310:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   312:                 $loncaparev = $1;
                    313:             }
                    314:         } else {
                    315:             $answer = &reply('serverloncaparev',$lonhost);
                    316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    317:                 if ($caller eq 'loncron') {
1.1397    raeburn   318:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   319:                     my $protocol = $protocol{$lonhost};
                    320:                     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn   321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   322:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   324:                     unless ($response->is_error()) {
                    325:                         my $content = $response->content;
1.1081    raeburn   326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   327:                             $loncaparev = $1;
                    328:                         }
                    329:                     }
                    330:                 } else {
                    331:                     $loncaparev = $loncaparevs{$lonhost};
                    332:                 }
1.1081    raeburn   333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   334:                 $loncaparev = $1;
                    335:             }
1.993     raeburn   336:         }
1.1073    raeburn   337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   338:     }
                    339: }
                    340: 
1.1074    raeburn   341: sub get_server_homeID {
                    342:     my ($hostname,$ignore_cache,$caller) = @_;
                    343:     unless ($ignore_cache) {
                    344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    345:         if (defined($cached)) {
                    346:             return $serverhomeID;
                    347:         }
                    348:     }
                    349:     my $cachetime = 12*3600;
                    350:     my $serverhomeID;
                    351:     if ($caller eq 'loncron') { 
                    352:         my @machine_ids = &machine_ids($hostname);
                    353:         foreach my $id (@machine_ids) {
                    354:             my $response = &reply('serverhomeID',$id);
                    355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    356:                 $serverhomeID = $response;
                    357:                 last;
                    358:             }
                    359:         }
                    360:         if ($serverhomeID eq '') {
                    361:             $serverhomeID = $machine_ids[-1];
                    362:         }
                    363:     } else {
                    364:         $serverhomeID = $serverhomeIDs{$hostname};
                    365:     }
                    366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    367: }
                    368: 
1.1121    raeburn   369: sub get_remote_globals {
                    370:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   371:     my ($result,%returnhash,%whatneeded);
                    372:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   373:         foreach my $what (sort(keys(%{$whathash}))) {
                    374:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   375:             my ($response,$cached);
1.1121    raeburn   376:             unless ($ignore_cache) {
1.1125    raeburn   377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   378:             }
                    379:             if (defined($cached)) {
1.1125    raeburn   380:                 $returnhash{$what} = $response;
1.1121    raeburn   381:             } else {
1.1125    raeburn   382:                 $whatneeded{$what} = 1;
1.1121    raeburn   383:             }
                    384:         }
1.1125    raeburn   385:         if (keys(%whatneeded) == 0) {
                    386:             $result = 'ok';
                    387:         } else {
1.1121    raeburn   388:             my $requested = &freeze_escape(\%whatneeded);
                    389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    391:                 ($rep eq 'unknown_cmd')) {
                    392:                 $result = $rep;
                    393:             } else {
                    394:                 $result = 'ok';
1.1121    raeburn   395:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   396:                 foreach my $item (@pairs) {
                    397:                     my ($key,$value)=split(/=/,$item,2);
                    398:                     my $what = &unescape($key);
                    399:                     my $hashid = $lonhost.'-'.$what;
                    400:                     $returnhash{$what}=&thaw_unescape($value);
                    401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   402:                 }
                    403:             }
                    404:         }
                    405:     }
1.1125    raeburn   406:     return ($result,\%returnhash);
1.1121    raeburn   407: }
                    408: 
1.1124    raeburn   409: sub remote_devalidate_cache {
1.1241    raeburn   410:     my ($lonhost,$cachekeys) = @_;
                    411:     my $items;
                    412:     return unless (ref($cachekeys) eq 'ARRAY');
                    413:     my $cachestr = join('&',@{$cachekeys});
                    414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   415:     return $response;
                    416: }
                    417: 
1.1510    raeburn   418: sub sign_lti {
1.1511    raeburn   419:     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
1.1510    raeburn   420:     my $chome;
                    421:     if (&domain($cdom) ne '') {
1.1511    raeburn   422:         if ($crsdef) {
1.1510    raeburn   423:             $chome = &homeserver($cnum,$cdom);
                    424:         } else {
                    425:             $chome = &domain($cdom,'primary');
                    426:         }
                    427:     }
                    428:     if ($cdom && $chome && ($chome ne 'no_host')) {
                    429:         if ((ref($paramsref) eq 'HASH') &&
                    430:             (ref($inforef) eq 'HASH')) {
                    431:             my $rep;
                    432:             if (grep { $_ eq $chome } &current_machine_ids()) {
                    433:                 # domain information is hosted on this machine
                    434:                 $rep =
1.1511    raeburn   435:                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
                    436:                                                      $context,$url,$ltinum,$keynum,
                    437:                                                      $perlvar{'lonVersion'},
                    438:                                                      $paramsref,$inforef);
                    439:                 if (ref($rep) eq 'HASH') {
1.1510    raeburn   440:                     return ('ok',$rep);
                    441:                 }
                    442:             } else {
                    443:                 my ($escurl,$params,$info);
                    444:                 $escurl = &escape($url);
                    445:                 if (ref($paramsref) eq 'HASH') {
                    446:                     $params = &freeze_escape($paramsref);
                    447:                 }
                    448:                 if (ref($inforef) eq 'HASH') {
                    449:                     $info = &freeze_escape($inforef);
                    450:                 }
1.1511    raeburn   451:                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
1.1510    raeburn   452:             }
                    453:             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
                    454:                 return ();
1.1511    raeburn   455:             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
                    456:                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
                    457:                 return ('ok',$rep);
1.1510    raeburn   458:             } else {
                    459:                 my %returnhash;
                    460:                 foreach my $item (split(/\&/,$rep)) {
                    461:                     my ($name,$value)=split(/\=/,$item);
                    462:                     $returnhash{&unescape($name)}=&thaw_unescape($value);
                    463:                 }
                    464:                 return('ok',\%returnhash);
                    465:             }
                    466:         } else {
                    467:             return ();
                    468:         }
                    469:     } else {
                    470:         return ();
                    471:         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
                    472:     }
                    473: }
                    474: 
1.1       albertel  475: # -------------------------------------------------- Non-critical communication
                    476: sub subreply {
                    477:     my ($cmd,$server)=@_;
1.838     albertel  478:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      479:     #
                    480:     #  With loncnew process trimming, there's a timing hole between lonc server
                    481:     #  process exit and the master server picking up the listen on the AF_UNIX
                    482:     #  socket.  In that time interval, a lock file will exist:
                    483: 
                    484:     my $lockfile=$peerfile.".lock";
                    485:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   486: 	sleep(0.1);
1.549     foxr      487:     }
                    488:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      489:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      490:     #
1.550     foxr      491:     #   We'll give the connection a few tries before abandoning it.  If
                    492:     #   connection is not possible, we'll con_lost back to the client.
                    493:     #   
                    494:     my $client;
                    495:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    496: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    497: 				      Type    => SOCK_STREAM,
                    498: 				      Timeout => 10);
1.869     albertel  499: 	if ($client) {
1.550     foxr      500: 	    last;		# Connected!
1.850     albertel  501: 	} else {
1.853     albertel  502: 	    &create_connection(&hostname($server),$server);
1.550     foxr      503: 	}
1.1289    damieng   504:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      505:     }
                    506:     my $answer;
                    507:     if ($client) {
1.704     albertel  508: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      509: 	$answer=<$client>;
                    510: 	if (!$answer) { $answer="con_lost"; }
                    511: 	chomp($answer);
                    512:     } else {
                    513: 	$answer = 'con_lost';	# Failed connection.
                    514:     }
1.1       albertel  515:     return $answer;
                    516: }
                    517: 
                    518: sub reply {
                    519:     my ($cmd,$server)=@_;
1.838     albertel  520:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  521:     my $answer=subreply($cmd,$server);
1.65      www       522:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396    raeburn   523:         my $logged = $cmd;
                    524:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    525:             my $subcmd = $1;
                    526:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    527:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462    raeburn   528:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
                    529:                 ($subcmd eq 'put')) {
1.1396    raeburn   530:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    531:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    532:                     splice(@rest,2,1,'Hidden');
                    533:                 } elsif ($subcmd eq 'passwd') {
                    534:                     splice(@rest,2,2,('Hidden','Hidden'));
                    535:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462    raeburn   536:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1396    raeburn   537:                     splice(@rest,3,1,'Hidden');
                    538:                 }
                    539:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    540:             }
                    541:         }
                    542:         &logthis("<font color=\"blue\">WARNING:".
                    543:                  " $logged to $server returned $answer</font>");
1.12      www       544:     }
1.1       albertel  545:     return $answer;
                    546: }
                    547: 
                    548: # ----------------------------------------------------------- Send USR1 to lonc
                    549: 
                    550: sub reconlonc {
1.891     albertel  551:     my ($lonid) = @_;
                    552:     if ($lonid) {
1.1295    raeburn   553:         my $hostname = &hostname($lonid);
1.891     albertel  554: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    555: 	if ($hostname && -e $peerfile) {
                    556: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    557: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    558: 					     Type    => SOCK_STREAM,
                    559: 					     Timeout => 10);
                    560: 	    if ($client) {
                    561: 		print $client ("reset_retries\n");
                    562: 		my $answer=<$client>;
                    563: 		#reset just this one.
                    564: 	    }
                    565: 	}
                    566: 	return;
                    567:     }
                    568: 
1.836     www       569:     &logthis("Trying to reconnect lonc");
1.1       albertel  570:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   571:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  572: 	my $loncpid=<$fh>;
                    573:         chomp($loncpid);
                    574:         if (kill 0 => $loncpid) {
                    575: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    576:             kill USR1 => $loncpid;
                    577:             sleep 1;
1.1295    raeburn   578:         } else {
1.12      www       579: 	    &logthis(
1.672     albertel  580:                "<font color=\"blue\">WARNING:".
1.12      www       581:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  582:         }
                    583:     } else {
1.836     www       584: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  585:     }
                    586: }
                    587: 
                    588: # ------------------------------------------------------ Critical communication
1.12      www       589: 
1.1       albertel  590: sub critical {
                    591:     my ($cmd,$server)=@_;
1.838     albertel  592:     unless (&hostname($server)) {
1.672     albertel  593:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       594:                " Critical message to unknown server ($server)</font>");
                    595:         return 'no_such_host';
                    596:     }
1.1       albertel  597:     my $answer=reply($cmd,$server);
                    598:     if ($answer eq 'con_lost') {
1.1295    raeburn   599: 	&reconlonc($server);
1.589     albertel  600: 	my $answer=reply($cmd,$server);
1.1       albertel  601:         if ($answer eq 'con_lost') {
                    602:             my $now=time;
                    603:             my $middlename=$cmd;
1.5       www       604:             $middlename=substr($middlename,0,16);
1.1       albertel  605:             $middlename=~s/\W//g;
                    606:             my $dfilename=
1.305     www       607:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    608:             $dumpcount++;
1.1       albertel  609:             {
1.448     albertel  610: 		my $dfh;
1.1359    raeburn   611: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  612: 		    print $dfh "$cmd\n"; 
                    613: 		    close($dfh);
                    614: 		}
1.1       albertel  615:             }
1.1288    damieng   616:             sleep 1;
1.1       albertel  617:             my $wcmd='';
                    618:             {
1.448     albertel  619: 		my $dfh;
1.1359    raeburn   620: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  621: 		    $wcmd=<$dfh>; 
                    622: 		    close($dfh);
                    623: 		}
1.1       albertel  624:             }
                    625:             chomp($wcmd);
1.7       www       626:             if ($wcmd eq $cmd) {
1.672     albertel  627: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       628:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  629:                 &logperm("D:$server:$cmd");
                    630: 	        return 'con_delayed';
                    631:             } else {
1.672     albertel  632:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       633:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  634:                 &logperm("F:$server:$cmd");
                    635:                 return 'con_failed';
                    636:             }
                    637:         }
                    638:     }
                    639:     return $answer;
1.405     albertel  640: }
                    641: 
1.755     albertel  642: # ------------------------------------------- check if return value is an error
                    643: 
                    644: sub error {
                    645:     my ($result) = @_;
1.756     albertel  646:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  647: 	if ($2 == 2) { return undef; }
                    648: 	return $1;
                    649:     }
                    650:     return undef;
                    651: }
                    652: 
1.783     albertel  653: sub convert_and_load_session_env {
                    654:     my ($lonidsdir,$handle)=@_;
                    655:     my @profile;
                    656:     {
1.917     albertel  657: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    658: 	if (!$opened) {
1.915     albertel  659: 	    return 0;
                    660: 	}
1.783     albertel  661: 	flock($idf,LOCK_SH);
                    662: 	@profile=<$idf>;
                    663: 	close($idf);
                    664:     }
                    665:     my %temp_env;
                    666:     foreach my $line (@profile) {
1.786     albertel  667: 	if ($line !~ m/=/) {
                    668: 	    return 0;
                    669: 	}
1.783     albertel  670: 	chomp($line);
                    671: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    672: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    673:     }
                    674:     unlink("$lonidsdir/$handle.id");
                    675:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    676: 	    0640)) {
                    677: 	%disk_env = %temp_env;
                    678: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    679: 	untie(%disk_env);
                    680:     }
1.786     albertel  681:     return 1;
1.783     albertel  682: }
                    683: 
1.374     www       684: # ------------------------------------------- Transfer profile into environment
1.780     albertel  685: my $env_loaded;
                    686: sub transfer_profile_to_env {
1.788     albertel  687:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    688:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       689: 
1.720     albertel  690:     if (!defined($lonidsdir)) {
                    691: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    692:     }
                    693:     if (!defined($handle)) {
                    694:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    695:     }
                    696: 
1.786     albertel  697:     my $convert;
                    698:     {
1.917     albertel  699:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    700: 	if (!$opened) {
1.915     albertel  701: 	    return;
                    702: 	}
1.786     albertel  703: 	flock($idf,LOCK_SH);
                    704: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    705: 		&GDBM_READER(),0640)) {
                    706: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    707: 	    untie(%disk_env);
                    708: 	} else {
                    709: 	    $convert = 1;
                    710: 	}
                    711:     }
                    712:     if ($convert) {
                    713: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    714: 	    &logthis("Failed to load session, or convert session.");
                    715: 	}
1.374     www       716:     }
1.783     albertel  717: 
1.786     albertel  718:     my %remove;
1.783     albertel  719:     while ( my $envname = each(%env) ) {
1.433     matthew   720:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    721:             if ($time < time-300) {
1.783     albertel  722:                 $remove{$key}++;
1.433     matthew   723:             }
                    724:         }
                    725:     }
1.783     albertel  726: 
1.619     albertel  727:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  728:     $env_loaded=1;
1.783     albertel  729:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   730:         &delenv($expired_key);
1.374     www       731:     }
1.1       albertel  732: }
                    733: 
1.916     albertel  734: # ---------------------------------------------------- Check for valid session 
                    735: sub check_for_valid_session {
1.1355    raeburn   736:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  737:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   738:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    739:     if ($name eq 'lonDAV') {
                    740:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    741:     } else {
                    742:         $lonidsdir=$r->dir_config('lonIDsDir');
                    743:         if ($name eq '') {
                    744:             $name = 'lonID';
                    745:         }
                    746:     }
                    747:     if ($name eq 'lonID') {
                    748:         $secure = 'lonSID';
1.1337    raeburn   749:         $linkname = 'lonLinkID';
                    750:         $pubname = 'lonPubID';
1.1378    raeburn   751:         if (exists($cookies{$secure})) {
                    752:             $lonid=$cookies{$secure};
                    753:         } elsif (exists($cookies{$name})) {
                    754:             $lonid=$cookies{$name};
1.1400    raeburn   755:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337    raeburn   756:             $lonid=$cookies{$linkname};
1.1378    raeburn   757:         } elsif (exists($cookies{$pubname})) {
                    758:             $lonid=$cookies{$pubname};
1.1337    raeburn   759:         }
1.1378    raeburn   760:     } else {
                    761:         $lonid=$cookies{$name};
1.1337    raeburn   762:     }
1.916     albertel  763:     return undef if (!$lonid);
                    764: 
                    765:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   766:     if (-l "$lonidsdir/$handle.id") {
                    767:         my $link = readlink("$lonidsdir/$handle.id");
                    768:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    769:             $handle = $1;
                    770:         }
1.1155    raeburn   771:     }
1.1355    raeburn   772:     if (!-e "$lonidsdir/$handle.id") {
                    773:         if ((ref($domref)) && ($name eq 'lonID') && 
                    774:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    775:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    776:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    777:                 $$domref = $possudom;
                    778:             }
                    779:         }
                    780:         return undef;
                    781:     }
1.916     albertel  782: 
1.917     albertel  783:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    784:     return undef if (!$opened);
1.916     albertel  785: 
                    786:     flock($idf,LOCK_SH);
                    787:     my %disk_env;
                    788:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    789: 	    &GDBM_READER(),0640)) {
                    790: 	return undef;	
                    791:     }
                    792: 
                    793:     if (!defined($disk_env{'user.name'})
                    794: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   795:         untie(%disk_env);
1.916     albertel  796: 	return undef;
                    797:     }
1.1245    raeburn   798: 
                    799:     if (ref($userhashref) eq 'HASH') {
                    800:         $userhashref->{'name'} = $disk_env{'user.name'};
                    801:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448    raeburn   802:         if ($disk_env{'request.role'}) {
                    803:             $userhashref->{'role'} = $disk_env{'request.role'};
                    804:         }
1.1361    raeburn   805:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   806:         if ($userhashref->{'lti'}) {
                    807:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    808:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    809:         }
1.1212    raeburn   810:     }
1.1394    raeburn   811:     untie(%disk_env);
1.1245    raeburn   812: 
1.916     albertel  813:     return $handle;
                    814: }
                    815: 
1.830     albertel  816: sub timed_flock {
                    817:     my ($file,$lock_type) = @_;
                    818:     my $failed=0;
                    819:     eval {
                    820: 	local $SIG{__DIE__}='DEFAULT';
                    821: 	local $SIG{ALRM}=sub {
                    822: 	    $failed=1;
                    823: 	    die("failed lock");
                    824: 	};
                    825: 	alarm(13);
                    826: 	flock($file,$lock_type);
                    827: 	alarm(0);
                    828:     };
                    829:     if ($failed) {
                    830: 	return undef;
                    831:     } else {
                    832: 	return 1;
                    833:     }
                    834: }
                    835: 
1.1392    raeburn   836: sub get_sessionfile_vars {
                    837:     my ($handle,$lonidsdir,$storearr) = @_;
                    838:     my %returnhash;
                    839:     unless (ref($storearr) eq 'ARRAY') {
                    840:         return %returnhash;
                    841:     }
                    842:     if (-l "$lonidsdir/$handle.id") {
                    843:         my $link = readlink("$lonidsdir/$handle.id");
                    844:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    845:             $handle = $1;
                    846:         }
                    847:     }
                    848:     if ((-e "$lonidsdir/$handle.id") &&
                    849:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    850:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    851:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    852:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    853:                 flock($idf,LOCK_SH);
                    854:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    855:                         &GDBM_READER(),0640)) {
                    856:                     foreach my $item (@{$storearr}) {
                    857:                         $returnhash{$item} = $disk_env{$item};
                    858:                     }
                    859:                     untie(%disk_env);
                    860:                 }
                    861:             }
                    862:         }
                    863:     }
                    864:     return %returnhash;
                    865: }
                    866: 
1.5       www       867: # ---------------------------------------------------------- Append Environment
                    868: 
                    869: sub appenv {
1.949     raeburn   870:     my ($newenv,$roles) = @_;
                    871:     if (ref($newenv) eq 'HASH') {
                    872:         foreach my $key (keys(%{$newenv})) {
                    873:             my $refused = 0;
                    874: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    875:                 $refused = 1;
                    876:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   877:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   878:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    879:                         $refused = 0;
                    880:                     }
                    881:                 }
                    882:             }
                    883:             if ($refused) {
                    884:                 &logthis("<font color=\"blue\">WARNING: ".
                    885:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    886:                          .'</font>');
                    887: 	        delete($newenv->{$key});
                    888:             } else {
                    889:                 $env{$key}=$newenv->{$key};
                    890:             }
                    891:         }
1.1376    raeburn   892:         my $lonids = $perlvar{'lonIDsDir'};
                    893:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    894:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    895:             if ($opened
                    896: 	        && &timed_flock($env_file,LOCK_EX)
                    897: 	        &&
                    898: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    899: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    900: 	        while (my ($key,$value) = each(%{$newenv})) {
                    901: 	            $disk_env{$key} = $value;
                    902: 	        }
                    903: 	        untie(%disk_env);
                    904:             }
1.35      www       905:         }
1.191     harris41  906:     }
1.56      www       907:     return 'ok';
                    908: }
                    909: # ----------------------------------------------------- Delete from Environment
                    910: 
                    911: sub delenv {
1.1104    raeburn   912:     my ($delthis,$regexp,$roles) = @_;
                    913:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    914:         my $refused = 1;
                    915:         if (ref($roles) eq 'ARRAY') {
                    916:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    917:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    918:                 $refused = 0;
                    919:             }
                    920:         }
                    921:         if ($refused) {
                    922:             &logthis("<font color=\"blue\">WARNING: ".
                    923:                      "Attempt to delete from environment ".$delthis);
                    924:             return 'error';
                    925:         }
1.56      www       926:     }
1.917     albertel  927:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    928:     if ($opened
1.915     albertel  929: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  930: 	&&
                    931: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    932: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  933: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   934: 	    if ($regexp) {
                    935:                 if ($key=~/^$delthis/) {
                    936:                     delete($env{$key});
                    937:                     delete($disk_env{$key});
                    938:                 } 
                    939:             } else {
                    940:                 if ($key=~/^\Q$delthis\E/) {
                    941: 		    delete($env{$key});
                    942: 		    delete($disk_env{$key});
                    943: 	        }
                    944:             }
1.448     albertel  945: 	}
1.783     albertel  946: 	untie(%disk_env);
1.5       www       947:     }
                    948:     return 'ok';
1.369     albertel  949: }
                    950: 
1.790     albertel  951: sub get_env_multiple {
                    952:     my ($name) = @_;
                    953:     my @values;
                    954:     if (defined($env{$name})) {
                    955:         # exists is it an array
                    956:         if (ref($env{$name})) {
                    957:             @values=@{ $env{$name} };
                    958:         } else {
                    959:             $values[0]=$env{$name};
                    960:         }
                    961:     }
                    962:     return(@values);
                    963: }
                    964: 
1.958     www       965: # ------------------------------------------------------------------- Locking
                    966: 
                    967: sub set_lock {
                    968:     my ($text)=@_;
                    969:     $locknum++;
                    970:     my $id=$$.'-'.$locknum;
                    971:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    972:              'session.lock.'.$id => $text});
                    973:     return $id;
                    974: }
                    975: 
                    976: sub get_locks {
                    977:     my $num=0;
                    978:     my %texts=();
                    979:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    980:        if ($lock=~/\w/) {
                    981:           $num++;
                    982:           $texts{$lock}=$env{'session.lock.'.$lock};
                    983:        }
                    984:    }
                    985:    return ($num,%texts);
                    986: }
                    987: 
                    988: sub remove_lock {
                    989:     my ($id)=@_;
                    990:     my $newlocks='';
                    991:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    992:        if (($lock=~/\w/) && ($lock ne $id)) {
                    993:           $newlocks.=','.$lock;
                    994:        }
                    995:     }
                    996:     &appenv({'session.locks' => $newlocks});
                    997:     &delenv('session.lock.'.$id);
                    998: }
                    999: 
                   1000: sub remove_all_locks {
                   1001:     my $activelocks=$env{'session.locks'};
                   1002:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                   1003:        if ($lock=~/\w/) {
                   1004:           &remove_lock($lock);
                   1005:        }
                   1006:     }
                   1007: }
                   1008: 
                   1009: 
1.369     albertel 1010: # ------------------------------------------ Find out current server userload
                   1011: sub userload {
                   1012:     my $numusers=0;
                   1013:     {
                   1014: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   1015: 	my $filename;
                   1016: 	my $curtime=time;
                   1017: 	while ($filename=readdir(LONIDS)) {
1.925     albertel 1018: 	    next if ($filename eq '.' || $filename eq '..');
                   1019: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn  1020:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel 1021: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel 1022: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel 1023: 	}
                   1024: 	closedir(LONIDS);
                   1025:     }
                   1026:     my $userloadpercent=0;
                   1027:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   1028:     if ($maxuserload) {
1.371     albertel 1029: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel 1030:     }
1.372     albertel 1031:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel 1032:     return $userloadpercent;
1.283     www      1033: }
                   1034: 
1.1       albertel 1035: # ------------------------------ Find server with least workload from spare.tab
1.11      www      1036: 
1.1       albertel 1037: sub spareserver {
1.1451    raeburn  1038:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel 1039:     my $spare_server;
1.370     albertel 1040:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel 1041:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                   1042:                                                      :  $userloadpercent;
1.1083    raeburn  1043:     my ($uint_dom,$remotesessions);
                   1044:     if (($udom ne '') && (&domain($udom) ne '')) {
1.1494    raeburn  1045:         my $uprimary_id = &domain($udom,'primary');
                   1046:         $uint_dom = &internet_dom($uprimary_id);
                   1047:         my %udomdefaults = &get_domain_defaults($udom);
1.1083    raeburn  1048:         $remotesessions = $udomdefaults{'remotesessions'};
                   1049:     }
1.1123    raeburn  1050:     my $spareshash = &this_host_spares($udom);
                   1051:     if (ref($spareshash) eq 'HASH') {
                   1052:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1053:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn  1054:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                   1055:                                              $try_server));
1.1123    raeburn  1056: 	        ($spare_server, $lowest_load) =
                   1057: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                   1058:             }
1.1083    raeburn  1059:         }
1.784     albertel 1060: 
1.1123    raeburn  1061:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                   1062: 
                   1063:         if (!$found_server) {
                   1064:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1065: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1066:                     next unless (&spare_can_host($udom,$uint_dom,
                   1067:                                                  $remotesessions,$try_server));
1.1123    raeburn  1068: 	            ($spare_server, $lowest_load) =
                   1069: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1070:                 }
                   1071: 	    }
                   1072:         }
1.784     albertel 1073:     }
                   1074: 
                   1075:     if (!$want_server_name) {
1.1001    raeburn  1076:         if (defined($spare_server)) {
                   1077:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1078:             if (defined($hostname)) {
1.1397    raeburn  1079:                 my $protocol = 'http';
                   1080:                 if ($protocol{$spare_server} eq 'https') {
                   1081:                     $protocol = $protocol{$spare_server};
                   1082:                 }
1.1494    raeburn  1083:                 my $alias = &use_proxy_alias($r,$spare_server);
1.1451    raeburn  1084:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn  1085: 	        $spare_server = $protocol.'://'.$hostname;
                   1086:             }
                   1087:         }
1.784     albertel 1088:     }
                   1089:     return $spare_server;
                   1090: }
                   1091: 
                   1092: sub compare_server_load {
1.1253    raeburn  1093:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1094: 
                   1095:     if ($required) {
                   1096:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1097:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1098:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1099:         if (($major eq '' && $minor eq '') ||
                   1100:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1101:             return ($spare_server,$lowest_load);
                   1102:         }
                   1103:     }
1.784     albertel 1104: 
                   1105:     my $loadans     = &reply('load',    $try_server);
                   1106:     my $userloadans = &reply('userload',$try_server);
                   1107: 
                   1108:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1109: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1110:     }
                   1111: 
                   1112:     my $load;
                   1113:     if ($loadans =~ /\d/) {
                   1114: 	if ($userloadans =~ /\d/) {
                   1115: 	    #both are numbers, pick the bigger one
                   1116: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1117: 		                              : $userloadans;
1.411     albertel 1118: 	} else {
1.784     albertel 1119: 	    $load = $loadans;
1.411     albertel 1120: 	}
1.784     albertel 1121:     } else {
                   1122: 	$load = $userloadans;
                   1123:     }
                   1124: 
                   1125:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1126: 	$spare_server = $try_server;
                   1127: 	$lowest_load  = $load;
1.370     albertel 1128:     }
1.784     albertel 1129:     return ($spare_server,$lowest_load);
1.202     matthew  1130: }
1.914     albertel 1131: 
                   1132: # --------------------------- ask offload servers if user already has a session
                   1133: sub find_existing_session {
                   1134:     my ($udom,$uname) = @_;
1.1123    raeburn  1135:     my $spareshash = &this_host_spares($udom);
                   1136:     if (ref($spareshash) eq 'HASH') {
                   1137:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1138:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1139:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1140:             }
                   1141:         }
                   1142:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1143:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1144:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1145:             }
                   1146:         }
1.914     albertel 1147:     }
                   1148:     return;
                   1149: }
                   1150: 
1.1411    raeburn  1151: sub delusersession {
                   1152:     my ($lonid,$udom,$uname) = @_;
                   1153:     my $uprimary_id = &domain($udom,'primary');
                   1154:     my $uintdom = &internet_dom($uprimary_id);
                   1155:     my $intdom = &internet_dom($lonid);
                   1156:     my $serverhomedom = &host_domain($lonid);
                   1157:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1158:         return &reply(join(':','delusersession',
                   1159:                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1160:     }
                   1161:     return;
                   1162: }
                   1163: 
1.1389    raeburn  1164: # check if user's browser sent load balancer cookie and server still has session
                   1165: # and is not overloaded.
                   1166: sub check_for_balancer_cookie {
                   1167:     my ($r,$update_mtime) = @_;
                   1168:     my ($otherserver,$cookie);
                   1169:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1170:     if (exists($cookies{'balanceID'})) {
                   1171:         my $balid = $cookies{'balanceID'};
                   1172:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1173:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1174:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1175:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1176:                 my ($possudom,$possuname) = ($1,$2);
                   1177:                 my $has_session = 0;
                   1178:                 if ((&domain($possudom) ne '') &&
                   1179:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1180:                     my $try_server;
                   1181:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1182:                     if ($opened) {
                   1183:                         flock($idf,LOCK_SH);
                   1184:                         while (my $line = <$idf>) {
                   1185:                             chomp($line);
                   1186:                             if (&hostname($line) ne '') {
                   1187:                                 $try_server = $line;
                   1188:                                 last;
                   1189:                             }
                   1190:                         }
                   1191:                         close($idf);
                   1192:                         if (($try_server) &&
                   1193:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1194:                             my $lowest_load = 30000;
                   1195:                             ($otherserver,$lowest_load) =
                   1196:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1197:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1198:                                 $has_session = 1;
                   1199:                             } else {
                   1200:                                 undef($otherserver);
                   1201:                             }
                   1202:                         }
                   1203:                     }
                   1204:                 }
                   1205:                 if ($has_session) {
                   1206:                     if ($update_mtime) {
                   1207:                         my $atime = my $mtime = time;
                   1208:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1209:                     }
                   1210:                 } else {
                   1211:                     unlink("$balancedir/$cookie.id");
                   1212:                 }
                   1213:             }
                   1214:         }
                   1215:     }
                   1216:     return ($otherserver,$cookie);
                   1217: }
                   1218: 
1.1431    raeburn  1219: sub updatebalcookie {
                   1220:     my ($cookie,$balancer,$lastentry)=@_;
                   1221:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1222:         my ($udom,$uname) = ($1,$2);
                   1223:         my $uprimary_id = &domain($udom,'primary');
                   1224:         my $uintdom = &internet_dom($uprimary_id);
                   1225:         my $intdom = &internet_dom($balancer);
                   1226:         my $serverhomedom = &host_domain($balancer);
                   1227:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1228:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1229:         }
                   1230:     }
                   1231:     return;
                   1232: }
                   1233: 
1.1389    raeburn  1234: sub delbalcookie {
                   1235:     my ($cookie,$balancer) =@_;
                   1236:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1237:         my ($udom,$uname) = ($1,$2);
                   1238:         my $uprimary_id = &domain($udom,'primary');
                   1239:         my $uintdom = &internet_dom($uprimary_id);
                   1240:         my $intdom = &internet_dom($balancer);
                   1241:         my $serverhomedom = &host_domain($balancer);
                   1242:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431    raeburn  1243:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389    raeburn  1244:         }
                   1245:     }
                   1246: }
                   1247: 
1.914     albertel 1248: # -------------------------------- ask if server already has a session for user
                   1249: sub has_user_session {
                   1250:     my ($lonid,$udom,$uname) = @_;
                   1251:     my $result = &reply(join(':','userhassession',
                   1252: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1253:     return 1 if ($result eq 'ok');
                   1254: 
                   1255:     return 0;
                   1256: }
                   1257: 
1.1076    raeburn  1258: # --------- determine least loaded server in a user's domain which allows login
                   1259: 
                   1260: sub choose_server {
1.1259    raeburn  1261:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1262:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1263:     my %servers = &get_servers($udom);
1.1076    raeburn  1264:     my $lowest_load = 30000;
1.1259    raeburn  1265:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1266:     if ($skiploadbal) {
                   1267:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1268:         unless (defined($cached)) {
                   1269:             my $cachetime = 60*60*24;
                   1270:             my %domconfig =
1.1494    raeburn  1271:                 &get_dom('configuration',['loadbalancing'],$udom);
1.1259    raeburn  1272:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1273:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1274:                                            $cachetime);
                   1275:             }
                   1276:         }
                   1277:     }
1.1076    raeburn  1278:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1279:         if ($skiploadbal) {
                   1280:             if (ref($balancers) eq 'HASH') {
                   1281:                 next if (exists($balancers->{$lonhost}));
                   1282:             }
1.1389    raeburn  1283:         }
1.1115    raeburn  1284:         my $loginvia;
                   1285:         if ($checkloginvia) {
                   1286:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1287:             if ($loginvia) {
                   1288:                 my ($server,$path) = split(/:/,$loginvia);
                   1289:                 ($login_host, $lowest_load) =
1.1253    raeburn  1290:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1291:                 if ($login_host eq $server) {
                   1292:                     $portal_path = $path;
1.1151    raeburn  1293:                     $isredirect = 1;
1.1116    raeburn  1294:                 }
                   1295:             } else {
                   1296:                 ($login_host, $lowest_load) =
1.1253    raeburn  1297:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1298:                 if ($login_host eq $lonhost) {
                   1299:                     $portal_path = '';
1.1151    raeburn  1300:                     $isredirect = ''; 
1.1116    raeburn  1301:                 }
                   1302:             }
                   1303:         } else {
1.1076    raeburn  1304:             ($login_host, $lowest_load) =
1.1253    raeburn  1305:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1306:         }
                   1307:     }
                   1308:     if ($login_host ne '') {
1.1116    raeburn  1309:         $hostname = &hostname($login_host);
1.1076    raeburn  1310:     }
1.1331    raeburn  1311:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1312: }
                   1313: 
1.1420    raeburn  1314: sub get_course_sessions {
                   1315:     my ($cnum,$cdom,$lastactivity) = @_;
                   1316:     my %servers = &internet_dom_servers($cdom);
                   1317:     my %returnhash;
                   1318:     foreach my $server (sort(keys(%servers))) {
                   1319:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1320:         my @pairs=split(/\&/,$rep);
                   1321:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1322:             foreach my $item (@pairs) {
                   1323:                 my ($key,$value)=split(/=/,$item,2);
                   1324:                 $key = &unescape($key);
                   1325:                 next if ($key =~ /^error: 2 /);
                   1326:                 if (exists($returnhash{$key})) {
                   1327:                     next if ($value < $returnhash{$key});
                   1328:                 }
                   1329:                 $returnhash{$key}=$value;
                   1330:             }
                   1331:         }
                   1332:     }
                   1333:     return %returnhash;
                   1334: }
                   1335: 
1.202     matthew  1336: # --------------------------------------------- Try to change a user's password
                   1337: 
                   1338: sub changepass {
1.799     raeburn  1339:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1340:     $currentpass = &escape($currentpass);
                   1341:     $newpass     = &escape($newpass);
1.1030    raeburn  1342:     my $lonhost = $perlvar{'lonHostID'};
                   1343:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1344: 		       $server);
                   1345:     if (! $answer) {
                   1346: 	&logthis("No reply on password change request to $server ".
                   1347: 		 "by $uname in domain $udom.");
                   1348:     } elsif ($answer =~ "^ok") {
                   1349:         &logthis("$uname in $udom successfully changed their password ".
                   1350: 		 "on $server.");
                   1351:     } elsif ($answer =~ "^pwchange_failure") {
                   1352: 	&logthis("$uname in $udom was unable to change their password ".
                   1353: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1354: 		 "or pwchange");
                   1355:     } elsif ($answer =~ "^non_authorized") {
                   1356:         &logthis("$uname in $udom did not get their password correct when ".
                   1357: 		 "attempting to change it on $server.");
                   1358:     } elsif ($answer =~ "^auth_mode_error") {
                   1359:         &logthis("$uname in $udom attempted to change their password despite ".
                   1360: 		 "not being locally or internally authenticated on $server.");
                   1361:     } elsif ($answer =~ "^unknown_user") {
                   1362:         &logthis("$uname in $udom attempted to change their password ".
                   1363: 		 "on $server but were unable to because $server is not ".
                   1364: 		 "their home server.");
                   1365:     } elsif ($answer =~ "^refused") {
                   1366: 	&logthis("$server refused to change $uname in $udom password because ".
                   1367: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1368:     } elsif ($answer =~ "invalid_client") {
                   1369:         &logthis("$server refused to change $uname in $udom password because ".
                   1370:                  "it was a reset by e-mail originating from an invalid server.");
1.1408    raeburn  1371:     } elsif ($answer =~ "^prioruse") {
                   1372:        &logthis("$server refused to change $uname in $udom password because ".
                   1373:                 "the password had been used before");
1.202     matthew  1374:     }
                   1375:     return $answer;
1.1       albertel 1376: }
                   1377: 
1.169     harris41 1378: # ----------------------- Try to determine user's current authentication scheme
                   1379: 
                   1380: sub queryauthenticate {
                   1381:     my ($uname,$udom)=@_;
1.456     albertel 1382:     my $uhome=&homeserver($uname,$udom);
1.1484    raeburn  1383:     if ((!$uhome) || ($uhome eq 'no_host')) {
1.456     albertel 1384: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1385: 	return 'no_host';
                   1386:     }
                   1387:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1388:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1389: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1390:     }
1.456     albertel 1391:     return $answer;
1.169     harris41 1392: }
                   1393: 
1.1       albertel 1394: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1395: 
1.1       albertel 1396: sub authenticate {
1.1073    raeburn  1397:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1398:     $upass=&escape($upass);
                   1399:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1400:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1401:     my $newhome;
1.836     www      1402:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1403: # Maybe the machine was offline and only re-appeared again recently?
                   1404:         &reconlonc();
                   1405: # One more
1.952     raeburn  1406: 	$uhome=&homeserver($uname,$udom,1);
                   1407:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1408:             if (defined(&domain($udom,'primary'))) {
                   1409:                 $newhome=&domain($udom,'primary');
                   1410:             }
                   1411:             if ($newhome ne '') {
                   1412:                 $uhome = $newhome;
                   1413:             }
                   1414:         }
1.836     www      1415: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1416: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1417: 	    return 'no_host';
                   1418:         }
1.1       albertel 1419:     }
1.1073    raeburn  1420:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1421:     if ($answer eq 'authorized') {
1.952     raeburn  1422:         if ($newhome) {
                   1423:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1424:             return 'no_account_on_host'; 
                   1425:         } else {
                   1426:             &logthis("User $uname at $udom authorized by $uhome");
                   1427:             return $uhome;
                   1428:         }
1.471     albertel 1429:     }
                   1430:     if ($answer eq 'non_authorized') {
                   1431: 	&logthis("User $uname at $udom rejected by $uhome");
1.1484    raeburn  1432: 	return 'no_host';
1.9       www      1433:     }
1.471     albertel 1434:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1435:     return 'no_host';
                   1436: }
                   1437: 
1.1491    raeburn  1438: sub can_switchserver {
                   1439:     my ($udom,$home) = @_;
                   1440:     my ($canswitch,@intdoms);
                   1441:     my $internet_names = &get_internet_names($home);
                   1442:     if (ref($internet_names) eq 'ARRAY') {
                   1443:         @intdoms = @{$internet_names};
                   1444:     }
                   1445:     my $uint_dom = &internet_dom(&domain($udom,'primary'));
                   1446:     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1447:         $canswitch = 1;
                   1448:     } else {
                   1449:          my $serverhomeID = &get_server_homeID(&hostname($home));
                   1450:          my $serverhomedom = &host_domain($serverhomeID);
                   1451:          my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1452:          my %udomdefaults = &get_domain_defaults($udom);
                   1453:          my $remoterev = &get_server_loncaparev('',$home);
                   1454:          $canswitch = &can_host_session($udom,$home,$remoterev,
                   1455:                                         $udomdefaults{'remotesessions'},
                   1456:                                         $defdomdefaults{'hostedsessions'});
                   1457:     }
                   1458:     return $canswitch;
                   1459: }
                   1460: 
1.1073    raeburn  1461: sub can_host_session {
1.1074    raeburn  1462:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1463:     my $canhost = 1;
1.1494    raeburn  1464:     my $host_idn = &internet_dom($lonhost);
1.1073    raeburn  1465:     if (ref($remotesessions) eq 'HASH') {
                   1466:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1467:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1468:                 $canhost = 0;
                   1469:             } else {
                   1470:                 $canhost = 1;
                   1471:             }
                   1472:         }
                   1473:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1474:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1475:                 $canhost = 1;
                   1476:             } else {
                   1477:                 $canhost = 0;
                   1478:             }
                   1479:         }
                   1480:         if ($canhost) {
                   1481:             if ($remotesessions->{'version'} ne '') {
                   1482:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1483:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1484:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1485:                         my $major = $1;
                   1486:                         my $minor = $2;
                   1487:                         if (($major < $reqmajor ) ||
                   1488:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1489:                             $canhost = 0;
                   1490:                         }
                   1491:                     } else {
                   1492:                         $canhost = 0;
                   1493:                     }
                   1494:                 }
                   1495:             }
                   1496:         }
                   1497:     }
                   1498:     if ($canhost) {
                   1499:         if (ref($hostedsessions) eq 'HASH') {
1.1494    raeburn  1500:             my $uprimary_id = &domain($udom,'primary');
                   1501:             my $uint_dom = &internet_dom($uprimary_id);
1.1073    raeburn  1502:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1503:                 if (($uint_dom ne '') && 
                   1504:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1505:                     $canhost = 0;
                   1506:                 } else {
                   1507:                     $canhost = 1;
                   1508:                 }
                   1509:             }
                   1510:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1511:                 if (($uint_dom ne '') && 
                   1512:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1513:                     $canhost = 1;
                   1514:                 } else {
                   1515:                     $canhost = 0;
                   1516:                 }
                   1517:             }
                   1518:         }
                   1519:     }
                   1520:     return $canhost;
                   1521: }
                   1522: 
1.1083    raeburn  1523: sub spare_can_host {
                   1524:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1525:     my $canhost=1;
1.1279    raeburn  1526:     my $try_server_hostname = &hostname($try_server);
                   1527:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1528:     my $serverhomedom = &host_domain($serverhomeID);
                   1529:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1530:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1531:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1532:             $canhost = 0;
                   1533:         }
                   1534:     }
1.1439    raeburn  1535:     if ($canhost) {
                   1536:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1537:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1538:                 unless (&shared_institution($udom,$try_server)) {
                   1539:                     $canhost = 0;
                   1540:                 }
                   1541:             }
                   1542:         }
                   1543:     }
1.1279    raeburn  1544:     if (($canhost) && ($uint_dom)) {
                   1545:         my @intdoms;
                   1546:         my $internet_names = &get_internet_names($try_server);
                   1547:         if (ref($internet_names) eq 'ARRAY') {
                   1548:             @intdoms = @{$internet_names};
                   1549:         }
                   1550:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1551:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1552:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1553:                                          $remotesessions,
                   1554:                                          $defdomdefaults{'hostedsessions'});
                   1555:         }
1.1083    raeburn  1556:     }
                   1557:     return $canhost;
                   1558: }
                   1559: 
1.1123    raeburn  1560: sub this_host_spares {
                   1561:     my ($dom) = @_;
1.1126    raeburn  1562:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1563:     my @hosts = &current_machine_ids();
                   1564:     foreach my $lonhost (@hosts) {
                   1565:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1566:             $dom_in_use = $dom;
                   1567:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1568:             last;
                   1569:         }
                   1570:     }
1.1126    raeburn  1571:     if ($dom_in_use ne '') {
                   1572:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1573:     }
                   1574:     if (ref($result) ne 'HASH') {
                   1575:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1576:         $dom_in_use = &host_domain($lonhost_in_use);
                   1577:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1578:         if (ref($result) ne 'HASH') {
                   1579:             $result = \%spareid;
                   1580:         }
                   1581:     }
                   1582:     return $result;
                   1583: }
                   1584: 
                   1585: sub spares_for_offload  {
                   1586:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1587:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1588:     if (defined($cached)) {
                   1589:         return $result;
                   1590:     } else {
1.1126    raeburn  1591:         my $cachetime = 60*60*24;
                   1592:         my %domconfig =
1.1494    raeburn  1593:             &get_dom('configuration',['usersessions'],$dom_in_use);
1.1126    raeburn  1594:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1595:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1596:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1597:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1598:                 }
                   1599:             }
                   1600:         }
                   1601:     }
1.1126    raeburn  1602:     return;
1.1123    raeburn  1603: }
                   1604: 
1.1129    raeburn  1605: sub get_lonbalancer_config {
                   1606:     my ($servers) = @_;
                   1607:     my ($currbalancer,$currtargets);
                   1608:     if (ref($servers) eq 'HASH') {
                   1609:         foreach my $server (keys(%{$servers})) {
                   1610:             my %what = (
                   1611:                          spareid => 1,
                   1612:                          perlvar => 1,
                   1613:                        );
                   1614:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1615:             if ($result eq 'ok') {
                   1616:                 if (ref($returnhash) eq 'HASH') {
                   1617:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1618:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1619:                             $currbalancer = $server;
                   1620:                             $currtargets = {};
                   1621:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1622:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1623:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1624:                                 }
                   1625:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1626:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1627:                                 }
                   1628:                             }
                   1629:                             last;
                   1630:                         }
                   1631:                     }
                   1632:                 }
                   1633:             }
                   1634:         }
                   1635:     }
                   1636:     return ($currbalancer,$currtargets);
                   1637: }
                   1638: 
                   1639: sub check_loadbalancing {
1.1331    raeburn  1640:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1641:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1642:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1643:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1644:     my @hosts = &current_machine_ids();
1.1494    raeburn  1645:     my $uprimary_id = &domain($udom,'primary');
                   1646:     my $uintdom = &internet_dom($uprimary_id);
                   1647:     my $intdom = &internet_dom($lonhost);
1.1129    raeburn  1648:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1649:     my $domneedscache;
1.1129    raeburn  1650:     my $cachetime = 60*60*24;
                   1651: 
                   1652:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1653:         $dom_in_use = $udom;
                   1654:         $homeintdom = 1;
                   1655:     } else {
                   1656:         $dom_in_use = $serverhomedom;
                   1657:     }
                   1658:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1659:     unless (defined($cached)) {
                   1660:         my %domconfig =
1.1494    raeburn  1661:             &get_dom('configuration',['loadbalancing'],$dom_in_use);
1.1129    raeburn  1662:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1663:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1664:         } else {
                   1665:             $domneedscache = $dom_in_use;
1.1129    raeburn  1666:         }
                   1667:     }
                   1668:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1669:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1670:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1671:         if ($is_balancer) {
                   1672:             if (ref($currrules) eq 'HASH') {
                   1673:                 if ($homeintdom) {
                   1674:                     if ($uname ne '') {
                   1675:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1676:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1677:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1678:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1679:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1680:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1681:                             }
                   1682:                         }
                   1683:                         if ($rule_in_effect eq '') {
                   1684:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1685:                             if ($userenv{'inststatus'} ne '') {
                   1686:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1687:                                 my ($othertitle,$usertypes,$types) =
                   1688:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1689:                                 if (ref($types) eq 'ARRAY') {
                   1690:                                     foreach my $type (@{$types}) {
                   1691:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1692:                                             if (exists($currrules->{$type})) {
                   1693:                                                 $rule_in_effect = $currrules->{$type};
                   1694:                                             }
                   1695:                                         }
                   1696:                                     }
                   1697:                                 }
                   1698:                             } else {
                   1699:                                 if (exists($currrules->{'default'})) {
                   1700:                                     $rule_in_effect = $currrules->{'default'};
                   1701:                                 }
                   1702:                             }
                   1703:                         }
                   1704:                     } else {
                   1705:                         if (exists($currrules->{'default'})) {
                   1706:                             $rule_in_effect = $currrules->{'default'};
                   1707:                         }
                   1708:                     }
                   1709:                 } else {
                   1710:                     if ($currrules->{'_LC_external'} ne '') {
                   1711:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1712:                     }
                   1713:                 }
                   1714:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1715:                                                        $uname,$udom);
                   1716:             }
                   1717:         }
                   1718:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1719:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1720:         unless (defined($cached)) {
                   1721:             my %domconfig =
1.1494    raeburn  1722:                 &get_dom('configuration',['loadbalancing'],$serverhomedom);
1.1129    raeburn  1723:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1724:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1725:             } else {
                   1726:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1727:             }
                   1728:         }
                   1729:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1730:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1731:                 &check_balancer_result($result,@hosts);
                   1732:             if ($is_balancer) {
1.1129    raeburn  1733:                 if (ref($currrules) eq 'HASH') {
                   1734:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1735:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1736:                     }
                   1737:                 }
                   1738:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1739:                                                        $uname,$udom);
                   1740:             }
                   1741:         } else {
                   1742:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1743:                 $is_balancer = 1;
                   1744:                 $offloadto = &this_host_spares($dom_in_use);
                   1745:             }
1.1307    raeburn  1746:             unless (defined($cached)) {
                   1747:                 $domneedscache = $serverhomedom;
                   1748:             }
1.1129    raeburn  1749:         }
                   1750:     } else {
                   1751:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1752:             $is_balancer = 1;
                   1753:             $offloadto = &this_host_spares($dom_in_use);
                   1754:         }
1.1307    raeburn  1755:         unless (defined($cached)) {
                   1756:             $domneedscache = $serverhomedom;
                   1757:         }
                   1758:     }
                   1759:     if ($domneedscache) {
                   1760:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1761:     }
1.1430    raeburn  1762:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176    raeburn  1763:         my $lowest_load = 30000;
                   1764:         if (ref($offloadto) eq 'HASH') {
                   1765:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1766:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1767:                     ($otherserver,$lowest_load) =
                   1768:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1769:                 }
1.1129    raeburn  1770:             }
1.1176    raeburn  1771:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1772: 
1.1176    raeburn  1773:             if (!$found_server) {
                   1774:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1775:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1776:                         ($otherserver,$lowest_load) =
                   1777:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1778:                     }
                   1779:                 }
                   1780:             }
                   1781:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1782:             if (@{$offloadto} == 1) {
                   1783:                 $otherserver = $offloadto->[0];
                   1784:             } elsif (@{$offloadto} > 1) {
                   1785:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1786:                     ($otherserver,$lowest_load) =
                   1787:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1788:                 }
                   1789:             }
                   1790:         }
1.1331    raeburn  1791:         unless ($caller eq 'login') {
                   1792:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1793:                 $is_balancer = 0;
                   1794:                 if ($uname ne '' && $udom ne '') {
                   1795:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1796:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1797:                                  'user.loadbalcheck.time' => time});
                   1798:                     }
1.1176    raeburn  1799:                 }
1.1129    raeburn  1800:             }
                   1801:         }
1.1430    raeburn  1802:     }
                   1803:     if (($is_balancer) && (!$homeintdom)) {
                   1804:         undef($setcookie);
1.1129    raeburn  1805:     }
1.1391    raeburn  1806:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1807: }
                   1808: 
1.1191    raeburn  1809: sub check_balancer_result {
                   1810:     my ($result,@hosts) = @_;
1.1391    raeburn  1811:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1812:     if (ref($result) eq 'HASH') {
                   1813:         if ($result->{'lonhost'} ne '') {
                   1814:             my $currbalancer = $result->{'lonhost'};
                   1815:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1816:                 $is_balancer = 1;
                   1817:                 $currtargets = $result->{'targets'};
                   1818:                 $currrules = $result->{'rules'};
                   1819:             }
1.1391    raeburn  1820:             $dom_balancers = $currbalancer;
1.1191    raeburn  1821:         } else {
1.1391    raeburn  1822:             if (keys(%{$result})) {
                   1823:                 foreach my $key (keys(%{$result})) {
                   1824:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1825:                         (ref($result->{$key}) eq 'HASH')) {
                   1826:                         $is_balancer = 1;
                   1827:                         $currrules = $result->{$key}{'rules'};
                   1828:                         $currtargets = $result->{$key}{'targets'};
                   1829:                         $setcookie = $result->{$key}{'cookie'};
                   1830:                         last;
                   1831:                     }
1.1191    raeburn  1832:                 }
1.1391    raeburn  1833:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1834:             }
                   1835:         }
                   1836:     }
1.1391    raeburn  1837:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1838: }
                   1839: 
1.1129    raeburn  1840: sub get_loadbalancer_targets {
                   1841:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1842:     my $offloadto;
1.1175    raeburn  1843:     if ($rule_in_effect eq 'none') {
                   1844:         return [$perlvar{'lonHostID'}];
                   1845:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1846:         $offloadto = $currtargets;
                   1847:     } else {
                   1848:         if ($rule_in_effect eq 'homeserver') {
                   1849:             my $homeserver = &homeserver($uname,$udom);
                   1850:             if ($homeserver ne 'no_host') {
                   1851:                 $offloadto = [$homeserver];
                   1852:             }
                   1853:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1854:             my %domconfig =
1.1494    raeburn  1855:                 &get_dom('configuration',['loadbalancing'],$udom);
1.1129    raeburn  1856:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1857:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1858:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1859:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1860:                     }
                   1861:                 }
                   1862:             } else {
1.1178    raeburn  1863:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1864:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1865:                 if (&hostname($remotebalancer) ne '') {
                   1866:                     $offloadto = [$remotebalancer];
                   1867:                 }
                   1868:             }
                   1869:         } elsif (&hostname($rule_in_effect) ne '') {
                   1870:             $offloadto = [$rule_in_effect];
                   1871:         }
                   1872:     }
                   1873:     return $offloadto;
                   1874: }
                   1875: 
1.1127    raeburn  1876: sub internet_dom_servers {
                   1877:     my ($dom) = @_;
                   1878:     my (%uniqservers,%servers);
                   1879:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1880:     my @machinedoms = &machine_domains($primaryserver);
                   1881:     foreach my $mdom (@machinedoms) {
                   1882:         my %currservers = %servers;
                   1883:         my %server = &get_servers($mdom);
                   1884:         %servers = (%currservers,%server);
                   1885:     }
                   1886:     my %by_hostname;
                   1887:     foreach my $id (keys(%servers)) {
                   1888:         push(@{$by_hostname{$servers{$id}}},$id);
                   1889:     }
                   1890:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1891:         if (@{$by_hostname{$hostname}} > 1) {
                   1892:             my $match = 0;
                   1893:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1894:                 if (&host_domain($id) eq $dom) {
                   1895:                     $uniqservers{$id} = $hostname;
                   1896:                     $match = 1;
                   1897:                 }
                   1898:             }
                   1899:             unless ($match) {
                   1900:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1901:             }
                   1902:         } else {
                   1903:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1904:         }
                   1905:     }
                   1906:     return %uniqservers;
                   1907: }
                   1908: 
1.1347    raeburn  1909: sub trusted_domains {
                   1910:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1911:     my ($trusted,$untrusted);
1.1347    raeburn  1912:     if (&domain($calldom) eq '') {
1.1349    raeburn  1913:         return ($trusted,$untrusted);
1.1347    raeburn  1914:     }
1.1395    raeburn  1915:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1916:         return ($trusted,$untrusted);
1.1347    raeburn  1917:     }
                   1918:     my $callprimary = &domain($calldom,'primary');
1.1494    raeburn  1919:     my $intcalldom = &internet_dom($callprimary);
1.1347    raeburn  1920:     if ($intcalldom eq '') {
1.1349    raeburn  1921:         return ($trusted,$untrusted);
1.1347    raeburn  1922:     }
                   1923: 
1.1494    raeburn  1924:     my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
1.1347    raeburn  1925:     unless (defined($cached)) {
1.1494    raeburn  1926:         my %domconfig = &get_dom('configuration',['trust'],$calldom);
                   1927:         &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1.1347    raeburn  1928:         $trustconfig = $domconfig{'trust'};
                   1929:     }
                   1930:     if (ref($trustconfig)) {
                   1931:         my (%possexc,%possinc,@allexc,@allinc); 
                   1932:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1933:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1934:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1935:             }
                   1936:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1937:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1938:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1939:             }
                   1940:         }
                   1941:         if (keys(%possexc)) {
                   1942:             if (keys(%possinc)) {
                   1943:                 foreach my $key (sort(keys(%possexc))) {
                   1944:                     next if ($key eq $intcalldom);
                   1945:                     unless ($possinc{$key}) {
                   1946:                         push(@allexc,$key);
                   1947:                     }
                   1948:                 }
                   1949:             } else {
                   1950:                 @allexc = sort(keys(%possexc));
                   1951:             }
                   1952:         }
                   1953:         if (keys(%possinc)) {
                   1954:             $possinc{$intcalldom} = 1;
                   1955:             @allinc = sort(keys(%possinc));
                   1956:         }
                   1957:         if ((@allexc > 0) || (@allinc > 0)) {
                   1958:             my %doms_by_intdom;
                   1959:             my %allintdoms = &all_host_intdom();
                   1960:             my %alldoms = &all_host_domain();
                   1961:             foreach my $key (%allintdoms) {
                   1962:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1963:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1964:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1965:                     }
                   1966:                 } else {
                   1967:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1968:                 }
                   1969:             }
                   1970:             foreach my $exc (@allexc) {
                   1971:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1972:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1973:                 }
                   1974:             }
                   1975:             foreach my $inc (@allinc) {
                   1976:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1977:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1978:                 }
                   1979:             }
                   1980:         }
                   1981:     }
1.1349    raeburn  1982:     return ($trusted,$untrusted);
1.1347    raeburn  1983: }
                   1984: 
                   1985: sub will_trust {
                   1986:     my ($cmdtype,$domain,$possdom) = @_;
                   1987:     return 1 if ($domain eq $possdom);
                   1988:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1989:     my $willtrust; 
                   1990:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1991:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1992:             $willtrust = 1;
                   1993:         }
                   1994:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1995:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1996:             $willtrust = 1;
                   1997:         }
                   1998:     } else {
                   1999:         $willtrust = 1;
                   2000:     }
                   2001:     return $willtrust;
                   2002: }
                   2003: 
1.1       albertel 2004: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      2005: 
1.599     albertel 2006: my %homecache;
1.1       albertel 2007: sub homeserver {
1.230     stredwic 2008:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 2009:     my $index="$uname:$udom";
1.426     albertel 2010: 
1.599     albertel 2011:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 2012: 
                   2013:     my %servers = &get_servers($udom,'library');
                   2014:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 2015:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 2016: 		 exists($badServerCache{$tryserver}));
1.841     albertel 2017: 
                   2018: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   2019: 	if ($answer eq 'found') {
                   2020: 	    delete($badServerCache{$tryserver}); 
                   2021: 	    return $homecache{$index}=$tryserver;
                   2022: 	} elsif ($answer eq 'no_host') {
                   2023: 	    $badServerCache{$tryserver}=1;
                   2024: 	}
1.1       albertel 2025:     }    
                   2026:     return 'no_host';
1.70      www      2027: }
                   2028: 
1.1300    raeburn  2029: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      2030: 
                   2031: sub idget {
1.1300    raeburn  2032:     my ($udom,$idsref,$namespace)=@_;
1.70      www      2033:     my %returnhash=();
1.1300    raeburn  2034:     my @ids=(); 
                   2035:     if (ref($idsref) eq 'ARRAY') {
                   2036:         @ids = @{$idsref};
                   2037:     } else {
                   2038:         return %returnhash; 
                   2039:     }
                   2040:     if ($namespace eq '') {
                   2041:         $namespace = 'ids';
                   2042:     }
1.70      www      2043:     
1.841     albertel 2044:     my %servers = &get_servers($udom,'library');
                   2045:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  2046: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  2047: 	if ($namespace eq 'ids') {
                   2048: 	    $idlist=~tr/A-Z/a-z/;
                   2049: 	}
                   2050: 	my $reply;
                   2051: 	if ($namespace eq 'ids') {
                   2052: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   2053: 	} else {
                   2054: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   2055: 	}
1.841     albertel 2056: 	my @answer=();
                   2057: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   2058: 	    @answer=split(/\&/,$reply);
                   2059: 	}                    ;
                   2060: 	my $i;
                   2061: 	for ($i=0;$i<=$#ids;$i++) {
                   2062: 	    if ($answer[$i]) {
1.1299    raeburn  2063: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  2064: 	    }
1.841     albertel 2065: 	}
1.1300    raeburn  2066:     }
1.70      www      2067:     return %returnhash;
                   2068: }
                   2069: 
                   2070: # ------------------------------------- Find the IDs behind a list of usernames
                   2071: 
                   2072: sub idrget {
                   2073:     my ($udom,@unames)=@_;
                   2074:     my %returnhash=();
1.800     albertel 2075:     foreach my $uname (@unames) {
                   2076:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 2077:     }
1.70      www      2078:     return %returnhash;
                   2079: }
                   2080: 
1.1300    raeburn  2081: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      2082: 
                   2083: sub idput {
1.1300    raeburn  2084:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      2085:     my %servers=();
1.1300    raeburn  2086:     my %ids=();
                   2087:     my %byid = ();
                   2088:     if (ref($idsref) eq 'HASH') {
                   2089:         %ids=%{$idsref};
                   2090:     }
                   2091:     if ($namespace eq '') {
                   2092:         $namespace = 'ids'; 
                   2093:     }
1.800     albertel 2094:     foreach my $uname (keys(%ids)) {
                   2095: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  2096:         if ($uhom eq '') {
                   2097:             $uhom=&homeserver($uname,$udom);
                   2098:         }
1.70      www      2099:         if ($uhom ne 'no_host') {
1.800     albertel 2100:             my $esc_unam=&escape($uname);
1.1300    raeburn  2101:             if ($namespace eq 'ids') {
                   2102:                 my $id=&escape($ids{$uname});
                   2103:                 $id=~tr/A-Z/a-z/;
                   2104:                 my $esc_unam=&escape($uname);
                   2105:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      2106:             } else {
1.1300    raeburn  2107:                 my @currids = split(/,/,$ids{$uname});
                   2108:                 foreach my $id (@currids) {
                   2109:                     $byid{$uhom}{$id} .= $uname.',';
                   2110:                 }
                   2111:             }
                   2112:         }
                   2113:     }
                   2114:     if ($namespace eq 'clickers') {
                   2115:         foreach my $server (keys(%byid)) {
                   2116:             if (ref($byid{$server}) eq 'HASH') {
                   2117:                 foreach my $id (keys(%{$byid{$server}})) {
                   2118:                     $byid{$server} =~ s/,$//;
                   2119:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   2120:                 }
1.70      www      2121:             }
                   2122:         }
1.191     harris41 2123:     }
1.800     albertel 2124:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2125:         $servers{$server} =~ s/\&$//;
                   2126:         if ($namespace eq 'ids') {     
                   2127:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   2128:         } else {
                   2129:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   2130:         }
1.191     harris41 2131:     }
1.344     www      2132: }
                   2133: 
1.1300    raeburn  2134: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  2135: 
                   2136: sub iddel {
1.1300    raeburn  2137:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  2138:     my %result=();
1.1300    raeburn  2139:     my %ids=();
                   2140:     my %byid = ();
                   2141:     if (ref($idshashref) eq 'HASH') {
                   2142:         %ids=%{$idshashref};
                   2143:     } else {
1.1231    raeburn  2144:         return %result;
                   2145:     }
1.1300    raeburn  2146:     if ($namespace eq '') {
                   2147:         $namespace = 'ids';
                   2148:     }
1.1231    raeburn  2149:     my %servers=();
1.1300    raeburn  2150:     while (my ($id,$unamestr) = each(%ids)) {
                   2151:         if ($namespace eq 'ids') {
                   2152:             my $uhom = $uhome;
                   2153:             if ($uhom eq '') { 
                   2154:                 $uhom=&homeserver($unamestr,$udom);
                   2155:             }
                   2156:             if ($uhom ne 'no_host') {
                   2157:                 $servers{$uhom}.='&'.&escape($id);
                   2158:             }
                   2159:          } else {
                   2160:             my @curritems = split(/,/,$ids{$id});
                   2161:             foreach my $uname (@curritems) {
                   2162:                 my $uhom = $uhome;
                   2163:                 if ($uhom eq '') {
                   2164:                     $uhom=&homeserver($uname,$udom);
                   2165:                 }
                   2166:                 if ($uhom ne 'no_host') { 
                   2167:                     $byid{$uhom}{$id} .= $uname.',';
                   2168:                 }
                   2169:             }
1.1231    raeburn  2170:         }
1.1300    raeburn  2171:     }
                   2172:     if ($namespace eq 'clickers') {
                   2173:         foreach my $server (keys(%byid)) {
                   2174:             if (ref($byid{$server}) eq 'HASH') {
                   2175:                 foreach my $id (keys(%{$byid{$server}})) {
                   2176:                     $byid{$server}{$id} =~ s/,$//;
                   2177:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2178:                 }
1.1231    raeburn  2179:             }
                   2180:         }
                   2181:     }
                   2182:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2183:         $servers{$server} =~ s/\&$//;
                   2184:         if ($namespace eq 'ids') {
                   2185:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2186:         } elsif ($namespace eq 'clickers') {
                   2187:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2188:         }
1.1231    raeburn  2189:     }
                   2190:     return %result;
                   2191: }
                   2192: 
1.1300    raeburn  2193: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2194: 
                   2195: sub updateclickers {
                   2196:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2197:     my %clickers;
                   2198:     if (ref($idshashref) eq 'HASH') {
                   2199:         %clickers=%{$idshashref};
                   2200:     } else {
                   2201:         return;
                   2202:     }
                   2203:     my $items='';
                   2204:     foreach my $item (keys(%clickers)) {
                   2205:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2206:     }
                   2207:     $items=~s/\&$//;
                   2208:     my $request = "updateclickers:$udom:$action:$items";
                   2209:     if ($critical) {
                   2210:         return &critical($request,$uhome);
                   2211:     } else {
                   2212:         return &reply($request,$uhome);
                   2213:     }
                   2214: }
                   2215: 
1.1023    raeburn  2216: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2217: sub dump_dom {
1.1165    droeschl 2218:     my ($namespace, $udom, $regexp) = @_;
                   2219: 
                   2220:     $udom ||= $env{'user.domain'};
                   2221: 
                   2222:     return () unless $udom;
                   2223: 
                   2224:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2225: }
                   2226: 
1.1023    raeburn  2227: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2228: 
                   2229: sub get_dom {
1.1462    raeburn  2230:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267    raeburn  2231:     return if ($udom eq 'public');
1.806     raeburn  2232:     my $items='';
                   2233:     foreach my $item (@$storearr) {
                   2234:         $items.=&escape($item).'&';
                   2235:     }
                   2236:     $items=~s/\&$//;
1.860     raeburn  2237:     if (!$udom) {
                   2238:         $udom=$env{'user.domain'};
1.1267    raeburn  2239:         return if ($udom eq 'public');
1.860     raeburn  2240:         if (defined(&domain($udom,'primary'))) {
                   2241:             $uhome=&domain($udom,'primary');
                   2242:         } else {
1.874     albertel 2243:             undef($uhome);
1.860     raeburn  2244:         }
                   2245:     } else {
                   2246:         if (!$uhome) {
                   2247:             if (defined(&domain($udom,'primary'))) {
                   2248:                 $uhome=&domain($udom,'primary');
                   2249:             }
                   2250:         }
                   2251:     }
                   2252:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2253:         my $rep;
1.1442    raeburn  2254:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2255:             # domain information is hosted on this machine
1.1462    raeburn  2256:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344    raeburn  2257:         } else {
1.1462    raeburn  2258:             if ($encrypt) {
1.1442    raeburn  2259:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2260:             } else {
                   2261:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2262:             }
1.1344    raeburn  2263:         }
1.866     raeburn  2264:         my %returnhash;
1.875     albertel 2265:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2266:             return %returnhash;
                   2267:         }
1.806     raeburn  2268:         my @pairs=split(/\&/,$rep);
                   2269:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2270:             return @pairs;
                   2271:         }
                   2272:         my $i=0;
                   2273:         foreach my $item (@$storearr) {
                   2274:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2275:             $i++;
                   2276:         }
                   2277:         return %returnhash;
                   2278:     } else {
1.880     banghart 2279:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2280:     }
                   2281: }
                   2282: 
                   2283: # -------------------------------------------- put items in domain db files 
                   2284: 
                   2285: sub put_dom {
1.1462    raeburn  2286:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  2287:     if (!$udom) {
                   2288:         $udom=$env{'user.domain'};
                   2289:         if (defined(&domain($udom,'primary'))) {
                   2290:             $uhome=&domain($udom,'primary');
                   2291:         } else {
1.874     albertel 2292:             undef($uhome);
1.860     raeburn  2293:         }
                   2294:     } else {
                   2295:         if (!$uhome) {
                   2296:             if (defined(&domain($udom,'primary'))) {
                   2297:                 $uhome=&domain($udom,'primary');
                   2298:             }
                   2299:         }
                   2300:     } 
                   2301:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2302:         my $items='';
                   2303:         foreach my $item (keys(%$storehash)) {
                   2304:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2305:         }
                   2306:         $items=~s/\&$//;
1.1462    raeburn  2307:         if ($encrypt) {
1.1344    raeburn  2308:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2309:         } else {
                   2310:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2311:         }
1.806     raeburn  2312:     } else {
1.860     raeburn  2313:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2314:     }
                   2315: }
                   2316: 
1.1023    raeburn  2317: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2318: sub newput_dom {
1.1023    raeburn  2319:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2320:     my $result;
                   2321:     if (!$udom) {
                   2322:         $udom=$env{'user.domain'};
                   2323:     }
1.1023    raeburn  2324:     if ($udom) {
                   2325:         my $uname = &get_domainconfiguser($udom);
                   2326:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2327:     }
                   2328:     return $result;
                   2329: }
                   2330: 
1.1023    raeburn  2331: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2332: sub del_dom {
1.1023    raeburn  2333:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2334:     if (ref($storearr) eq 'ARRAY') {
                   2335:         if (!$udom) {
                   2336:             $udom=$env{'user.domain'};
                   2337:         }
1.1023    raeburn  2338:         if ($udom) {
                   2339:             my $uname = &get_domainconfiguser($udom); 
                   2340:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2341:         }
                   2342:     }
                   2343: }
                   2344: 
1.1481    raeburn  2345: sub store_dom {
1.1482    raeburn  2346:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481    raeburn  2347:     $$storehash{'ip'}=&get_requestor_ip();
                   2348:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2349:     my $namevalue='';
                   2350:     foreach my $key (keys(%{$storehash})) {
                   2351:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2352:     }
                   2353:     $namevalue=~s/\&$//;
                   2354:     if (grep { $_ eq $home } current_machine_ids()) {
                   2355:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2356:     } else {
                   2357:         if ($namespace eq 'private') {
                   2358:             return 'refused';
1.1482    raeburn  2359:         } elsif ($encrypt) {
                   2360:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481    raeburn  2361:         } else {
1.1482    raeburn  2362:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481    raeburn  2363:         }
                   2364:     }
                   2365: }
                   2366: 
1.1482    raeburn  2367: sub restore_dom {
                   2368:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2369:     my $answer;
                   2370:     if (grep { $_ eq $home } current_machine_ids()) {
                   2371:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2372:     } elsif ($namespace ne 'private') {
                   2373:         if ($encrypt) {
                   2374:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2375:         } else {
                   2376:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2377:         }
                   2378:     }
                   2379:     my %returnhash=();
                   2380:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
                   2381:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2382:         foreach my $line (split(/\&/,$answer)) {
                   2383:             my ($name,$value)=split(/\=/,$line);
                   2384:             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2385:         }
                   2386:         my $version;
                   2387:         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2388:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2389:                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2390:             }
                   2391:         }
                   2392:     }
                   2393:     return %returnhash;
                   2394: }
                   2395: 
1.1023    raeburn  2396: # ----------------------------------construct domainconfig user for a domain 
                   2397: sub get_domainconfiguser {
                   2398:     my ($udom) = @_;
                   2399:     return $udom.'-domainconfig';
                   2400: }
                   2401: 
1.837     raeburn  2402: sub retrieve_inst_usertypes {
                   2403:     my ($udom) = @_;
                   2404:     my (%returnhash,@order);
1.1494    raeburn  2405:     my %domdefs = &get_domain_defaults($udom);
1.989     raeburn  2406:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2407:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2408:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2409:     } else {
                   2410:         if (defined(&domain($udom,'primary'))) {
                   2411:             my $uhome=&domain($udom,'primary');
                   2412:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2413:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2414:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2415:                 return (\%returnhash,\@order);
                   2416:             }
                   2417:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2418:             my @pairs=split(/\&/,$hashitems);
                   2419:             foreach my $item (@pairs) {
                   2420:                 my ($key,$value)=split(/=/,$item,2);
                   2421:                 $key = &unescape($key);
                   2422:                 next if ($key =~ /^error: 2 /);
                   2423:                 $returnhash{$key}=&thaw_unescape($value);
                   2424:             }
                   2425:             my @esc_order = split(/\&/,$orderitems);
                   2426:             foreach my $item (@esc_order) {
                   2427:                 push(@order,&unescape($item));
                   2428:             }
                   2429:         } else {
1.1256    raeburn  2430:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2431:         }
1.1256    raeburn  2432:         return (\%returnhash,\@order);
1.837     raeburn  2433:     }
                   2434: }
                   2435: 
1.868     raeburn  2436: sub is_domainimage {
                   2437:     my ($url) = @_;
1.1468    raeburn  2438:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2439:         if (&domain($1) ne '') {
                   2440:             return '1';
                   2441:         }
                   2442:     }
                   2443:     return;
                   2444: }
                   2445: 
1.899     raeburn  2446: sub inst_directory_query {
                   2447:     my ($srch) = @_;
                   2448:     my $udom = $srch->{'srchdomain'};
                   2449:     my %results;
                   2450:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2451:     my $outcome;
1.899     raeburn  2452:     if ($homeserver ne '') {
1.1357    raeburn  2453:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2454:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2455:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2456:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2457:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2458:                     (($major == 2) && ($minor < 12))) {
                   2459:                     return;
                   2460:                 }
                   2461:             }
                   2462:         }
1.904     albertel 2463: 	my $queryid=&reply("querysend:instdirsearch:".
                   2464: 			   &escape($srch->{'srchby'}).':'.
                   2465: 			   &escape($srch->{'srchterm'}).':'.
                   2466: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2467: 	my $host=&hostname($homeserver);
                   2468: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2469: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2470: 	    return;
                   2471: 	}
                   2472: 	my $response = &get_query_reply($queryid);
                   2473: 	my $maxtries = 5;
                   2474: 	my $tries = 1;
                   2475: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2476: 	    $response = &get_query_reply($queryid);
                   2477: 	    $tries ++;
                   2478: 	}
                   2479: 
                   2480:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2481:             if ($response eq 'unavailable') {
                   2482:                 $outcome = $response;
                   2483:             } else {
                   2484:                 $outcome = 'ok';
                   2485:                 my @matches = split(/\n/,$response);
                   2486:                 foreach my $match (@matches) {
                   2487:                     my ($key,$value) = split(/=/,$match);
                   2488:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2489:                 }
1.899     raeburn  2490:             }
                   2491:         }
                   2492:     }
1.909     raeburn  2493:     return ($outcome,%results);
1.899     raeburn  2494: }
                   2495: 
                   2496: sub usersearch {
                   2497:     my ($srch) = @_;
                   2498:     my $dom = $srch->{'srchdomain'};
                   2499:     my %results;
                   2500:     my %libserv = &all_library();
                   2501:     my $query = 'usersearch';
                   2502:     foreach my $tryserver (keys(%libserv)) {
                   2503:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2504:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2505:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2506:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2507:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2508:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2509:                              (($major == 2) && ($minor < 12)));
                   2510:                 }
                   2511:             }
1.899     raeburn  2512:             my $host=&hostname($tryserver);
                   2513:             my $queryid=
1.911     raeburn  2514:                 &reply("querysend:".&escape($query).':'.
                   2515:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2516:                        &escape($srch->{'srchtype'}).':'.
                   2517:                        &escape($srch->{'srchterm'}),$tryserver);
                   2518:             if ($queryid !~/^\Q$host\E\_/) {
                   2519:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2520:                 next;
1.899     raeburn  2521:             }
                   2522:             my $reply = &get_query_reply($queryid);
                   2523:             my $maxtries = 1;
                   2524:             my $tries = 1;
                   2525:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2526:                 $reply = &get_query_reply($queryid);
                   2527:                 $tries ++;
                   2528:             }
                   2529:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2530:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2531:             } else {
1.911     raeburn  2532:                 my @matches;
                   2533:                 if ($reply =~ /\n/) {
                   2534:                     @matches = split(/\n/,$reply);
                   2535:                 } else {
                   2536:                     @matches = split(/\&/,$reply);
                   2537:                 }
1.899     raeburn  2538:                 foreach my $match (@matches) {
                   2539:                     my ($uname,$udom,%userhash);
1.911     raeburn  2540:                     foreach my $entry (split(/:/,$match)) {
                   2541:                         my ($key,$value) =
                   2542:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2543:                         $userhash{$key} = $value;
                   2544:                         if ($key eq 'username') {
                   2545:                             $uname = $value;
                   2546:                         } elsif ($key eq 'domain') {
                   2547:                             $udom = $value;
1.911     raeburn  2548:                         }
1.899     raeburn  2549:                     }
                   2550:                     $results{$uname.':'.$udom} = \%userhash;
                   2551:                 }
                   2552:             }
                   2553:         }
                   2554:     }
                   2555:     return %results;
                   2556: }
                   2557: 
1.912     raeburn  2558: sub get_instuser {
                   2559:     my ($udom,$uname,$id) = @_;
                   2560:     my $homeserver = &domain($udom,'primary');
                   2561:     my ($outcome,%results);
                   2562:     if ($homeserver ne '') {
                   2563:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2564:                            &escape($id).':'.&escape($udom),$homeserver);
                   2565:         my $host=&hostname($homeserver);
                   2566:         if ($queryid !~/^\Q$host\E\_/) {
                   2567:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2568:             return;
                   2569:         }
                   2570:         my $response = &get_query_reply($queryid);
                   2571:         my $maxtries = 5;
                   2572:         my $tries = 1;
                   2573:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2574:             $response = &get_query_reply($queryid);
                   2575:             $tries ++;
                   2576:         }
                   2577:         if (!&error($response) && $response ne 'refused') {
                   2578:             if ($response eq 'unavailable') {
                   2579:                 $outcome = $response;
                   2580:             } else {
                   2581:                 $outcome = 'ok';
                   2582:                 my @matches = split(/\n/,$response);
                   2583:                 foreach my $match (@matches) {
                   2584:                     my ($key,$value) = split(/=/,$match);
                   2585:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2586:                 }
                   2587:             }
                   2588:         }
                   2589:     }
                   2590:     my %userinfo;
                   2591:     if (ref($results{$uname}) eq 'HASH') {
                   2592:         %userinfo = %{$results{$uname}};
                   2593:     } 
                   2594:     return ($outcome,%userinfo);
                   2595: }
                   2596: 
1.1290    raeburn  2597: sub get_multiple_instusers {
                   2598:     my ($udom,$users,$caller) = @_;
                   2599:     my ($outcome,$results);
                   2600:     if (ref($users) eq 'HASH') {
                   2601:         my $count = keys(%{$users}); 
                   2602:         my $requested = &freeze_escape($users);
                   2603:         my $homeserver = &domain($udom,'primary');
                   2604:         if ($homeserver ne '') {
                   2605:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2606:             my $host=&hostname($homeserver);
                   2607:             if ($queryid !~/^\Q$host\E\_/) {
                   2608:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2609:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2610:                 return ($outcome,$results);
                   2611:             }
                   2612:             my $response = &get_query_reply($queryid);
                   2613:             my $maxtries = 5;
                   2614:             if ($count > 100) {
                   2615:                 $maxtries = 1+int($count/20);
                   2616:             }
                   2617:             my $tries = 1;
                   2618:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2619:                 $response = &get_query_reply($queryid);
                   2620:                 $tries ++;
                   2621:             }
                   2622:             if ($response eq '') {
                   2623:                 $results = {};
                   2624:                 foreach my $key (keys(%{$users})) {
                   2625:                     my ($uname,$id);
                   2626:                     if ($caller eq 'id') {
                   2627:                         $id = $key;
                   2628:                     } else {
                   2629:                         $uname = $key;
                   2630:                     }
                   2631:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2632:                     $outcome = $resp;
1.1290    raeburn  2633:                     if ($resp eq 'ok') {
                   2634:                         %{$results} = (%{$results}, %info);
                   2635:                     } else {
                   2636:                         last;
                   2637:                     }
                   2638:                 }
                   2639:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2640:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2641:                     $outcome = $response;
                   2642:                 } else {
1.1291    raeburn  2643:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2644:                     if ($outcome eq 'ok') {
                   2645:                         $results = &thaw_unescape($userdata); 
                   2646:                     }
                   2647:                 }
                   2648:             }
                   2649:         }
                   2650:     }
                   2651:     return ($outcome,$results);
                   2652: }
                   2653: 
1.912     raeburn  2654: sub inst_rulecheck {
1.923     raeburn  2655:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2656:     my %returnhash;
                   2657:     if ($udom ne '') {
                   2658:         if (ref($rules) eq 'ARRAY') {
                   2659:             @{$rules} = map {&escape($_);} (@{$rules});
                   2660:             my $rulestr = join(':',@{$rules});
                   2661:             my $homeserver=&domain($udom,'primary');
                   2662:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2663:                 my $response;
                   2664:                 if ($item eq 'username') {                
                   2665:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2666:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2667:                                               $homeserver));
1.923     raeburn  2668:                 } elsif ($item eq 'id') {
                   2669:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2670:                                               ':'.&escape($id).':'.$rulestr,
                   2671:                                               $homeserver));
1.945     raeburn  2672:                 } elsif ($item eq 'selfcreate') {
                   2673:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2674:                                                &escape($udom).':'.&escape($uname).
                   2675:                                               ':'.$rulestr,$homeserver));
1.1484    raeburn  2676:                 } elsif ($item eq 'unamemap') {
                   2677:                     $response=&unescape(&reply('instunamemapcheck:'.
                   2678:                                                &escape($udom).':'.&escape($uname).
                   2679:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2680:                 }
1.912     raeburn  2681:                 if ($response ne 'refused') {
                   2682:                     my @pairs=split(/\&/,$response);
                   2683:                     foreach my $item (@pairs) {
                   2684:                         my ($key,$value)=split(/=/,$item,2);
                   2685:                         $key = &unescape($key);
                   2686:                         next if ($key =~ /^error: 2 /);
                   2687:                         $returnhash{$key}=&thaw_unescape($value);
                   2688:                     }
                   2689:                 }
                   2690:             }
                   2691:         }
                   2692:     }
                   2693:     return %returnhash;
                   2694: }
                   2695: 
                   2696: sub inst_userrules {
1.923     raeburn  2697:     my ($udom,$check) = @_;
1.912     raeburn  2698:     my (%ruleshash,@ruleorder);
                   2699:     if ($udom ne '') {
                   2700:         my $homeserver=&domain($udom,'primary');
                   2701:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2702:             my $response;
                   2703:             if ($check eq 'id') {
                   2704:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2705:                                  $homeserver);
1.943     raeburn  2706:             } elsif ($check eq 'email') {
                   2707:                 $response=&reply('instemailrules:'.&escape($udom),
                   2708:                                  $homeserver);
1.1484    raeburn  2709:             } elsif ($check eq 'unamemap') {
                   2710:                 $response=&reply('unamemaprules:'.&escape($udom),
                   2711:                                  $homeserver); 
1.923     raeburn  2712:             } else {
                   2713:                 $response=&reply('instuserrules:'.&escape($udom),
                   2714:                                  $homeserver);
                   2715:             }
1.912     raeburn  2716:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2717:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2718:                 ($response ne 'no_such_host')) {
                   2719:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2720:                 my @pairs=split(/\&/,$hashitems);
                   2721:                 foreach my $item (@pairs) {
                   2722:                     my ($key,$value)=split(/=/,$item,2);
                   2723:                     $key = &unescape($key);
                   2724:                     next if ($key =~ /^error: 2 /);
                   2725:                     $ruleshash{$key}=&thaw_unescape($value);
                   2726:                 }
                   2727:                 my @esc_order = split(/\&/,$orderitems);
                   2728:                 foreach my $item (@esc_order) {
                   2729:                     push(@ruleorder,&unescape($item));
                   2730:                 }
                   2731:             }
                   2732:         }
                   2733:     }
                   2734:     return (\%ruleshash,\@ruleorder);
                   2735: }
                   2736: 
1.976     raeburn  2737: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2738: 
                   2739: sub get_domain_defaults {
1.1240    raeburn  2740:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2741:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2742:     my $cachetime = 60*60*24;
1.1240    raeburn  2743:     unless ($ignore_cache) {
                   2744:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2745:         if (defined($cached)) {
                   2746:             if (ref($result) eq 'HASH') {
                   2747:                 return %{$result};
                   2748:             }
1.943     raeburn  2749:         }
                   2750:     }
                   2751:     my %domdefaults;
                   2752:     my %domconfig =
1.1494    raeburn  2753:          &get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2754:                                   'requestcourses','inststatus',
1.1183    raeburn  2755:                                   'coursedefaults','usersessions',
1.1517    raeburn  2756:                                   'requestauthor','authordefaults',
                   2757:                                   'selfenrollment','coursecategories',
                   2758:                                   'ssl','autoenroll','trust',
                   2759:                                   'helpsettings','wafproxy',
1.1520    raeburn  2760:                                   'ltisec','toolsec','privacy'],$domain);
1.1305    raeburn  2761:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2762:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2763:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2764:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2765:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2766:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2767:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2768:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1492    raeburn  2769:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
                   2770:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1340    raeburn  2771:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2772:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2773:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484    raeburn  2774:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2775:     } else {
                   2776:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2777:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2778:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2779:     }
1.976     raeburn  2780:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2781:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2782:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2783:         } else {
                   2784:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2785:         }
1.1521    raeburn  2786:         my @usertools = ('aboutme','blog','webdav','portfolio','portaccess');
1.976     raeburn  2787:         foreach my $item (@usertools) {
                   2788:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2789:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2790:             }
                   2791:         }
1.1229    raeburn  2792:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2793:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2794:         }
1.976     raeburn  2795:     }
1.985     raeburn  2796:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2797:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2798:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2799:         }
                   2800:     }
1.1183    raeburn  2801:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2802:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2803:     }
1.1517    raeburn  2804:     if (ref($domconfig{'authordefaults'}) eq 'HASH') {
1.1527  ! raeburn  2805:         foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors','archive') {
1.1517    raeburn  2806:             if ($item eq 'editors') {
                   2807:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
                   2808:                     $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
                   2809:                 }
                   2810:             } else {
                   2811:                 $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
                   2812:             }
                   2813:         }
                   2814:     }
1.989     raeburn  2815:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2816:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2817:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2818:         }
                   2819:     }
1.1047    raeburn  2820:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2821:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2822:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476    raeburn  2823:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277    raeburn  2824:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2825:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2826:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2827:         }
1.1254    raeburn  2828:         foreach my $type (@coursetypes) {
                   2829:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2830:                 unless ($type eq 'community') {
                   2831:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2832:                 }
                   2833:             }
                   2834:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2835:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2836:             }
1.1514    raeburn  2837:             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
                   2838:                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
                   2839:             }
1.1277    raeburn  2840:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2841:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2842:                     $domdefaults{$type.'postsubtimeout'} = 
                   2843:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2844:                 }
                   2845:             }
1.1508    raeburn  2846:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
                   2847:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
                   2848:             } else {
                   2849:                 $domdefaults{$type.'domexttool'} = 1;
                   2850:             }
                   2851:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
                   2852:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
                   2853:             } else {
                   2854:                 $domdefaults{$type.'exttool'} = 0;
                   2855:             }
1.1520    raeburn  2856:             if (ref($domconfig{'coursedefaults'}{'crsauthor'}) eq 'HASH') {
                   2857:                 $domdefaults{$type.'crsauthor'} = $domconfig{'coursedefaults'}{'crsauthor'}{$type};
                   2858:             } else {
                   2859:                 $domdefaults{$type.'crsauthor'} = 1;
                   2860:             }
1.1525    raeburn  2861:             if (ref($domconfig{'coursedefaults'}{'crseditors'}) eq 'ARRAY') {
                   2862:                 $domdefaults{'crseditors'}=join(',',@{$domconfig{'coursedefaults'}{'crseditors'}});
                   2863:             }
1.1230    raeburn  2864:         }
1.1286    raeburn  2865:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2866:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2867:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2868:                 if (@clonecodes) {
                   2869:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2870:                 }
                   2871:             }
                   2872:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2873:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2874:         }
1.1356    raeburn  2875:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2876:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480    raeburn  2877:         }
                   2878:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2879:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2880:         }
1.1047    raeburn  2881:     }
1.1073    raeburn  2882:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2883:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2884:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2885:         }
                   2886:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2887:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2888:         }
1.1279    raeburn  2889:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2890:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2891:         }
1.1440    raeburn  2892:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439    raeburn  2893:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2894:         }
1.1073    raeburn  2895:     }
1.1254    raeburn  2896:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2897:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2898:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2899:                             'approval','limit');
                   2900:             foreach my $type (@coursetypes) {
                   2901:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2902:                     my @mgrdc = ();
                   2903:                     foreach my $item (@settings) {
                   2904:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2905:                             push(@mgrdc,$item);
                   2906:                         }
                   2907:                     }
                   2908:                     if (@mgrdc) {
                   2909:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2910:                     }
                   2911:                 }
                   2912:             }
                   2913:         }
                   2914:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2915:             foreach my $type (@coursetypes) {
                   2916:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2917:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2918:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2919:                     }
                   2920:                 }
                   2921:             }
                   2922:         }
                   2923:     }
1.1258    raeburn  2924:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2925:         $domdefaults{'catauth'} = 'std';
                   2926:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2927:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2928:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2929:         }
                   2930:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2931:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2932:         }
                   2933:     }
1.1315    raeburn  2934:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2935:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2936:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2937:         }
1.1338    raeburn  2938:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2939:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2940:         }
                   2941:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2942:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2943:         }
                   2944:     }
1.1320    raeburn  2945:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2946:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2947:         foreach my $prefix (@prefixes) {
                   2948:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2949:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2950:             }
                   2951:         }
                   2952:     }
1.1314    raeburn  2953:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2954:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477    raeburn  2955:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314    raeburn  2956:     }
1.1332    raeburn  2957:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2958:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2959:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2960:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2961:         }
                   2962:     }
1.1434    raeburn  2963:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449    raeburn  2964:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434    raeburn  2965:             if ($domconfig{'wafproxy'}{$item}) {
                   2966:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2967:             }
                   2968:         }
1.1482    raeburn  2969:     }
                   2970:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2971:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2972:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2973:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2974:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2975:         }
                   2976:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2977:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
1.1504    raeburn  2978:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2979:             }
                   2980:         }
1.1523    raeburn  2981:         if (ref($domconfig{'ltisec'}{'suggested'}) eq 'HASH') {
                   2982:             my %suggestions = %{$domconfig{'ltisec'}{'suggested'}};
                   2983:             foreach my $item (keys(%{$domconfig{'ltisec'}{'suggested'}})) {
                   2984:                 unless (ref($domconfig{'ltisec'}{'suggested'}{$item}) eq 'HASH') {
                   2985:                     delete($suggestions{$item});
                   2986:                 }
                   2987:             }
                   2988:             if (keys(%suggestions)) {
                   2989:                 $domdefaults{'linkprotsuggested'} = \%suggestions;
                   2990:             }
                   2991:         }
1.1504    raeburn  2992:     }
                   2993:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   2994:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
                   2995:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
                   2996:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
                   2997:         }
                   2998:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
                   2999:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
                   3000:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
1.1482    raeburn  3001:             }
                   3002:         }
                   3003:     }
1.1512    raeburn  3004:     if (ref($domconfig{'privacy'}) eq 'HASH') {
                   3005:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
                   3006:             foreach my $domtype ('instdom','extdom') {
                   3007:                 if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
                   3008:                     foreach my $roletype ('domain','author','course','community') {
                   3009:                         if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
                   3010:                             $domdefaults{'userapprovals'} = 1;
                   3011:                             last;
                   3012:                         }
                   3013:                     }
                   3014:                 }
                   3015:                 last if ($domdefaults{'userapprovals'});
                   3016:             }
                   3017:         }
                   3018:     }
1.1219    raeburn  3019:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  3020:     return %domdefaults;
                   3021: }
                   3022: 
1.1412    raeburn  3023: sub get_dom_cats {
                   3024:     my ($dom) = @_;
                   3025:     return unless (&domain($dom));
                   3026:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   3027:     unless (defined($cached)) {
                   3028:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   3029:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   3030:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   3031:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   3032:             } else {
                   3033:                 $cats = {};
                   3034:             }
                   3035:         } else {
                   3036:             $cats = {};
                   3037:         }
1.1494    raeburn  3038:         &do_cache_new('cats',$dom,$cats,3600);
1.1412    raeburn  3039:     }
1.1413    raeburn  3040:     return $cats;
                   3041: }
                   3042: 
                   3043: sub get_dom_instcats {
                   3044:     my ($dom) = @_;
                   3045:     return unless (&domain($dom));
                   3046:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   3047:     unless (defined($cached)) {
                   3048:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   3049:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   3050:         if ($totcodes > 0) {
                   3051:             my $caller = 'global';
                   3052:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   3053:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   3054:                 $instcats = {
1.1503    raeburn  3055:                                 totcodes => $totcodes,
1.1413    raeburn  3056:                                 codes => \%codes,
                   3057:                                 codetitles => \@codetitles,
                   3058:                                 cat_titles => \%cat_titles,
                   3059:                                 cat_order => \%cat_order,
                   3060:                             };
                   3061:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   3062:             }
                   3063:         }
                   3064:     }
                   3065:     return $instcats;
                   3066: }
                   3067: 
                   3068: sub retrieve_instcodes {
                   3069:     my ($coursecodes,$dom) = @_;
                   3070:     my $totcodes;
                   3071:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   3072:     foreach my $course (keys(%courses)) {
                   3073:         if (ref($courses{$course}) eq 'HASH') {
                   3074:             if ($courses{$course}{'inst_code'} ne '') {
                   3075:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   3076:                 $totcodes ++;
                   3077:             }
                   3078:         }
                   3079:     }
                   3080:     return $totcodes;
1.1412    raeburn  3081: }
                   3082: 
1.1311    raeburn  3083: sub course_portal_url {
1.1451    raeburn  3084:     my ($cnum,$cdom,$r) = @_;
1.1311    raeburn  3085:     my $chome = &homeserver($cnum,$cdom);
                   3086:     my $hostname = &hostname($chome);
                   3087:     my $protocol = $protocol{$chome};
                   3088:     $protocol = 'http' if ($protocol ne 'https');
                   3089:     my %domdefaults = &get_domain_defaults($cdom);
                   3090:     my $firsturl;
                   3091:     if ($domdefaults{'portal_def'}) {
                   3092:         $firsturl = $domdefaults{'portal_def'};
                   3093:     } else {
1.1494    raeburn  3094:         my $alias = &use_proxy_alias($r,$chome);
1.1451    raeburn  3095:         $hostname = $alias if ($alias ne '');
1.1311    raeburn  3096:         $firsturl = $protocol.'://'.$hostname;
                   3097:     }
                   3098:     return $firsturl;
                   3099: }
                   3100: 
1.1492    raeburn  3101: sub url_prefix {
                   3102:     my ($r,$dom,$home,$context) = @_;
                   3103:     my $prefix;
                   3104:     my %domdefs = &get_domain_defaults($dom);
                   3105:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
                   3106:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
                   3107:             $prefix = $1;
                   3108:         }
                   3109:     }
                   3110:     if ($prefix eq '') {
                   3111:         my $hostname = &hostname($home);
                   3112:         my $protocol = $protocol{$home};
                   3113:         $protocol = 'http' if ($protocol{$home} ne 'https');
                   3114:         my $alias = &use_proxy_alias($r,$home);
                   3115:         $hostname = $alias if ($alias ne '');
                   3116:         $prefix = $protocol.'://'.$hostname;
                   3117:     }
                   3118:     return $prefix;
                   3119: }
                   3120: 
1.1407    raeburn  3121: # --------------------------------------------- Get domain config for passwords
                   3122: 
                   3123: sub get_passwdconf {
                   3124:     my ($dom) = @_;
                   3125:     my (%passwdconf,$gotconf,$lookup);
                   3126:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   3127:     if (defined($cached)) {
                   3128:         if (ref($result) eq 'HASH') {
                   3129:             %passwdconf = %{$result};
                   3130:             $gotconf = 1;
                   3131:         }
                   3132:     }
                   3133:     unless ($gotconf) {
                   3134:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   3135:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   3136:             %passwdconf = %{$domconfig{'passwords'}};
                   3137:         }
                   3138:         my $cachetime = 24*60*60;
                   3139:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   3140:     }
                   3141:     return %passwdconf;
                   3142: }
                   3143: 
1.344     www      3144: # --------------------------------------------------- Assign a key to a student
                   3145: 
                   3146: sub assign_access_key {
1.364     www      3147: #
                   3148: # a valid key looks like uname:udom#comments
                   3149: # comments are being appended
                   3150: #
1.498     www      3151:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   3152:     $kdom=
1.620     albertel 3153:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      3154:     $knum=
1.620     albertel 3155:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      3156:     $cdom=
1.620     albertel 3157:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3158:     $cnum=
1.620     albertel 3159:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3160:     $udom=$env{'user.name'} unless (defined($udom));
                   3161:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      3162:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      3163:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 3164:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      3165:                                                   # assigned to this person
                   3166:                                                   # - this should not happen,
1.345     www      3167:                                                   # unless something went wrong
                   3168:                                                   # the first time around
                   3169: # ready to assign
1.364     www      3170:         $logentry=$1.'; '.$logentry;
1.496     www      3171:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      3172:                                                  $kdom,$knum) eq 'ok') {
1.345     www      3173: # key now belongs to user
1.346     www      3174: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      3175:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  3176:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      3177:                 return 'ok';
                   3178:             } else {
                   3179:                 return 
                   3180:   'error: Count not permanently assign key, will need to be re-entered later.';
                   3181: 	    }
                   3182:         } else {
                   3183:             return 'error: Could not assign key, try again later.';
                   3184:         }
1.364     www      3185:     } elsif (!$existing{$ckey}) {
1.345     www      3186: # the key does not exist
                   3187: 	return 'error: The key does not exist';
                   3188:     } else {
                   3189: # the key is somebody else's
                   3190: 	return 'error: The key is already in use';
                   3191:     }
1.344     www      3192: }
                   3193: 
1.364     www      3194: # ------------------------------------------ put an additional comment on a key
                   3195: 
                   3196: sub comment_access_key {
                   3197: #
                   3198: # a valid key looks like uname:udom#comments
                   3199: # comments are being appended
                   3200: #
                   3201:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   3202:     $cdom=
1.620     albertel 3203:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      3204:     $cnum=
1.620     albertel 3205:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      3206:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   3207:     if ($existing{$ckey}) {
                   3208:         $existing{$ckey}.='; '.$logentry;
                   3209: # ready to assign
1.367     www      3210:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      3211:                                                  $cdom,$cnum) eq 'ok') {
                   3212: 	    return 'ok';
                   3213:         } else {
                   3214: 	    return 'error: Count not store comment.';
                   3215:         }
                   3216:     } else {
                   3217: # the key does not exist
                   3218: 	return 'error: The key does not exist';
                   3219:     }
                   3220: }
                   3221: 
1.344     www      3222: # ------------------------------------------------------ Generate a set of keys
                   3223: 
                   3224: sub generate_access_keys {
1.364     www      3225:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      3226:     $cdom=
1.620     albertel 3227:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3228:     $cnum=
1.620     albertel 3229:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      3230:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      3231:     unless (($cdom) && ($cnum)) { return 0; }
                   3232:     if ($number>10000) { return 0; }
                   3233:     sleep(2); # make sure don't get same seed twice
                   3234:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   3235:     my $total=0;
                   3236:     for (my $i=1;$i<=$number;$i++) {
                   3237:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   3238:                   sprintf("%lx",int(100000*rand)).'-'.
                   3239:                   sprintf("%lx",int(100000*rand));
                   3240:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   3241:        $newkey=~s/0/h/g; # and also 0 and O
                   3242:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   3243:        if ($existing{$newkey}) {
                   3244:            $i--;
                   3245:        } else {
1.364     www      3246: 	  if (&put('accesskeys',
                   3247:               { $newkey => '# generated '.localtime().
1.620     albertel 3248:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      3249:                            '; '.$logentry },
                   3250: 		   $cdom,$cnum) eq 'ok') {
1.344     www      3251:               $total++;
                   3252: 	  }
                   3253:        }
                   3254:     }
1.620     albertel 3255:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      3256:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   3257:     return $total;
                   3258: }
                   3259: 
                   3260: # ------------------------------------------------------- Validate an accesskey
                   3261: 
                   3262: sub validate_access_key {
                   3263:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   3264:     $cdom=
1.620     albertel 3265:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3266:     $cnum=
1.620     albertel 3267:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3268:     $udom=$env{'user.domain'} unless (defined($udom));
                   3269:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      3270:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 3271:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      3272: }
                   3273: 
                   3274: # ------------------------------------- Find the section of student in a course
1.652     albertel 3275: sub devalidate_getsection_cache {
                   3276:     my ($udom,$unam,$courseid)=@_;
                   3277:     my $hashid="$udom:$unam:$courseid";
                   3278:     &devalidate_cache_new('getsection',$hashid);
                   3279: }
1.298     matthew  3280: 
1.815     albertel 3281: sub courseid_to_courseurl {
                   3282:     my ($courseid) = @_;
                   3283:     #already url style courseid
                   3284:     return $courseid if ($courseid =~ m{^/});
                   3285: 
                   3286:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3287: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3288: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3289: 	return "/$cdom/$cnum";
                   3290:     }
                   3291: 
1.1494    raeburn  3292:     my %courseinfo=&coursedescription($courseid);
1.815     albertel 3293:     if (exists($courseinfo{'num'})) {
                   3294: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3295:     }
                   3296: 
                   3297:     return undef;
                   3298: }
                   3299: 
1.298     matthew  3300: sub getsection {
                   3301:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3302:     my $cachetime=1800;
1.551     albertel 3303: 
                   3304:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3305:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3306:     if (defined($cached)) { return $result; }
                   3307: 
1.298     matthew  3308:     my %Pending; 
                   3309:     my %Expired;
                   3310:     #
                   3311:     # Each role can either have not started yet (pending), be active, 
                   3312:     #    or have expired.
                   3313:     #
                   3314:     # If there is an active role, we are done.
                   3315:     #
                   3316:     # If there is more than one role which has not started yet, 
                   3317:     #     choose the one which will start sooner
                   3318:     # If there is one role which has not started yet, return it.
                   3319:     #
                   3320:     # If there is more than one expired role, choose the one which ended last.
                   3321:     # If there is a role which has expired, return it.
                   3322:     #
1.815     albertel 3323:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3324:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3325:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3326:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3327:         my $section=$1;
                   3328:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3329:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3330:         my $now=time;
1.548     albertel 3331:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3332:             $Expired{$end}=$section;
                   3333:             next;
                   3334:         }
1.548     albertel 3335:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3336:             $Pending{$start}=$section;
                   3337:             next;
                   3338:         }
1.599     albertel 3339:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3340:     }
                   3341:     #
                   3342:     # Presumedly there will be few matching roles from the above
                   3343:     # loop and the sorting time will be negligible.
                   3344:     if (scalar(keys(%Pending))) {
                   3345:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3346:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3347:     } 
                   3348:     if (scalar(keys(%Expired))) {
                   3349:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3350:         my $time = pop(@sorted);
1.599     albertel 3351:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3352:     }
1.599     albertel 3353:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3354: }
1.70      www      3355: 
1.599     albertel 3356: sub save_cache {
                   3357:     &purge_remembered();
1.722     albertel 3358:     #&Apache::loncommon::validate_page();
1.620     albertel 3359:     undef(%env);
1.780     albertel 3360:     undef($env_loaded);
1.599     albertel 3361: }
1.452     albertel 3362: 
1.599     albertel 3363: my $to_remember=-1;
                   3364: my %remembered;
                   3365: my %accessed;
                   3366: my $kicks=0;
                   3367: my $hits=0;
1.849     albertel 3368: sub make_key {
                   3369:     my ($name,$id) = @_;
1.872     albertel 3370:     if (length($id) > 65 
                   3371: 	&& length(&escape($id)) > 200) {
                   3372: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3373:     }
1.849     albertel 3374:     return &escape($name.':'.$id);
                   3375: }
                   3376: 
1.599     albertel 3377: sub devalidate_cache_new {
                   3378:     my ($name,$id,$debug) = @_;
                   3379:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3380:     my $remembered_id=$name.':'.$id;
1.849     albertel 3381:     $id=&make_key($name,$id);
1.599     albertel 3382:     $memcache->delete($id);
1.1319    damieng  3383:     delete($remembered{$remembered_id});
                   3384:     delete($accessed{$remembered_id});
1.599     albertel 3385: }
                   3386: 
                   3387: sub is_cached_new {
                   3388:     my ($name,$id,$debug) = @_;
1.1319    damieng  3389:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3390:     if (exists($remembered{$remembered_id})) {
                   3391: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3392: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3393: 	$hits++;
1.1319    damieng  3394: 	return ($remembered{$remembered_id},1);
1.599     albertel 3395:     }
1.1319    damieng  3396:     $id=&make_key($name,$id);
1.599     albertel 3397:     my $value = $memcache->get($id);
                   3398:     if (!(defined($value))) {
                   3399: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3400: 	return (undef,undef);
1.416     albertel 3401:     }
1.599     albertel 3402:     if ($value eq '__undef__') {
                   3403: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3404: 	$value=undef;
                   3405:     }
1.1319    damieng  3406:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3407:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3408:     return ($value,1);
                   3409: }
                   3410: 
                   3411: sub do_cache_new {
                   3412:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3413:     my $remembered_id=$name.':'.$id;
1.849     albertel 3414:     $id=&make_key($name,$id);
1.599     albertel 3415:     my $setvalue=$value;
                   3416:     if (!defined($setvalue)) {
                   3417: 	$setvalue='__undef__';
                   3418:     }
1.623     albertel 3419:     if (!defined($time) ) {
                   3420: 	$time=600;
                   3421:     }
1.599     albertel 3422:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3423:     my $result = $memcache->set($id,$setvalue,$time);
                   3424:     if (! $result) {
1.872     albertel 3425: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3426: 	$memcache->disconnect_all();
1.872     albertel 3427:     }
1.600     albertel 3428:     # need to make a copy of $value
1.1319    damieng  3429:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3430:     return $value;
                   3431: }
                   3432: 
                   3433: sub make_room {
1.1319    damieng  3434:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3435: 
1.1319    damieng  3436:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3437:                                     : $value;
1.599     albertel 3438:     if ($to_remember<0) { return; }
1.1319    damieng  3439:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3440:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3441:     my $to_kick;
                   3442:     my $max_time=0;
                   3443:     foreach my $other (keys(%accessed)) {
                   3444: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3445: 	    $to_kick=$other;
                   3446: 	    $max_time=&tv_interval($accessed{$other});
                   3447: 	}
                   3448:     }
                   3449:     delete($remembered{$to_kick});
                   3450:     delete($accessed{$to_kick});
                   3451:     $kicks++;
                   3452:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3453:     return;
                   3454: }
                   3455: 
1.599     albertel 3456: sub purge_remembered {
1.604     albertel 3457:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3458:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3459:     undef(%remembered);
                   3460:     undef(%accessed);
1.428     albertel 3461: }
1.70      www      3462: # ------------------------------------- Read an entry from a user's environment
                   3463: 
                   3464: sub userenvironment {
                   3465:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3466:     my $items;
                   3467:     foreach my $item (@what) {
                   3468:         $items.=&escape($item).'&';
                   3469:     }
                   3470:     $items=~s/\&$//;
1.70      www      3471:     my %returnhash=();
1.1009    raeburn  3472:     my $uhome = &homeserver($unam,$udom);
                   3473:     unless ($uhome eq 'no_host') {
                   3474:         my @answer=split(/\&/, 
                   3475:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3476:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3477:             return %returnhash;
                   3478:         }
1.1009    raeburn  3479:         my $i;
                   3480:         for ($i=0;$i<=$#what;$i++) {
                   3481: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3482:         }
1.70      www      3483:     }
                   3484:     return %returnhash;
1.1       albertel 3485: }
                   3486: 
1.617     albertel 3487: # ---------------------------------------------------------- Get a studentphoto
                   3488: sub studentphoto {
                   3489:     my ($udom,$unam,$ext) = @_;
1.1494    raeburn  3490:     my $home=&homeserver($unam,$udom);
1.706     raeburn  3491:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3492:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3493:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3494:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3495:             } else {
                   3496:                 my ($result,$perm_reqd)=
1.1494    raeburn  3497: 		    &auto_photo_permission($unam,$udom);
1.706     raeburn  3498:                 if ($result eq 'ok') {
                   3499:                     if (!($perm_reqd eq 'yes')) {
                   3500:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3501:                     }
                   3502:                 }
                   3503:             }
                   3504:         }
                   3505:     } else {
                   3506:         my ($result,$perm_reqd) = 
1.1494    raeburn  3507: 	    &auto_photo_permission($unam,$udom);
1.706     raeburn  3508:         if ($result eq 'ok') {
                   3509:             if (!($perm_reqd eq 'yes')) {
                   3510:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3511:             }
                   3512:         }
                   3513:     }
                   3514:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3515: }
                   3516: 
                   3517: sub retrievestudentphoto {
                   3518:     my ($udom,$unam,$ext,$type) = @_;
1.1494    raeburn  3519:     my $home=&homeserver($unam,$udom);
                   3520:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
1.706     raeburn  3521:     if ($ret eq 'ok') {
                   3522:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3523:         if ($type eq 'thumbnail') {
                   3524:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3525:         }
1.1494    raeburn  3526:         my $tokenurl=&tokenwrapper($url);
1.706     raeburn  3527:         return $tokenurl;
                   3528:     } else {
                   3529:         if ($type eq 'thumbnail') {
                   3530:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3531:         } else { 
                   3532:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3533:         }
1.617     albertel 3534:     }
                   3535: }
                   3536: 
1.263     www      3537: # -------------------------------------------------------------------- New chat
                   3538: 
                   3539: sub chatsend {
1.724     raeburn  3540:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3541:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3542:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3543:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3544:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3545: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3546: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3547: }
                   3548: 
                   3549: # ------------------------------------------ Find current version of a resource
                   3550: 
                   3551: sub getversion {
                   3552:     my $fname=&clutter(shift);
1.1189    raeburn  3553:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3554:     return &currentversion(&filelocation('',$fname));
                   3555: }
                   3556: 
                   3557: sub currentversion {
                   3558:     my $fname=shift;
                   3559:     my $author=$fname;
                   3560:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3561:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3562:     my $home=&homeserver($uname,$udom);
1.292     www      3563:     if ($home eq 'no_host') { 
                   3564:         return -1; 
                   3565:     }
1.1112    www      3566:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3567:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3568: 	return -1;
                   3569:     }
1.1112    www      3570:     return $answer;
1.263     www      3571: }
                   3572: 
1.1111    www      3573: #
                   3574: # Return special version number of resource if set by override, empty otherwise
                   3575: #
                   3576: sub usedversion {
                   3577:     my $fname=shift;
                   3578:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3579:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3580:     if ($urlversion) { return $urlversion; }
                   3581:     return '';
                   3582: }
                   3583: 
1.1       albertel 3584: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3585: 
1.1       albertel 3586: sub subscribe {
                   3587:     my $fname=shift;
1.761     raeburn  3588:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3589:     $fname=~s/[\n\r]//g;
1.1       albertel 3590:     my $author=$fname;
                   3591:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3592:     my ($udom,$uname)=split(/\//,$author);
                   3593:     my $home=homeserver($uname,$udom);
1.335     albertel 3594:     if ($home eq 'no_host') {
                   3595:         return 'not_found';
1.1       albertel 3596:     }
                   3597:     my $answer=reply("sub:$fname",$home);
1.64      www      3598:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3599: 	$answer.=' by '.$home;
                   3600:     }
1.1       albertel 3601:     return $answer;
                   3602: }
                   3603:     
1.8       www      3604: # -------------------------------------------------------------- Replicate file
                   3605: 
                   3606: sub repcopy {
                   3607:     my $filename=shift;
1.23      www      3608:     $filename=~s/\/+/\//g;
1.1142    raeburn  3609:     my $londocroot = $perlvar{'lonDocRoot'};
                   3610:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3611:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3612:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3613: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3614: 	return &repcopy_userfile($filename);
                   3615:     }
1.532     albertel 3616:     $filename=~s/[\n\r]//g;
1.8       www      3617:     my $transname="$filename.in.transfer";
1.828     www      3618: # FIXME: this should flock
1.607     raeburn  3619:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3620:     my $remoteurl=subscribe($filename);
1.64      www      3621:     if ($remoteurl =~ /^con_lost by/) {
                   3622: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3623:            return 'unavailable';
1.8       www      3624:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3625: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3626: 	   return 'not_found';
1.64      www      3627:     } elsif ($remoteurl =~ /^rejected by/) {
                   3628: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3629:            return 'forbidden';
1.20      www      3630:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3631:            return 'ok';
1.8       www      3632:     } else {
1.290     www      3633:         my $author=$filename;
                   3634:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3635:         my ($udom,$uname)=split(/\//,$author);
                   3636:         my $home=homeserver($uname,$udom);
                   3637:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3638:            my @parts=split(/\//,$filename);
                   3639:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3640:            if ($path ne "$londocroot/res") {
1.8       www      3641:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3642: 	       return 'bad_request';
1.8       www      3643:            }
                   3644:            my $count;
                   3645:            for ($count=5;$count<$#parts;$count++) {
                   3646:                $path.="/$parts[$count]";
                   3647:                if ((-e $path)!=1) {
                   3648: 		   mkdir($path,0777);
                   3649:                }
                   3650:            }
                   3651:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3652:            my $response;
                   3653:            if ($remoteurl =~ m{/raw/}) {
                   3654:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3655:            } else {
                   3656:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3657:            }
1.8       www      3658:            if ($response->is_error()) {
                   3659: 	       unlink($transname);
                   3660:                my $message=$response->status_line;
1.672     albertel 3661:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3662:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3663:                return 'unavailable';
1.8       www      3664:            } else {
1.16      www      3665: 	       if ($remoteurl!~/\.meta$/) {
                   3666:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3667:                   my $mresponse;
                   3668:                   if ($remoteurl =~ m{/raw/}) {
                   3669:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3670:                   } else {
                   3671:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3672:                   }
1.16      www      3673:                   if ($mresponse->is_error()) {
                   3674: 		      unlink($filename.'.meta');
                   3675:                       &logthis(
1.672     albertel 3676:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3677:                   }
                   3678: 	       }
1.8       www      3679:                rename($transname,$filename);
1.607     raeburn  3680:                return 'ok';
1.8       www      3681:            }
1.290     www      3682:        }
1.8       www      3683:     }
1.330     www      3684: }
                   3685: 
1.1422    raeburn  3686: # ------------------------------------------------- Unsubscribe from a resource
                   3687: 
                   3688: sub unsubscribe {
                   3689:     my ($fname) = @_;
                   3690:     my $answer;
                   3691:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3692:     $fname=~s/[\n\r]//g;
                   3693:     my $author=$fname;
                   3694:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3695:     my ($udom,$uname)=split(/\//,$author);
                   3696:     my $home=homeserver($uname,$udom);
                   3697:     if ($home eq 'no_host') {
                   3698:         $answer = 'no_host';
                   3699:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3700:         $answer = 'home';
                   3701:     } else {
                   3702:         my $defdom = $perlvar{'lonDefDomain'};
                   3703:         if (&will_trust('content',$defdom,$udom)) {
                   3704:             $answer = reply("unsub:$fname",$home);
                   3705:         } else {
                   3706:             $answer = 'untrusted';
                   3707:         }
                   3708:     }
                   3709:     return $answer;
                   3710: }
                   3711: 
1.330     www      3712: # ------------------------------------------------ Get server side include body
                   3713: sub ssi_body {
1.381     albertel 3714:     my ($filelink,%form)=@_;
1.606     matthew  3715:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3716:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3717:     }
1.953     www      3718:     my $output='';
                   3719:     my $response;
1.980     raeburn  3720:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3721:        ($output,$response)=&externalssi($filelink);
1.953     www      3722:     } else {
1.1004    droeschl 3723:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3724:        $filelink .= 'inhibitmenu=yes';
1.953     www      3725:        ($output,$response)=&ssi($filelink,%form);
                   3726:     }
1.778     albertel 3727:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3728:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3729:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3730:     if (wantarray) {
                   3731:         return ($output, $response);
                   3732:     } else {
                   3733:         return $output;
                   3734:     }
1.8       www      3735: }
                   3736: 
1.15      www      3737: # --------------------------------------------------------- Server Side Include
                   3738: 
1.782     albertel 3739: sub absolute_url {
1.1447    raeburn  3740:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3741:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3742:     if ($host_name eq '') {
                   3743: 	$host_name = $ENV{'SERVER_NAME'};
                   3744:     }
1.1447    raeburn  3745:     if ($unalias) {
                   3746:         my $alias = &get_proxy_alias();
                   3747:         if ($alias eq $host_name) {
                   3748:             my $lonhost = $perlvar{'lonHostID'};
                   3749:             my $hostname = &hostname($lonhost);
                   3750:             my $lcproto; 
                   3751:             if (($keep_proto) || ($hostname eq '')) {
                   3752:                 $lcproto = $protocol;
                   3753:             } else {
                   3754:                 $lcproto = $protocol{$lonhost};
                   3755:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3756:                 $lcproto .= '://';
                   3757:             }
                   3758:             unless ($hostname eq '') {
                   3759:                 return $lcproto.$hostname;
                   3760:             }
                   3761:         }
                   3762:     }
1.782     albertel 3763:     return $protocol.$host_name;
                   3764: }
                   3765: 
1.942     foxr     3766: #
                   3767: #   Server side include.
                   3768: # Parameters:
                   3769: #  fn     Possibly encrypted resource name/id.
                   3770: #  form   Hash that describes how the rendering should be done
                   3771: #         and other things.
1.944     foxr     3772: # Returns:
1.950     raeburn  3773: #   Scalar context: The content of the response.
                   3774: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3775: #     
1.15      www      3776: sub ssi {
                   3777: 
1.944     foxr     3778:     my ($fn,%form)=@_;
1.1447    raeburn  3779:     my ($host,$request,$response);
                   3780:     $host = &absolute_url('',1);
1.711     albertel 3781: 
                   3782:     $form{'no_update_last_known'}=1;
1.895     albertel 3783:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3784:     if (%form) {
1.1447    raeburn  3785:       $request=new HTTP::Request('POST',$host.$fn);
1.1272    droeschl 3786:       $request->content(join('&',map { 
                   3787:             my $name = escape($_);
                   3788:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3789:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3790:             : &escape($form{$_}) );    
                   3791:         } keys(%form)));
1.23      www      3792:     } else {
1.1447    raeburn  3793:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3794:     }
                   3795: 
1.15      www      3796:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3797:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3798:     my $islocal;
                   3799:     if (($env{'request.course.id'}) &&
                   3800:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3801:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3802:         ($form{'grade_symb'} ne '') &&
1.1494    raeburn  3803:         (&allowed('mgr',$env{'request.course.id'}.
                   3804:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1385    raeburn  3805:         $islocal = 1;
                   3806:     }
1.1447    raeburn  3807:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
                   3808:                                              '','','',$islocal);
1.1182    foxr     3809: 
1.944     foxr     3810:     if (wantarray) {
1.1345    raeburn  3811: 	return ($response->content, $response);
1.944     foxr     3812:     } else {
1.1345    raeburn  3813: 	return $response->content;
1.942     foxr     3814:     }
1.324     www      3815: }
                   3816: 
                   3817: sub externalssi {
                   3818:     my ($url)=@_;
                   3819:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3820:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3821:     if (wantarray) {
                   3822:         return ($response->content, $response);
                   3823:     } else {
                   3824:         return $response->content;
                   3825:     }
1.15      www      3826: }
1.254     www      3827: 
1.1354    raeburn  3828: 
                   3829: # If the local copy of a replicated resource is outdated, trigger a  
                   3830: # connection from the homeserver to flush the delayed queue. If no update 
                   3831: # happens, remove local copies of outdated resource (and corresponding
                   3832: # metadata file).
                   3833: 
1.1352    raeburn  3834: sub remove_stale_resfile {
                   3835:     my ($url) = @_;
1.1354    raeburn  3836:     my $removed;
1.1352    raeburn  3837:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3838:         my $audom = $1;
                   3839:         my $auname = $2;
1.1353    raeburn  3840:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3841:             my $homeserver = &homeserver($auname,$audom);
                   3842:             unless (($homeserver eq 'no_host') ||
                   3843:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3844:                 my $fname = &filelocation('',$url);
                   3845:                 if (-e $fname) {
                   3846:                     my $hostname = &hostname($homeserver);
                   3847:                     if ($hostname) {
1.1397    raeburn  3848:                         my $protocol = $protocol{$homeserver};
                   3849:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3850:                         my $uri = &declutter($url);
                   3851:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3852:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3853:                         if ($response->is_success()) {
                   3854:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3855:                             my $locmodtime = (stat($fname))[9];
                   3856:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3857:                                 my $stale;
                   3858:                                 my $answer = &reply('pong',$homeserver);
                   3859:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3860:                                     sleep(0.2);
                   3861:                                     $locmodtime = (stat($fname))[9];
                   3862:                                     if ($locmodtime < $remmodtime) {
                   3863:                                         my $posstransfer = $fname.'.in.transfer';
                   3864:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3865:                                             $removed = 1;
                   3866:                                         } else {
                   3867:                                             $stale = 1;
                   3868:                                         }
                   3869:                                     } else {
                   3870:                                         $removed = 1;
                   3871:                                     }
                   3872:                                 } else {
                   3873:                                     $stale = 1;
                   3874:                                 }
                   3875:                                 if ($stale) {
1.1421    raeburn  3876:                                     if (unlink($fname)) {
                   3877:                                         if ($uri!~/\.meta$/) {
                   3878:                                             if (-e $fname.'.meta') {
                   3879:                                                 unlink($fname.'.meta');
                   3880:                                             }
                   3881:                                         }
1.1422    raeburn  3882:                                         my $unsubresult = &unsubscribe($fname);
                   3883:                                         unless ($unsubresult eq 'ok') {
                   3884:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3885:                                         }
1.1421    raeburn  3886:                                         $removed = 1;
1.1354    raeburn  3887:                                     }
1.1352    raeburn  3888:                                 }
                   3889:                             }
                   3890:                         }
                   3891:                     }
                   3892:                 }
                   3893:             }
                   3894:         }
                   3895:     }
1.1354    raeburn  3896:     return $removed;
1.1352    raeburn  3897: }
                   3898: 
1.492     albertel 3899: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3900: 
                   3901: sub allowuploaded {
                   3902:     my ($srcurl,$url)=@_;
                   3903:     $url=&clutter(&declutter($url));
                   3904:     my $dir=$url;
                   3905:     $dir=~s/\/[^\/]+$//;
                   3906:     my %httpref=();
                   3907:     my $httpurl=&hreflocation('',$url);
                   3908:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3909:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3910: }
1.477     raeburn  3911: 
1.1193    raeburn  3912: #
                   3913: # Determine if the current user should be able to edit a particular resource,
                   3914: # when viewing in course context.
                   3915: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3916: #     Functions.
                   3917: # (b) When displaying folder contents in course editor, used to determine if
                   3918: #     "Edit" link will be displayed alongside resource.
                   3919: #
1.1196    raeburn  3920: #  input: six args -- filename (decluttered), course number, course domain,
                   3921: #                   url, symb (if registered) and group (if this is a group
                   3922: #                   item -- e.g., bulletin board, group page etc.).
                   3923: #  output: array of five scalars -- 
1.1193    raeburn  3924: #          $cfile -- url for file editing if editable on current server
                   3925: #          $home -- homeserver of resource (i.e., for author if published,
                   3926: #                                           or course if uploaded.).
                   3927: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3928: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3929: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3930: #
                   3931: 
                   3932: sub can_edit_resource {
1.1194    raeburn  3933:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3934:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3935: #
                   3936: # For aboutme pages user can only edit his/her own.
                   3937: #
1.1199    raeburn  3938:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3939:         my ($sdom,$sname) = ($1,$2);
                   3940:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3941:             $home = $env{'user.home'};
                   3942:             $cfile = $resurl;
                   3943:             if ($env{'form.forceedit'}) {
                   3944:                 $forceview = 1;
                   3945:             } else {
                   3946:                 $forceedit = 1;
                   3947:             }
                   3948:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3949:         } else {
                   3950:             return;
                   3951:         }
                   3952:     }
                   3953: 
1.1517    raeburn  3954: #
                   3955: # For /adm/viewcoauthors can only edit if author or co-author who is manager.
                   3956: #
                   3957: 
                   3958:     if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
                   3959:         if (((&allowed('cca',"$cdom/$cnum")) ||
                   3960:              (&allowed('caa',"$cdom/$cnum"))) ||
                   3961:              ((&allowed('vca',"$cdom/$cnum") ||
                   3962:                &allowed('vaa',"$cdom/$cnum")) &&
                   3963:               ($env{"environment.internal.manager./$cdom/$cnum"}))) {
                   3964:             $home = $env{'user.home'};
                   3965:             $cfile = $resurl;
                   3966:             if ($env{'form.forceedit'}) {
                   3967:                 $forceview = 1;
                   3968:             } else {
                   3969:                 $forceedit = 1;
                   3970:             }
                   3971:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3972:         } else {
                   3973:             return;
                   3974:         }
                   3975:     }
                   3976: 
1.1194    raeburn  3977:     if ($env{'request.course.id'}) {
1.1494    raeburn  3978:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
1.1194    raeburn  3979:         if ($group ne '') {
                   3980: # if this is a group homepage or group bulletin board, check group privs
                   3981:             my $allowed = 0;
1.1197    raeburn  3982:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3983:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3984:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3985:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3986:                     $allowed = 1;
                   3987:                 }
1.1197    raeburn  3988:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3989:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3990:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3991:                     $allowed = 1;
                   3992:                 }
                   3993:             }
                   3994:             if ($allowed) {
                   3995:                 $home=&homeserver($cnum,$cdom);
                   3996:                 if ($env{'form.forceedit'}) {
                   3997:                     $forceview = 1;
                   3998:                 } else {
                   3999:                     $forceedit = 1;
                   4000:                 }
                   4001:                 $cfile = $resurl;
                   4002:             } else {
                   4003:                 return;
                   4004:             }
                   4005:         } else {
1.1208    raeburn  4006:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
1.1494    raeburn  4007:                 unless (&allowed('opa',$env{'request.course.id'})) {
1.1208    raeburn  4008:                     return;
                   4009:                 }
                   4010:             } elsif (!$crsedit) {
1.1507    raeburn  4011:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
1.1194    raeburn  4012: #
                   4013: # No edit allowed where CC has switched to student role.
                   4014: #
1.1507    raeburn  4015:                     return;
                   4016:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
                   4017:                          ($resurl =~ m{^/res/lib/templates/})) {
                   4018:                     return;
                   4019:                 }
1.1194    raeburn  4020:             }
                   4021:         }
                   4022:     }
                   4023: 
1.1193    raeburn  4024:     if ($file ne '') {
                   4025:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  4026:             if (&is_course_upload($file,$cnum,$cdom)) {
                   4027:                 $uploaded = 1;
                   4028:                 $incourse = 1;
1.1193    raeburn  4029:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   4030:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  4031:                     if ($env{'form.forceedit'}) {
                   4032:                         $forceview = 1;
                   4033:                     } else {
                   4034:                         $forceedit = 1;
                   4035:                     }
1.1194    raeburn  4036:                 }
                   4037:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   4038:                 $incourse = 1;
                   4039:                 if ($env{'form.forceedit'}) {
                   4040:                     $forceview = 1;
                   4041:                 } else {
                   4042:                     $forceedit = 1;
                   4043:                 }
                   4044:                 $cfile = $resurl;
1.1507    raeburn  4045:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
1.1194    raeburn  4046:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   4047:                     $incourse = 1;
                   4048:                     if ($env{'form.forceedit'}) {
                   4049:                         $forceview = 1;
                   4050:                     } else {
                   4051:                         $forceedit = 1;
                   4052:                     }
                   4053:                     $cfile = $resurl;
1.1199    raeburn  4054:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  4055:                     $incourse = 1;
                   4056:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  4057:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  4058:                     $incourse = 1;
1.1199    raeburn  4059:                     if ($env{'form.forceedit'}) {
                   4060:                         $forceview = 1;
                   4061:                     } else {
                   4062:                         $forceedit = 1;
                   4063:                     }
                   4064:                     $cfile = $resurl;
1.1419    raeburn  4065:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   4066:                     my ($map,$id,$res) = &decode_symb($symb);
                   4067:                     if ($map =~ /\.page$/) {
                   4068:                         $incourse = 1;
                   4069:                         if ($env{'form.forceedit'}) {
                   4070:                             $forceview = 1;
                   4071:                             $cfile = $map;
                   4072:                         } else {
                   4073:                             $forceedit = 1;
                   4074:                             $cfile =  '/adm/wrapper'.$resurl;
                   4075:                         }
                   4076:                     }
1.1343    raeburn  4077:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  4078:                     $incourse = 1;
                   4079:                     if ($env{'form.forceedit'}) {
                   4080:                         $forceview = 1;
                   4081:                     } else {
                   4082:                         $forceedit = 1;
                   4083:                     }
                   4084:                     $cfile = $resurl;
1.1208    raeburn  4085:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   4086:                     $incourse = 1;
                   4087:                     if ($env{'form.forceedit'}) {
                   4088:                         $forceview = 1;
                   4089:                     } else {
                   4090:                         $forceedit = 1;
                   4091:                     }
                   4092:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  4093:                 }
                   4094:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   4095:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   4096:                 if (&is_on_map($template)) { 
                   4097:                     $incourse = 1;
                   4098:                     $forceview = 1;
                   4099:                     $cfile = $template;
1.1193    raeburn  4100:                 }
1.1199    raeburn  4101:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  4102:                 $incourse = 1;
                   4103:                 if ($env{'form.forceedit'}) {
                   4104:                     $forceview = 1;
                   4105:                 } else {
                   4106:                     $forceedit = 1;
                   4107:                 }
                   4108:                 $cfile = $resurl;
1.1343    raeburn  4109:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  4110:                 $incourse = 1;
                   4111:                 if ($env{'form.forceedit'}) {
                   4112:                     $forceview = 1;
                   4113:                 } else {
                   4114:                     $forceedit = 1;
                   4115:                 }
                   4116:                 $cfile = $resurl;
1.1199    raeburn  4117:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   4118:                 $incourse = 1;
                   4119:                 $forceview = 1;
                   4120:                 if ($symb) {
                   4121:                     my ($map,$id,$res)=&decode_symb($symb);
                   4122:                     $env{'request.symb'} = $symb;
                   4123:                     $cfile = &clutter($res);
                   4124:                 } else {
                   4125:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  4126:                     my $escfile = &unescape($cfile);
1.1343    raeburn  4127:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  4128:                         $cfile = '/adm/wrapper'.$escfile;
                   4129:                     } else {
                   4130:                         $escfile =~ s{^http://}{};
                   4131:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   4132:                     }
1.1199    raeburn  4133:                 }
1.1234    raeburn  4134:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   4135:                 if ($env{'form.forceedit'}) {
                   4136:                     $forceview = 1;
                   4137:                 } else {
                   4138:                     $forceedit = 1;
                   4139:                 }
                   4140:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  4141:             }
                   4142:         }
1.1194    raeburn  4143:         if ($uploaded || $incourse) {
                   4144:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  4145:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  4146:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   4147:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   4148:             # Check that the user has permission to edit this resource
                   4149:             my $setpriv = 1;
                   4150:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   4151:             if (defined($cfudom)) {
                   4152:                 $home=&homeserver($cfuname,$cfudom);
                   4153:                 $cfile=$file;
                   4154:             }
                   4155:         }
1.1194    raeburn  4156:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   4157:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  4158:             my @ids=&current_machine_ids();
                   4159:             unless (grep(/^\Q$home\E$/,@ids)) {
                   4160:                 $switchserver=1;
                   4161:             }
                   4162:         }
                   4163:     }
1.1194    raeburn  4164:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  4165: }
                   4166: 
                   4167: sub is_course_upload {
                   4168:     my ($file,$cnum,$cdom) = @_;
                   4169:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   4170:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  4171:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   4172:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  4173:         return 1;
                   4174:     }
                   4175:     return;
                   4176: }
                   4177: 
1.1194    raeburn  4178: sub in_course {
1.1195    raeburn  4179:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   4180:     if ($hideprivileged) {
                   4181:         my $skipuser;
1.1219    raeburn  4182:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   4183:         my @possdoms = ($cdom);  
                   4184:         if ($coursehash{'checkforpriv'}) { 
                   4185:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   4186:         }
                   4187:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  4188:             $skipuser = 1;
                   4189:             if ($coursehash{'nothideprivileged'}) {
                   4190:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4191:                     my $user;
                   4192:                     if ($item =~ /:/) {
                   4193:                         $user = $item;
                   4194:                     } else {
                   4195:                         $user = join(':',split(/[\@]/,$item));
                   4196:                     }
                   4197:                     if ($user eq $uname.':'.$udom) {
                   4198:                         undef($skipuser);
                   4199:                         last;
                   4200:                     }
                   4201:                 }
                   4202:             }
                   4203:             if ($skipuser) {
                   4204:                 return 0;
                   4205:             }
                   4206:         }
                   4207:     }
1.1194    raeburn  4208:     $type ||= 'any';
                   4209:     if (!defined($cdom) || !defined($cnum)) {
                   4210:         my $cid  = $env{'request.course.id'};
                   4211:         $cdom = $env{'course.'.$cid.'.domain'};
                   4212:         $cnum = $env{'course.'.$cid.'.num'};
                   4213:     }
                   4214:     my $typesref;
1.1195    raeburn  4215:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  4216:         $typesref = ['active','previous','future'];
                   4217:     } elsif ($type eq 'previous' || $type eq 'future') {
                   4218:         $typesref = [$type];
                   4219:     }
                   4220:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   4221:                               $typesref,undef,[$cdom]);
                   4222:     my ($tmp) = keys(%roles);
                   4223:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   4224:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   4225:     if (@course_roles > 0) {
                   4226:         return 1;
                   4227:     }
                   4228:     return 0;
                   4229: }
                   4230: 
1.478     albertel 4231: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 4232: # input: action, courseID, current domain, intended
1.637     raeburn  4233: #        path to file, source of file, instruction to parse file for objects,
                   4234: #        ref to hash for embedded objects,
                   4235: #        ref to hash for codebase of java objects.
1.1095    raeburn  4236: #        reference to scalar to accommodate mime type determined
                   4237: #          from File::MMagic if $parser = parse.
1.637     raeburn  4238: #
1.485     raeburn  4239: # output: url to file (if action was uploaddoc), 
                   4240: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  4241: #
1.478     albertel 4242: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   4243: # course.
1.477     raeburn  4244: #
1.478     albertel 4245: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4246: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   4247: #          course's home server.
1.477     raeburn  4248: #
1.478     albertel 4249: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   4250: #          be copied from $source (current location) to 
                   4251: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4252: #         and will then be copied to
                   4253: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   4254: #         course's home server.
1.485     raeburn  4255: #
1.481     raeburn  4256: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 4257: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  4258: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4259: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   4260: #         in course's home server.
1.637     raeburn  4261: #
1.477     raeburn  4262: 
                   4263: sub process_coursefile {
1.1095    raeburn  4264:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   4265:         $mimetype)=@_;
1.477     raeburn  4266:     my $fetchresult;
1.638     albertel 4267:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  4268:     if ($action eq 'propagate') {
1.638     albertel 4269:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   4270: 			     $home);
1.481     raeburn  4271:     } else {
1.477     raeburn  4272:         my $fpath = '';
                   4273:         my $fname = $file;
1.478     albertel 4274:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  4275:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  4276:         my $filepath = &build_filepath($fpath);
1.481     raeburn  4277:         if ($action eq 'copy') {
                   4278:             if ($source eq '') {
                   4279:                 $fetchresult = 'no source file';
                   4280:                 return $fetchresult;
                   4281:             } else {
                   4282:                 my $destination = $filepath.'/'.$fname;
                   4283:                 rename($source,$destination);
                   4284:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4285:                                  $home);
1.481     raeburn  4286:             }
                   4287:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  4288:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 4289:             print $fh $env{'form.'.$source};
1.481     raeburn  4290:             close($fh);
1.637     raeburn  4291:             if ($parser eq 'parse') {
1.1024    raeburn  4292:                 my $mm = new File::MMagic;
1.1095    raeburn  4293:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   4294:                 if ($type eq 'text/html') {
1.1024    raeburn  4295:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   4296:                     unless ($parse_result eq 'ok') {
                   4297:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   4298:                     }
1.637     raeburn  4299:                 }
1.1095    raeburn  4300:                 if (ref($mimetype)) {
                   4301:                     $$mimetype = $type;
                   4302:                 } 
1.637     raeburn  4303:             }
1.477     raeburn  4304:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4305:                                  $home);
1.481     raeburn  4306:             if ($fetchresult eq 'ok') {
                   4307:                 return '/uploaded/'.$fpath.'/'.$fname;
                   4308:             } else {
                   4309:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4310:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  4311:                 return '/adm/notfound.html';
                   4312:             }
1.477     raeburn  4313:         }
                   4314:     }
1.485     raeburn  4315:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4316:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4317:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4318:     }
                   4319:     return $fetchresult;
                   4320: }
                   4321: 
1.637     raeburn  4322: sub build_filepath {
                   4323:     my ($fpath) = @_;
                   4324:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4325:     unless ($fpath eq '') {
                   4326:         my @parts=split('/',$fpath);
                   4327:         foreach my $part (@parts) {
                   4328:             $filepath.= '/'.$part;
                   4329:             if ((-e $filepath)!=1) {
                   4330:                 mkdir($filepath,0777);
                   4331:             }
                   4332:         }
                   4333:     }
                   4334:     return $filepath;
                   4335: }
                   4336: 
                   4337: sub store_edited_file {
1.638     albertel 4338:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4339:     my $file = $primary_url;
                   4340:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4341:     my $fpath = '';
                   4342:     my $fname = $file;
                   4343:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4344:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4345:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4346:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4347:     print $fh $content;
                   4348:     close($fh);
1.638     albertel 4349:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4350:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4351: 			  $home);
1.637     raeburn  4352:     if ($$fetchresult eq 'ok') {
                   4353:         return '/uploaded/'.$fpath.'/'.$fname;
                   4354:     } else {
1.638     albertel 4355:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4356: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4357:         return '/adm/notfound.html';
                   4358:     }
                   4359: }
                   4360: 
1.531     albertel 4361: sub clean_filename {
1.831     albertel 4362:     my ($fname,$args)=@_;
1.315     www      4363: # Replace Windows backslashes by forward slashes
1.257     www      4364:     $fname=~s/\\/\//g;
1.831     albertel 4365:     if (!$args->{'keep_path'}) {
                   4366:         # Get rid of everything but the actual filename
                   4367: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4368:     }
1.315     www      4369: # Replace spaces by underscores
                   4370:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4371: # Transliterate non-ascii text to ascii
                   4372:     my $lang = &Apache::lonlocal::current_language();
                   4373:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4374: # Replace all other weird characters by nothing
1.831     albertel 4375:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4376: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4377: # numbers
                   4378:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443    raeburn  4379: # Replace three or more adjacent underscores with one for consistency 
                   4380: # with loncfile::filename_check() so complete url can be extracted by
                   4381: # lonnet::decode_symb()
                   4382:     $fname=~s/_{3,}/_/g;
1.531     albertel 4383:     return $fname;
                   4384: }
1.1406    raeburn  4385: 
1.1051    raeburn  4386: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4387: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4388: # image with the same aspect ratio as the original, but with dimensions which do 
                   4389: # not exceed $resizewidth and $resizeheight.
                   4390:  
1.984     neumanie 4391: sub resizeImage {
1.1051    raeburn  4392:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4393:     my $ima = Image::Magick->new;
                   4394:     my $resized;
                   4395:     if (-e $img_path) {
                   4396:         $ima->Read($img_path);
                   4397:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4398:             my $width = $ima->Get('width');
                   4399:             my $height = $ima->Get('height');
                   4400:             if ($width > $resizewidth) {
                   4401: 	        my $factor = $width/$resizewidth;
                   4402:                 my $newheight = $height/$factor;
                   4403:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4404:                 $resized = 1;
                   4405:             }
                   4406:         }
                   4407:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4408:             my $width = $ima->Get('width');
                   4409:             my $height = $ima->Get('height');
                   4410:             if ($height > $resizeheight) {
                   4411:                 my $factor = $height/$resizeheight;
                   4412:                 my $newwidth = $width/$factor;
                   4413:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4414:                 $resized = 1;
                   4415:             }
                   4416:         }
                   4417:         if ($resized) {
                   4418:             $ima->Write($img_path);
                   4419:         }
                   4420:     }
                   4421:     return;
1.977     amueller 4422: }
                   4423: 
1.608     albertel 4424: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4425: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4426: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4427: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1504    raeburn  4428: #                                    canceloverwrite, scantron, toollogo  or ''.
1.1090    raeburn  4429: #                   if 'coursedoc': upload to the current course
                   4430: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4431: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4432: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4433: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4434: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4435: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4436: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4437: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4438: #        $allfiles - reference to hash for embedded objects
                   4439: #        $codebase - reference to hash for codebase of java objects
1.1504    raeburn  4440: #        $destuname - username for permanent storage of uploaded file
                   4441: #        $destudom - domain for permanaent storage of uploaded file
1.860     raeburn  4442: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4443: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4444: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4445: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4446: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4447: #                    from File::MMagic.
1.858     raeburn  4448: # 
1.686     albertel 4449: # output: url of file in userspace, or error: <message> 
                   4450: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4451: 
1.531     albertel 4452: sub userfileupload {
1.1090    raeburn  4453:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4454:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4455:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4456:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4457:     $fname=&clean_filename($fname);
1.1090    raeburn  4458:     # See if there is anything left
1.257     www      4459:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4460:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4461:     if ($fname =~ /^\./) {
                   4462:         my ($s,$usec) = &gettimeofday();
                   4463:         while (length($usec) < 6) {
                   4464:             $usec = '0'.$usec;
                   4465:         }
                   4466:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4467:     }
1.1090    raeburn  4468:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4469:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4470:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4471:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4472:         my $now = time;
1.1090    raeburn  4473:         my $filepath;
1.1095    raeburn  4474:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4475:              $filepath = 'tmp/helprequests/'.$now;
                   4476:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4477:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4478:                          '_'.$env{'user.domain'}.'/pending';
                   4479:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4480:             my ($docuname,$docudom);
1.1350    raeburn  4481:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4482:                 $docudom = $destudom;
                   4483:             } else {
                   4484:                 $docudom = $env{'user.domain'};
                   4485:             }
1.1350    raeburn  4486:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4487:                 $docuname = $destuname;
                   4488:             } else {
                   4489:                 $docuname = $env{'user.name'};
                   4490:             }
                   4491:             if (exists($env{'form.group'})) {
                   4492:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4493:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4494:             }
                   4495:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4496:             if ($context eq 'canceloverwrite') {
                   4497:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4498:                 if (-e  $tempfile) {
                   4499:                     my @info = stat($tempfile);
                   4500:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4501:                         unlink($tempfile);
                   4502:                     }
                   4503:                 }
                   4504:                 return;
1.523     raeburn  4505:             }
                   4506:         }
1.1090    raeburn  4507:         # Create the directory if not present
1.741     raeburn  4508:         my @parts=split(/\//,$filepath);
                   4509:         my $fullpath = $perlvar{'lonDaemons'};
                   4510:         for (my $i=0;$i<@parts;$i++) {
                   4511:             $fullpath .= '/'.$parts[$i];
                   4512:             if ((-e $fullpath)!=1) {
                   4513:                 mkdir($fullpath,0777);
                   4514:             }
                   4515:         }
1.1359    raeburn  4516:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4517:         print $fh $env{'form.'.$formname};
                   4518:         close($fh);
1.1090    raeburn  4519:         if ($context eq 'existingfile') {
                   4520:             my @info = stat($fullpath.'/'.$fname);
                   4521:             return ($fullpath.'/'.$fname,$info[9]);
                   4522:         } else {
                   4523:             return $fullpath.'/'.$fname;
                   4524:         }
1.523     raeburn  4525:     }
1.995     raeburn  4526:     if ($subdir eq 'scantron') {
                   4527:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4528:     } else {
1.995     raeburn  4529:         $fname="$subdir/$fname";
                   4530:     }
1.1090    raeburn  4531:     if ($context eq 'coursedoc') {
1.638     albertel 4532: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4533: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4534:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4535:             return &finishuserfileupload($docuname,$docudom,
                   4536: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4537: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4538:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4539:         } else {
1.1218    raeburn  4540:             if ($env{'form.folder'}) {
                   4541:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4542:             }
1.638     albertel 4543:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4544: 				       $fname,$formname,$parser,
1.1095    raeburn  4545: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4546:         }
1.719     banghart 4547:     } elsif (defined($destuname)) {
                   4548:         my $docuname=$destuname;
                   4549:         my $docudom=$destudom;
1.860     raeburn  4550: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4551: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4552:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4553:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4554:     } else {
1.638     albertel 4555:         my $docuname=$env{'user.name'};
                   4556:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4557:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4558:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4559:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4560:         }
1.860     raeburn  4561: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4562: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4563:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4564:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4565:     }
1.271     www      4566: }
                   4567: 
                   4568: sub finishuserfileupload {
1.860     raeburn  4569:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4570:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4571:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4572:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4573:   
1.860     raeburn  4574:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4575:     $file=$fname;
                   4576:     if ($fname=~m|/|) {
                   4577:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4578: 	$path.=$fnamepath.'/';
                   4579:     }
1.259     www      4580:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4581:     my $count;
                   4582:     for ($count=4;$count<=$#parts;$count++) {
                   4583:         $filepath.="/$parts[$count]";
                   4584:         if ((-e $filepath)!=1) {
                   4585: 	    mkdir($filepath,0777);
                   4586:         }
                   4587:     }
1.984     neumanie 4588: 
1.258     www      4589: # Save the file
                   4590:     {
1.1359    raeburn  4591: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4592: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4593: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4594: 	    return '/adm/notfound.html';
                   4595: 	}
1.1090    raeburn  4596:         if ($context eq 'overwrite') {
1.1117    foxr     4597:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4598:             my $target = $filepath.'/'.$file;
                   4599:             if (-e $source) {
                   4600:                 my @info = stat($source);
                   4601:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4602:                     unless (&File::Copy::move($source,$target)) {
                   4603:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4604:                         return "Moving from $source failed";
                   4605:                     }
                   4606:                 } else {
                   4607:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4608:                 }
                   4609:             } else {
                   4610:                 return "Temporary file: $source missing";
                   4611:             }
                   4612:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4613: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4614: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4615: 	    return '/adm/notfound.html';
                   4616: 	}
1.570     albertel 4617: 	close(FH);
1.1051    raeburn  4618:         if ($resizewidth && $resizeheight) {
                   4619:             my $mm = new File::MMagic;
                   4620:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4621:             if ($mime_type =~ m{^image/}) {
                   4622: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4623:             }  
1.977     amueller 4624: 	}
1.258     www      4625:     }
1.1152    raeburn  4626:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4627:         if (ref($mimetype)) {
                   4628:             if ($$mimetype eq '') {
                   4629:                 my $mm = new File::MMagic;
                   4630:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4631:                 $$mimetype = $type;
                   4632:             }
                   4633:         }
                   4634:     }
1.1401    raeburn  4635:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4636:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4637:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4638:                                                        $allfiles,$codebase);
                   4639:             unless ($parse_result eq 'ok') {
                   4640:                 &logthis('Failed to parse '.$filepath.$file.
                   4641: 	   	         ' for embedded media: '.$parse_result); 
                   4642:             }
1.637     raeburn  4643:         }
1.1401    raeburn  4644:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4645:         my $format = $env{'form.scantron_format'};
                   4646:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4647:     }
1.860     raeburn  4648:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4649:         my $input = $filepath.'/'.$file;
                   4650:         my $output = $filepath.'/'.'tn-'.$file;
1.1504    raeburn  4651:         my $makethumb; 
1.860     raeburn  4652:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1504    raeburn  4653:         if ($context eq 'toollogo') {
                   4654:             my ($fullwidth,$fullheight) = &check_dimensions($input);
                   4655:             if ($fullwidth ne '' && $fullheight ne '') {
                   4656:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
                   4657:                     $makethumb = 1;
                   4658:                 }
                   4659:             }
                   4660:         } else {
                   4661:             $makethumb = 1;
                   4662:         }
                   4663:         if ($makethumb) {
                   4664:             my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4665:             system({$args[0]} @args);
                   4666:             if (-e $filepath.'/'.'tn-'.$file) {
                   4667:                 $fetchthumb  = 1; 
                   4668:             }
1.860     raeburn  4669:         }
                   4670:     }
1.858     raeburn  4671:  
1.259     www      4672: # Notify homeserver to grep it
                   4673: #
1.984     neumanie 4674:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4675:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4676:     if ($fetchresult eq 'ok') {
1.860     raeburn  4677:         if ($fetchthumb) {
                   4678:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4679:             if ($thumbresult ne 'ok') {
                   4680:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4681:                          $docuhome.': '.$thumbresult);
                   4682:             }
                   4683:         }
1.259     www      4684: #
1.258     www      4685: # Return the URL to it
1.494     albertel 4686:         return '/uploaded/'.$path.$file;
1.263     www      4687:     } else {
1.494     albertel 4688:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4689: 		 ': '.$fetchresult);
1.263     www      4690:         return '/adm/notfound.html';
1.858     raeburn  4691:     }
1.493     albertel 4692: }
                   4693: 
1.637     raeburn  4694: sub extract_embedded_items {
1.961     raeburn  4695:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4696:     my @state = ();
1.1164    raeburn  4697:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4698:     my %javafiles = (
                   4699:                       codebase => '',
                   4700:                       code => '',
                   4701:                       archive => ''
                   4702:                     );
                   4703:     my %mediafiles = (
                   4704:                       src => '',
                   4705:                       movie => '',
                   4706:                      );
1.648     raeburn  4707:     my $p;
                   4708:     if ($content) {
                   4709:         $p = HTML::LCParser->new($content);
                   4710:     } else {
1.961     raeburn  4711:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4712:     }
1.641     albertel 4713:     while (my $t=$p->get_token()) {
1.640     albertel 4714: 	if ($t->[0] eq 'S') {
                   4715: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4716: 	    push(@state, $tagname);
1.648     raeburn  4717:             if (lc($tagname) eq 'allow') {
                   4718:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4719:             }
1.640     albertel 4720: 	    if (lc($tagname) eq 'img') {
                   4721: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4722: 	    }
1.886     albertel 4723: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4724:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4725:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4726:                 }
1.886     albertel 4727: 	    }
1.645     raeburn  4728:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4729:                 my $src;
1.645     raeburn  4730:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4731:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4732:                 } else {
1.1164    raeburn  4733:                     if ($attr->{'src'} ne '') {
                   4734:                         $src = $attr->{'src'};
                   4735:                         &add_filetype($allfiles,$src,'src');
                   4736:                     }
                   4737:                 }
                   4738:                 my $text = $p->get_trimmed_text();
                   4739:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4740:                     my @swfargs = split(/,/,$1);
                   4741:                     foreach my $item (@swfargs) {
                   4742:                         $item =~ s/["']//g;
                   4743:                         $item =~ s/^\s+//;
                   4744:                         $item =~ s/\s+$//;
                   4745:                     }
                   4746:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4747:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4748:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4749:                         } else {
                   4750:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4751:                         }
                   4752:                     }
1.645     raeburn  4753:                 }
                   4754:             }
                   4755:             if (lc($tagname) eq 'link') {
                   4756:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4757:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4758:                 }
                   4759:             }
1.640     albertel 4760: 	    if (lc($tagname) eq 'object' ||
                   4761: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4762: 		foreach my $item (keys(%javafiles)) {
                   4763: 		    $javafiles{$item} = '';
                   4764: 		}
1.1164    raeburn  4765:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4766:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4767:                 }
1.640     albertel 4768: 	    }
                   4769: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4770: 		my $name = lc($attr->{'name'});
                   4771: 		foreach my $item (keys(%javafiles)) {
                   4772: 		    if ($name eq $item) {
                   4773: 			$javafiles{$item} = $attr->{'value'};
                   4774: 			last;
                   4775: 		    }
                   4776: 		}
1.1164    raeburn  4777:                 my $pathfrom;
1.640     albertel 4778: 		foreach my $item (keys(%mediafiles)) {
                   4779: 		    if ($name eq $item) {
1.1164    raeburn  4780:                         $pathfrom = $attr->{'value'};
                   4781:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4782: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4783: 			last;
                   4784: 		    }
                   4785: 		}
1.1164    raeburn  4786:                 if ($name eq 'flashvars') {
                   4787:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4788:                 }
                   4789:                 if ($pathfrom ne '') {
                   4790:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4791:                                          $pathfrom);
                   4792:                 }
1.640     albertel 4793: 	    }
                   4794: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4795: 		foreach my $item (keys(%javafiles)) {
                   4796: 		    if ($attr->{$item}) {
                   4797: 			$javafiles{$item} = $attr->{$item};
                   4798: 			last;
                   4799: 		    }
                   4800: 		}
                   4801: 		foreach my $item (keys(%mediafiles)) {
                   4802: 		    if ($attr->{$item}) {
                   4803: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4804: 			last;
                   4805: 		    }
                   4806: 		}
1.1164    raeburn  4807:                 if (lc($tagname) eq 'embed') {
                   4808:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4809:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4810:                                              $attr->{'src'});
                   4811:                     }
                   4812:                 }
1.640     albertel 4813: 	    }
1.1243    raeburn  4814:             if (lc($tagname) eq 'iframe') {
                   4815:                 my $src = $attr->{'src'} ;
                   4816:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4817:                     &add_filetype($allfiles,$src,'src');
                   4818:                 } elsif ($src =~ m{^/}) {
                   4819:                     if ($env{'request.course.id'}) {
                   4820:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4821:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4822:                         my $url = &hreflocation('',$fullpath);
                   4823:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4824:                             my $relpath = $1;
                   4825:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4826:                                 &add_filetype($allfiles,$1,'src');
                   4827:                             }
                   4828:                         }
                   4829:                     }
                   4830:                 }
                   4831:             }
1.1164    raeburn  4832:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4833:                 pop(@state);
1.1164    raeburn  4834:             }
1.640     albertel 4835: 	} elsif ($t->[0] eq 'E') {
                   4836: 	    my ($tagname) = ($t->[1]);
                   4837: 	    if ($javafiles{'codebase'} ne '') {
                   4838: 		$javafiles{'codebase'} .= '/';
                   4839: 	    }  
                   4840: 	    if (lc($tagname) eq 'applet' ||
                   4841: 		lc($tagname) eq 'object' ||
                   4842: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4843: 		) {
                   4844: 		foreach my $item (keys(%javafiles)) {
                   4845: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4846: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4847: 			&add_filetype($allfiles,$file,$item);
                   4848: 		    }
                   4849: 		}
                   4850: 	    } 
                   4851: 	    pop @state;
                   4852: 	}
                   4853:     }
1.1164    raeburn  4854:     foreach my $id (sort(keys(%flashvars))) {
                   4855:         if ($shockwave{$id} ne '') {
                   4856:             my @pairs = split(/\&/,$flashvars{$id});
                   4857:             foreach my $pair (@pairs) {
                   4858:                 my ($key,$value) = split(/\=/,$pair);
                   4859:                 if ($key eq 'thumb') {
                   4860:                     &add_filetype($allfiles,$value,$key);
                   4861:                 } elsif ($key eq 'content') {
                   4862:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4863:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4864:                     if ($ext ne '') {
                   4865:                         &add_filetype($allfiles,$path.$value,$ext);
                   4866:                     }
                   4867:                 }
                   4868:             }
                   4869:         }
                   4870:     }
1.637     raeburn  4871:     return 'ok';
                   4872: }
                   4873: 
1.639     albertel 4874: sub add_filetype {
                   4875:     my ($allfiles,$file,$type)=@_;
                   4876:     if (exists($allfiles->{$file})) {
                   4877: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4878: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4879: 	}
                   4880:     } else {
                   4881: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4882:     }
                   4883: }
                   4884: 
1.1164    raeburn  4885: sub embedded_dependency {
                   4886:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4887:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4888:         if (($identifier ne '') &&
                   4889:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4890:             ($pathfrom ne '')) {
                   4891:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4892:             foreach my $dep (@{$related->{$identifier}}) {
                   4893:                 &add_filetype($allfiles,$path.$dep,'object');
                   4894:             }
                   4895:         }
                   4896:     }
                   4897:     return;
                   4898: }
                   4899: 
1.1504    raeburn  4900: sub check_dimensions {
                   4901:     my ($inputfile) = @_;
                   4902:     my ($fullwidth,$fullheight);
                   4903:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
                   4904:         my $mm = new File::MMagic;
                   4905:         my $mime_type = $mm->checktype_filename($inputfile);
                   4906:         if ($mime_type =~ m{^image/}) {
                   4907:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
                   4908:                 my $imageinfo = <PIPE>;
                   4909:                 if (!close(PIPE)) {
                   4910:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
                   4911:                 }
                   4912:                 chomp($imageinfo);
                   4913:                 my ($fullsize) =
                   4914:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
                   4915:                 if ($fullsize) {
                   4916:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
                   4917:                 }
                   4918:             }
                   4919:         }
                   4920:     }
                   4921:     return ($fullwidth,$fullheight);
                   4922: }
                   4923: 
1.1401    raeburn  4924: sub bubblesheet_converter {
                   4925:     my ($cdom,$fullpath,$config,$format) = @_;
                   4926:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4927:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4928:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4929:         my (%csvcols,%csvoptions);
                   4930:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4931:             %csvcols = %{$config->{'fields'}};
                   4932:         }
                   4933:         if (ref($config->{'options'}) eq 'HASH') {
                   4934:             %csvoptions = %{$config->{'options'}};
                   4935:         }
1.1401    raeburn  4936:         my %csvbynum = reverse(%csvcols);
                   4937:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4938:         if (keys(%scantronconf)) {
                   4939:             my %bynum = (
                   4940:                           $scantronconf{CODEstart} => 'CODEstart',
                   4941:                           $scantronconf{IDstart}   => 'IDstart',
                   4942:                           $scantronconf{PaperID}   => 'PaperID',
                   4943:                           $scantronconf{FirstName} => 'FirstName',
                   4944:                           $scantronconf{LastName}  => 'LastName',
                   4945:                           $scantronconf{Qstart}    => 'Qstart',
                   4946:                         );
                   4947:             my @ordered;
                   4948:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4949:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4950:             }
                   4951:             my %mapstart = (
                   4952:                               CODEstart => 'CODE',
                   4953:                               IDstart   => 'ID',
                   4954:                               PaperID   => 'PaperID',
                   4955:                               FirstName => 'FirstName',
                   4956:                               LastName  => 'LastName',
                   4957:                               Qstart    => 'FirstQuestion',
                   4958:                            );
                   4959:             my %maplength = (
                   4960:                               CODEstart => 'CODElength',
                   4961:                               IDstart   => 'IDlength',
                   4962:                               PaperID   => 'PaperIDlength',
                   4963:                               FirstName => 'FirstNamelength',
                   4964:                               LastName  => 'LastNamelength',
                   4965:             );
                   4966:             if (open(my $fh,'<',$fullpath)) {
                   4967:                 my $output;
1.1403    raeburn  4968:                 my %lettdig = &letter_to_digits();
                   4969:                 my %diglett = reverse(%lettdig);
                   4970:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4971:                 my $num = 0;
1.1401    raeburn  4972:                 while (my $line=<$fh>) {
1.1404    raeburn  4973:                     $num ++;
                   4974:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4975:                     $line =~ s{[\r\n]+$}{};
                   4976:                     my %found;
1.1475    raeburn  4977:                     my @values = split(/,/,$line,-1);
1.1401    raeburn  4978:                     my ($qstart,$record);
                   4979:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4980:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4981:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4982:                             if ($values[$i] eq '') {
                   4983:                                 $values[$i] = $scantronconf{'Qoff'};
                   4984:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4985:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4986:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4987:                                 }
                   4988:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4989:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4990:                                     $values[$i] = $diglett{$values[$i]};
                   4991:                                 }
                   4992:                             } else {
                   4993:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4994:                                     my $digit;
                   4995:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4996:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4997:                                         if ($values[$i] eq 'J') {
                   4998:                                             $digit += $numletts;
                   4999:                                         }
                   5000:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   5001:                                         $digit = $values[$i]-1;
                   5002:                                         if ($values[$i] eq '0') {
                   5003:                                             $digit += $numletts;
                   5004:                                         }
                   5005:                                     }
                   5006:                                     my $qval='';
                   5007:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   5008:                                         if ($j == $digit) {
                   5009:                                             $qval .= $scantronconf{'Qon'};
                   5010:                                         } else {
                   5011:                                             $qval .= $scantronconf{'Qoff'};
                   5012:                                         }
                   5013:                                     }
                   5014:                                     $values[$i] = $qval;
                   5015:                                 }
                   5016:                             }
                   5017:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   5018:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   5019:                             }
                   5020:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   5021:                             if ($numblank > 0) {
                   5022:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   5023:                             }
1.1401    raeburn  5024:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   5025:                                 $qstart = $i;
1.1403    raeburn  5026:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  5027:                             } else {
1.1403    raeburn  5028:                                 $found{'FirstQuestion'} .= $values[$i];
                   5029:                             }
                   5030:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  5031:                             if ($csvoptions{'rem'}) {
                   5032:                                 $values[$i] =~ s/^\s+//;
                   5033:                             }
                   5034:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  5035:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   5036:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  5037:                                 }
                   5038:                             }
                   5039:                             $found{$csvbynum{$i}} = $values[$i];
                   5040:                         }
                   5041:                     }
                   5042:                     foreach my $item (@ordered) {
                   5043:                         my $currlength = 1+length($record);
                   5044:                         my $numspaces = $scantronconf{$item} - $currlength;
                   5045:                         if ($numspaces > 0) {
                   5046:                             $record .= (' ' x $numspaces);
                   5047:                         }
                   5048:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   5049:                             unless ($item eq 'Qstart') {
                   5050:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   5051:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   5052:                                 }
                   5053:                             }
                   5054:                             $record .= $found{$mapstart{$item}};
                   5055:                         }
                   5056:                     }
                   5057:                     $output .= "$record\n";
                   5058:                 }
                   5059:                 close($fh);
                   5060:                 if ($output) {
                   5061:                     if (open(my $fh,'>',$fullpath)) {
                   5062:                         print $fh $output;
                   5063:                         close($fh);
                   5064:                     }
                   5065:                 }
                   5066:             }
                   5067:         }
                   5068:         return;
                   5069:     }
                   5070: }
                   5071: 
1.1403    raeburn  5072: sub letter_to_digits {
                   5073:     my %lettdig = (
                   5074:                     A => 1,
                   5075:                     B => 2,
                   5076:                     C => 3,
                   5077:                     D => 4,
                   5078:                     E => 5,
                   5079:                     F => 6,
                   5080:                     G => 7,
                   5081:                     H => 8,
                   5082:                     I => 9,
                   5083:                     J => 0,
                   5084:                   );
                   5085:     return %lettdig;
                   5086: }
                   5087: 
1.1401    raeburn  5088: sub get_scantron_config {
                   5089:     my ($which,$cdom) = @_;
                   5090:     my @lines = &get_scantronformat_file($cdom);
                   5091:     my %config;
                   5092:     #FIXME probably should move to XML it has already gotten a bit much now
                   5093:     foreach my $line (@lines) {
                   5094:         my ($name,$descrip)=split(/:/,$line);
                   5095:         if ($name ne $which ) { next; }
                   5096:         chomp($line);
                   5097:         my @config=split(/:/,$line);
                   5098:         $config{'name'}=$config[0];
                   5099:         $config{'description'}=$config[1];
                   5100:         $config{'CODElocation'}=$config[2];
                   5101:         $config{'CODEstart'}=$config[3];
                   5102:         $config{'CODElength'}=$config[4];
                   5103:         $config{'IDstart'}=$config[5];
                   5104:         $config{'IDlength'}=$config[6];
                   5105:         $config{'Qstart'}=$config[7];
                   5106:         $config{'Qlength'}=$config[8];
                   5107:         $config{'Qoff'}=$config[9];
                   5108:         $config{'Qon'}=$config[10];
                   5109:         $config{'PaperID'}=$config[11];
                   5110:         $config{'PaperIDlength'}=$config[12];
                   5111:         $config{'FirstName'}=$config[13];
                   5112:         $config{'FirstNamelength'}=$config[14];
                   5113:         $config{'LastName'}=$config[15];
                   5114:         $config{'LastNamelength'}=$config[16];
                   5115:         $config{'BubblesPerRow'}=$config[17];
                   5116:         last;
                   5117:     }
                   5118:     return %config;
                   5119: }
                   5120: 
                   5121: sub get_scantronformat_file {
                   5122:     my ($cdom) = @_;
                   5123:     if ($cdom eq '') {
                   5124:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5125:     }
                   5126:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   5127:     my $gottab = 0;
                   5128:     my @lines;
                   5129:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5130:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5131:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5132:             if ($formatfile ne '-1') {
                   5133:                 @lines = split("\n",$formatfile,-1);
                   5134:                 $gottab = 1;
                   5135:             }
                   5136:         }
                   5137:     }
                   5138:     if (!$gottab) {
                   5139:         my $confname = $cdom.'-domainconfig';
                   5140:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5141:         my $formatfile = &getfile($default);
                   5142:         if ($formatfile ne '-1') {
                   5143:             @lines = split("\n",$formatfile,-1);
                   5144:             $gottab = 1;
                   5145:         }
                   5146:     }
                   5147:     if (!$gottab) {
                   5148:         my @domains = &current_machine_domains();
                   5149:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5150:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   5151:                 @lines = <$fh>;
                   5152:                 close($fh);
1.1403    raeburn  5153:             }
1.1401    raeburn  5154:         } else {
                   5155:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   5156:                 @lines = <$fh>;
                   5157:                 close($fh);
                   5158:             }
                   5159:         }
1.1488    raeburn  5160:         chomp(@lines);
1.1401    raeburn  5161:     }
                   5162:     return @lines;
                   5163: }
                   5164: 
1.493     albertel 5165: sub removeuploadedurl {
1.984     neumanie 5166:     my ($url)=@_;	
                   5167:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 5168:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 5169: }
                   5170: 
                   5171: sub removeuserfile {
                   5172:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 5173:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  5174:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 5175:     if ($result eq 'ok') {	
1.798     raeburn  5176:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   5177:             my $metafile = $fname.'.meta';
                   5178:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 5179: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 5180:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  5181:             my $sqlresult = 
1.823     albertel 5182:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  5183:                                         'portfolio_metadata',$group,
                   5184:                                         'delete');
1.798     raeburn  5185:         }
                   5186:     }
                   5187:     return $result;
1.257     www      5188: }
1.15      www      5189: 
1.530     albertel 5190: sub mkdiruserfile {
                   5191:     my ($docuname,$docudom,$dir)=@_;
                   5192:     my $home=&homeserver($docuname,$docudom);
                   5193:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   5194: }
                   5195: 
1.531     albertel 5196: sub renameuserfile {
                   5197:     my ($docuname,$docudom,$old,$new)=@_;
                   5198:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  5199:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   5200:                         &escape("$old").':'.&escape("$new"),$home);
                   5201:     if ($result eq 'ok') {
                   5202:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   5203:             my $oldmeta = $old.'.meta';
                   5204:             my $newmeta = $new.'.meta';
                   5205:             my $metaresult = 
                   5206:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 5207: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   5208:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  5209:             my $sqlresult = 
1.823     albertel 5210:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  5211:                                         'portfolio_metadata',$group,
                   5212:                                         'delete');
1.798     raeburn  5213:         }
                   5214:     }
                   5215:     return $result;
1.531     albertel 5216: }
                   5217: 
1.14      www      5218: # ------------------------------------------------------------------------- Log
                   5219: 
                   5220: sub log {
                   5221:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      5222:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      5223: }
                   5224: 
                   5225: # ------------------------------------------------------------------ Course Log
1.352     www      5226: #
                   5227: # This routine flushes several buffers of non-mission-critical nature
                   5228: #
1.157     www      5229: 
                   5230: sub flushcourselogs {
1.352     www      5231:     &logthis('Flushing log buffers');
                   5232: #
                   5233: # course logs
                   5234: # This is a log of all transactions in a course, which can be used
                   5235: # for data mining purposes
                   5236: #
                   5237: # It also collects the courseid database, which lists last transaction
                   5238: # times and course titles for all courseids
                   5239: #
                   5240:     my %courseidbuffer=();
1.921     raeburn  5241:     foreach my $crsid (keys(%courselogs)) {
1.352     www      5242:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      5243: 		          &escape($courselogs{$crsid}),
                   5244: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      5245: 	    delete $courselogs{$crsid};
                   5246:         } else {
                   5247:             &logthis('Failed to flush log buffer for '.$crsid);
                   5248:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 5249:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      5250:                         " exceeded maximum size, deleting.</font>");
                   5251:                delete $courselogs{$crsid};
                   5252:             }
1.352     www      5253:         }
1.920     raeburn  5254:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  5255:             'description' => $coursedescrbuf{$crsid},
                   5256:             'inst_code'    => $courseinstcodebuf{$crsid},
                   5257:             'type'        => $coursetypebuf{$crsid},
                   5258:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  5259:         };
1.191     harris41 5260:     }
1.352     www      5261: #
                   5262: # Write course id database (reverse lookup) to homeserver of courses 
                   5263: # Is used in pickcourse
                   5264: #
1.840     albertel 5265:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  5266:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  5267:                                     $courseidbuffer{$crs_home},
                   5268:                                     $crs_home,'timeonly');
1.352     www      5269:     }
                   5270: #
                   5271: # File accesses
                   5272: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   5273: #
1.449     matthew  5274:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  5275:         if ($entry =~ /___count$/) {
                   5276:             my ($dom,$name);
1.807     albertel 5277:             ($dom,$name,undef)=
1.811     albertel 5278: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  5279:             if (! defined($dom) || $dom eq '' || 
                   5280:                 ! defined($name) || $name eq '') {
1.620     albertel 5281:                 my $cid = $env{'request.course.id'};
1.1472    raeburn  5282: #
                   5283: # FIXME 11/29/2021
                   5284: # Typo in rev. 1.458 (2003/12/09)??
                   5285: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   5286: #
1.1509    raeburn  5287: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1472    raeburn  5288: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   5289: # in a nohist_accesscount.db file for the user rather than the course.
                   5290: #
                   5291: # That said there is a lot of noise in the data being stored.
                   5292: # So counts for prtspool/  and adm/ etc. are recorded.
                   5293: #
                   5294: # A review of which items ending '___count' are written to %accesshash should likely be 
                   5295: # made before deciding whether to set these to 'course.' instead of 'request.'
                   5296: #
                   5297: # Under the current scheme each user receives a nohist_accesscount.db file listing 
                   5298: # accesses for things which are not published resources, regardless of course, and
                   5299: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   5300: # anyone in the course for things which are not published resources.
                   5301: #
                   5302: # For an author, nohist_accesscount.db ends up having records for other items
                   5303: # mixed up with the legitimate access counts for the author's published resources.
                   5304: #
1.620     albertel 5305:                 $dom  = $env{'request.'.$cid.'.domain'};
                   5306:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  5307:             }
1.450     matthew  5308:             my $value = $accesshash{$entry};
                   5309:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   5310:             my %temphash=($url => $value);
1.449     matthew  5311:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   5312:             if ($result eq 'ok') {
                   5313:                 delete $accesshash{$entry};
                   5314:             }
                   5315:         } else {
1.811     albertel 5316:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      5317:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  5318:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  5319:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   5320:                 delete $accesshash{$entry};
                   5321:             }
1.185     www      5322:         }
1.191     harris41 5323:     }
1.352     www      5324: #
                   5325: # Roles
                   5326: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   5327: #
1.800     albertel 5328:     foreach my $entry (keys(%userrolehash)) {
1.351     www      5329:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      5330: 	    split(/\:/,$entry);
1.1494    raeburn  5331:         if (&put('nohist_userroles',
1.351     www      5332:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      5333:                 $rudom,$runame) eq 'ok') {
                   5334: 	    delete $userrolehash{$entry};
                   5335:         }
                   5336:     }
1.662     raeburn  5337: #
1.1334    raeburn  5338: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5339: #
                   5340:     my %domrolebuffer = ();
1.1000    raeburn  5341:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5342:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5343:         if ($domrolebuffer{$rudom}) {
                   5344:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5345:                       '='.&escape($domainrolehash{$entry});
                   5346:         } else {
                   5347:             $domrolebuffer{$rudom}.=&escape($entry).
                   5348:                       '='.&escape($domainrolehash{$entry});
                   5349:         }
                   5350:         delete $domainrolehash{$entry};
                   5351:     }
                   5352:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  5353: 	my %servers;
                   5354: 	if (defined(&domain($dom,'primary'))) {
                   5355: 	    my $primary=&domain($dom,'primary');
                   5356: 	    my $hostname=&hostname($primary);
                   5357: 	    $servers{$primary} = $hostname;
                   5358: 	} else { 
                   5359: 	    %servers = &get_servers($dom,'library');
                   5360: 	}
1.841     albertel 5361: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  5362: 	    if (&reply('domroleput:'.$dom.':'.
                   5363: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5364: 		last;
                   5365: 	    } else {  
1.841     albertel 5366: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5367: 	    }
1.662     raeburn  5368:         }
                   5369:     }
1.186     www      5370:     $dumpcount++;
1.157     www      5371: }
                   5372: 
                   5373: sub courselog {
                   5374:     my $what=shift;
1.158     www      5375:     $what=time.':'.$what;
1.620     albertel 5376:     unless ($env{'request.course.id'}) { return ''; }
                   5377:     $coursedombuf{$env{'request.course.id'}}=
                   5378:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5379:     $coursenumbuf{$env{'request.course.id'}}=
                   5380:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5381:     $coursehombuf{$env{'request.course.id'}}=
                   5382:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5383:     $coursedescrbuf{$env{'request.course.id'}}=
                   5384:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5385:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5386:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5387:     $courseownerbuf{$env{'request.course.id'}}=
                   5388:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5389:     $coursetypebuf{$env{'request.course.id'}}=
                   5390:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5391:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5392: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5393:     } else {
1.620     albertel 5394: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5395:     }
1.620     albertel 5396:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5397: 	&flushcourselogs();
                   5398:     }
1.158     www      5399: }
                   5400: 
                   5401: sub courseacclog {
                   5402:     my $fnsymb=shift;
1.620     albertel 5403:     unless ($env{'request.course.id'}) { return ''; }
                   5404:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5405:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5406:         $what.=':POST';
1.583     matthew  5407:         # FIXME: Probably ought to escape things....
1.800     albertel 5408: 	foreach my $key (keys(%env)) {
                   5409:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5410:                 my $formitem = $1;
                   5411:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5412:                     $what.=':'.$formitem.'='.$env{$key};
                   5413:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5414:                     if ($formitem eq 'proctorpassword') {
1.1433    raeburn  5415:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5416:                     } else {
                   5417:                         $what.=':'.$formitem.'='.$env{$key};
                   5418:                     }
1.975     raeburn  5419:                 }
1.158     www      5420:             }
1.191     harris41 5421:         }
1.583     matthew  5422:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5423:         # FIXME: We should not be depending on a form parameter that someone
                   5424:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5425:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5426:             $what.= ':POST';
                   5427:             # FIXME: Probably ought to escape things....
                   5428:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5429:                                  'crsdiscuss') {
1.620     albertel 5430:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5431:             }
                   5432:         }
1.158     www      5433:     }
                   5434:     &courselog($what);
1.149     www      5435: }
                   5436: 
1.185     www      5437: sub countacc {
                   5438:     my $url=&declutter(shift);
1.458     matthew  5439:     return if (! defined($url) || $url eq '');
1.620     albertel 5440:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5441: #
                   5442: # Mark that this url was used in this course
                   5443: #
1.620     albertel 5444:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5445: #
                   5446: # Increase the access count for this resource in this child process
                   5447: #
1.281     www      5448:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5449:     $accesshash{$key}++;
1.185     www      5450: }
1.349     www      5451: 
1.361     www      5452: sub linklog {
                   5453:     my ($from,$to)=@_;
                   5454:     $from=&declutter($from);
                   5455:     $to=&declutter($to);
                   5456:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5457:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5458: }
1.1160    www      5459: 
                   5460: sub statslog {
                   5461:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5462:     if ($users<2) { return; }
                   5463:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5464:             'course'       => $env{'request.course.id'},
                   5465:             'sections'     => '"all"',
                   5466:             'num_students' => $users,
                   5467:             'part'         => $part,
                   5468:             'symb'         => $symb,
                   5469:             'mean_tries'   => $av_attempts,
                   5470:             'deg_of_diff'  => $degdiff});
                   5471:     foreach my $key (keys(%dynstore)) {
                   5472:         $accesshash{$key}=$dynstore{$key};
                   5473:     }
                   5474: }
1.361     www      5475:   
1.349     www      5476: sub userrolelog {
                   5477:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5478:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5479:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5480:        $userrolehash
                   5481:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5482:                     =$tend.':'.$tstart;
1.662     raeburn  5483:     }
1.1169    droeschl 5484:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5485:        $userrolehash
                   5486:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5487:                     =$tend.':'.$tstart;
                   5488:     }
1.1334    raeburn  5489:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5490:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5491:        $domainrolehash
                   5492:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5493:                     = $tend.':'.$tstart;
                   5494:     }
1.351     www      5495: }
                   5496: 
1.957     raeburn  5497: sub courserolelog {
1.1512    raeburn  5498:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
                   5499:         $context,$othdomby,$requester)=@_;
1.1184    raeburn  5500:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5501:         my $cdom = $1;
                   5502:         my $cnum = $2;
                   5503:         my $sec = $3;
                   5504:         my $namespace = 'rolelog';
                   5505:         my %storehash = (
                   5506:                            role    => $trole,
                   5507:                            start   => $tstart,
                   5508:                            end     => $tend,
                   5509:                            selfenroll => $selfenroll,
                   5510:                            context    => $context,
                   5511:                         );
1.1512    raeburn  5512:         if ($othdomby) {
                   5513:             if ($othdomby eq 'othdombydc') {
                   5514:                 $storehash{'approval'} = 'domain';
                   5515:             } elsif ($othdomby eq 'othdombyuser') {
                   5516:                 $storehash{'approval'} = 'user'; 
                   5517:             }
                   5518:             if ($requester ne '') {
                   5519:                 $storehash{'requester'} = $requester;
                   5520:             }
                   5521:         }
1.1184    raeburn  5522:         if ($trole eq 'gr') {
                   5523:             $namespace = 'groupslog';
                   5524:             $storehash{'group'} = $sec;
                   5525:         } else {
                   5526:             $storehash{'section'} = $sec;
1.1516    raeburn  5527:             my ($curruserdomstr,$newuserdomstr);
1.1515    raeburn  5528:             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
                   5529:                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
1.1516    raeburn  5530:             } else {
1.1515    raeburn  5531:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
                   5532:                 $curruserdomstr = $courseinfo{'internal.userdomains'};
                   5533:             }
1.1516    raeburn  5534:             if ($curruserdomstr ne '') {
                   5535:                 my @udoms = split(/,/,$curruserdomstr);
1.1515    raeburn  5536:                 unless (grep(/^\Q$domain\E/,@udoms)) {
                   5537:                     push(@udoms,$domain);
                   5538:                     $newuserdomstr = join(',',sort(@udoms));
                   5539:                 }
                   5540:             } else {
                   5541:                 $newuserdomstr = $domain;
                   5542:             }
                   5543:             if ($newuserdomstr ne '') {
                   5544:                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
                   5545:                                      $cdom,$cnum);
                   5546:                 if ($putresult eq 'ok') {
                   5547:                     unless (($selfenroll) || ($context eq 'selfenroll')) { 
                   5548:                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
                   5549:                             ($context eq 'automated') || ($context eq 'domain')) {
                   5550:                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
                   5551:                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   5552:                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
                   5553:                         }
                   5554:                     }
                   5555:                 }
                   5556:             }
1.1184    raeburn  5557:         }
1.1188    raeburn  5558:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5559:                    $domain,$cnum,$cdom);
1.1184    raeburn  5560:         if (($trole ne 'st') || ($sec ne '')) {
                   5561:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5562:         }
                   5563:     }
                   5564:     return;
                   5565: }
                   5566: 
1.1184    raeburn  5567: sub domainrolelog {
1.1512    raeburn  5568:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
                   5569:         $context,$othdomby,$requester)=@_;
1.1184    raeburn  5570:     if ($area =~ m{^/($match_domain)/$}) {
                   5571:         my $cdom = $1;
1.1494    raeburn  5572:         my $domconfiguser = &get_domainconfiguser($cdom);
1.1184    raeburn  5573:         my $namespace = 'rolelog';
                   5574:         my %storehash = (
                   5575:                            role    => $trole,
                   5576:                            start   => $tstart,
                   5577:                            end     => $tend,
                   5578:                            context => $context,
                   5579:                         );
1.1512    raeburn  5580:         if ($othdomby) {
                   5581:             if ($othdomby eq 'othdombydc') {
                   5582:                 $storehash{'approval'} = 'domain';
                   5583:             } elsif ($othdomby eq 'othdombyuser') {
                   5584:                 $storehash{'approval'} = 'user';
                   5585:             }
                   5586:             if ($requester ne '') {
                   5587:                 $storehash{'requester'} = $requester;
                   5588:             }
                   5589:         }
1.1188    raeburn  5590:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5591:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5592:     }
                   5593:     return;
                   5594: 
                   5595: }
                   5596: 
                   5597: sub coauthorrolelog {
1.1512    raeburn  5598:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
                   5599:         $context,$othdomby,$requester)=@_;
1.1184    raeburn  5600:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5601:         my $audom = $1;
                   5602:         my $auname = $2;
                   5603:         my $namespace = 'rolelog';
                   5604:         my %storehash = (
                   5605:                            role    => $trole,
                   5606:                            start   => $tstart,
                   5607:                            end     => $tend,
                   5608:                            context => $context,
                   5609:                         );
1.1512    raeburn  5610:         if ($othdomby) {
                   5611:             if ($othdomby eq 'othdombydc') {
                   5612:                 $storehash{'approval'} = 'domain';
                   5613:             } elsif ($othdomby eq 'othdombyuser') {
                   5614:                 $storehash{'approval'} = 'user';
                   5615:             }
                   5616:             if ($requester ne '') {
                   5617:                 $storehash{'requester'} = $requester;
                   5618:             }
                   5619:         }
1.1188    raeburn  5620:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5621:                    $domain,$auname,$audom);
1.1184    raeburn  5622:     }
                   5623:     return;
                   5624: }
                   5625: 
1.1527  ! raeburn  5626: sub authorarchivelog {
        !          5627:     my ($hashref,$size,$filesdest,$action) = @_;
        !          5628:     my $lonprtdir = $Apache::lonnet::perlvar{'lonPrtDir'};
        !          5629:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
        !          5630:     $filesdest =~ s{^\Q$lonprtdir/\E}{};
        !          5631:     if ($filesdest =~ m{^($match_username)_($match_domain)_archive_(\d+_\d+_\d+(|[.\w]+))$}) {
        !          5632:         my ($auname,$audom,$id) = ($1,$2,$3);
        !          5633:         if (ref($hashref) eq 'HASH') {
        !          5634:             my $namespace = 'archivelog';
        !          5635:             my $dir;
        !          5636:             if ($hashref->{dir} =~ m{^\Q$londocroot/priv/$audom/$auname\E(.*)$}) {
        !          5637:                 $dir = $1;
        !          5638:             }
        !          5639:             my $delflag = 0;
        !          5640:             my %storehash = (
        !          5641:                               id      => $id,
        !          5642:                               dir     => $dir,
        !          5643:                               files   => $hashref->{numfiles},
        !          5644:                               subdirs => $hashref->{numdirs},
        !          5645:                               bytes   => $hashref->{bytes},
        !          5646:                               size    => $size,
        !          5647:                               action  => $action,
        !          5648:                             );
        !          5649:             if ($action eq 'delete') {
        !          5650:                 $delflag = 1;
        !          5651:             }
        !          5652:             &write_log('author',$namespace,\%storehash,$delflag,$auname,
        !          5653:                        $audom,$auname,$audom);
        !          5654:         }
        !          5655:     }
        !          5656:     return;
        !          5657: }
        !          5658: 
1.351     www      5659: sub get_course_adv_roles {
1.948     raeburn  5660:     my ($cid,$codes) = @_;
1.620     albertel 5661:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5662:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5663:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5664:     my %nothide=();
1.800     albertel 5665:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5666:         if ($user !~ /:/) {
                   5667: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5668:         } else {
                   5669:             $nothide{$user}=1;
                   5670:         }
1.470     www      5671:     }
1.1219    raeburn  5672:     my @possdoms = ($coursehash{'domain'});
                   5673:     if ($coursehash{'checkforpriv'}) {
                   5674:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5675:     }
1.351     www      5676:     my %returnhash=();
                   5677:     my %dumphash=
                   5678:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5679:     my $now=time;
1.997     raeburn  5680:     my %privileged;
1.1000    raeburn  5681:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5682: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5683:         if (($tstart) && ($tstart<0)) { next; }
                   5684:         if (($tend) && ($tend<$now)) { next; }
                   5685:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5686:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5687: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5688:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5689:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5690: 	if ($role eq 'cr') { next; }
1.948     raeburn  5691:         if ($codes) {
                   5692:             if ($section) { $role .= ':'.$section; }
                   5693:             if ($returnhash{$role}) {
                   5694:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5695:             } else {
                   5696:                 $returnhash{$role}=$username.':'.$domain;
                   5697:             }
1.351     www      5698:         } else {
1.988     raeburn  5699:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5700:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5701:             if ($returnhash{$key}) {
                   5702: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5703:             } else {
                   5704:                 $returnhash{$key}=$username.':'.$domain;
                   5705:             }
1.351     www      5706:         }
1.948     raeburn  5707:     }
1.400     www      5708:     return %returnhash;
                   5709: }
                   5710: 
                   5711: sub get_my_roles {
1.937     raeburn  5712:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5713:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5714:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5715:     my (%dumphash,%nothide);
1.1086    raeburn  5716:     if ($context eq 'userroles') {
1.1166    raeburn  5717:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5718:     } else {
1.1219    raeburn  5719:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5720:         if ($hidepriv) {
                   5721:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5722:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5723:                 if ($user !~ /:/) {
                   5724:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5725:                 } else {
                   5726:                     $nothide{$user} = 1;
                   5727:                 }
                   5728:             }
                   5729:         }
1.858     raeburn  5730:     }
1.400     www      5731:     my %returnhash=();
                   5732:     my $now=time;
1.999     raeburn  5733:     my %privileged;
1.800     albertel 5734:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5735:         my ($role,$tend,$tstart);
                   5736:         if ($context eq 'userroles') {
1.1149    raeburn  5737:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5738: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5739:         } else {
                   5740:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5741:         }
1.400     www      5742:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5743:         my $status = 'active';
1.939     raeburn  5744:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5745:             $status = 'previous';
                   5746:         } 
                   5747:         if (($tstart) && ($now<$tstart)) {
                   5748:             $status = 'future';
                   5749:         }
                   5750:         if (ref($types) eq 'ARRAY') {
                   5751:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5752:                 next;
                   5753:             } 
                   5754:         } else {
                   5755:             if ($status ne 'active') {
                   5756:                 next;
                   5757:             }
                   5758:         }
1.867     raeburn  5759:         my ($rolecode,$username,$domain,$section,$area);
                   5760:         if ($context eq 'userroles') {
1.1186    raeburn  5761:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5762:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5763:         } else {
                   5764:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5765:         }
1.832     raeburn  5766:         if (ref($roledoms) eq 'ARRAY') {
                   5767:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5768:                 next;
                   5769:             }
                   5770:         }
                   5771:         if (ref($roles) eq 'ARRAY') {
                   5772:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5773:                 if ($role =~ /^cr\//) {
                   5774:                     if (!grep(/^cr$/,@{$roles})) {
                   5775:                         next;
                   5776:                     }
1.1104    raeburn  5777:                 } elsif ($role =~ /^gr\//) {
                   5778:                     if (!grep(/^gr$/,@{$roles})) {
                   5779:                         next;
                   5780:                     }
1.922     raeburn  5781:                 } else {
                   5782:                     next;
                   5783:                 }
1.832     raeburn  5784:             }
1.867     raeburn  5785:         }
1.937     raeburn  5786:         if ($hidepriv) {
1.1219    raeburn  5787:             my @privroles = ('dc','su');
1.999     raeburn  5788:             if ($context eq 'userroles') {
1.1219    raeburn  5789:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5790:             } else {
1.1219    raeburn  5791:                 my $possdoms = [$domain];
                   5792:                 if (ref($roledoms) eq 'ARRAY') {
                   5793:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5794:                 }
1.1219    raeburn  5795:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5796:                     if (!$nothide{$username.':'.$domain}) {
                   5797:                         next;
                   5798:                     }
                   5799:                 }
1.937     raeburn  5800:             }
                   5801:         }
1.933     raeburn  5802:         if ($withsec) {
                   5803:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5804:                 $tstart.':'.$tend;
                   5805:         } else {
                   5806:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5807:         }
1.832     raeburn  5808:     }
1.373     www      5809:     return %returnhash;
1.399     www      5810: }
                   5811: 
1.1333    raeburn  5812: sub get_all_adhocroles {
                   5813:     my ($dom) = @_;
                   5814:     my @roles_by_num = ();
                   5815:     my %domdefaults = &get_domain_defaults($dom);
                   5816:     my (%description,%access_in_dom,%access_info);
                   5817:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5818:         my $count = 0;
                   5819:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5820:         my %ordered;
                   5821:         foreach my $role (sort(keys(%domcurrent))) {
                   5822:             my ($order,$desc,$access_in_dom);
                   5823:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5824:                 $order = $domcurrent{$role}{'order'};
                   5825:                 $desc = $domcurrent{$role}{'desc'};
                   5826:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5827:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5828:             }
                   5829:             if ($order eq '') {
                   5830:                 $order = $count;
                   5831:             }
                   5832:             $ordered{$order} = $role;
                   5833:             if ($desc ne '') {
                   5834:                 $description{$role} = $desc;
                   5835:             } else {
                   5836:                 $description{$role}= $role;
                   5837:             }
                   5838:             $count++;
                   5839:         }
                   5840:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5841:             push(@roles_by_num,$ordered{$item});
                   5842:         }
                   5843:     }
                   5844:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5845: }
                   5846: 
1.1332    raeburn  5847: sub get_my_adhocroles {
1.1333    raeburn  5848:     my ($cid,$checkreg) = @_;
                   5849:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5850:     if ($env{'request.course.id'} eq $cid) {
                   5851:         $cdom = $env{'course.'.$cid.'.domain'};
                   5852:         $cnum = $env{'course.'.$cid.'.num'};
                   5853:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5854:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5855:         $cdom = $1;
                   5856:         $cnum = $2;
1.1494    raeburn  5857:         %info = &get('environment',['internal.coursecode'],
                   5858:                      $cdom,$cnum);
1.1333    raeburn  5859:     }
                   5860:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5861:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5862:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5863:         if ($rosterhash{$user} ne '') {
                   5864:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5865:             return ([],{}) if ($type eq 'auto');
                   5866:         }
                   5867:     }
                   5868:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5869:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5870:             my $then=$env{'user.login.time'};
                   5871:             my $update=$env{'user.update.time'};
1.1335    raeburn  5872:             if (!$update) {
                   5873:                 $update = $then;
                   5874:             }
                   5875:             my @liveroles;
1.1334    raeburn  5876:             foreach my $role ('dh','da') {
                   5877:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5878:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5879:                     my $limit = $update;
                   5880:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5881:                         $limit = $then;
                   5882:                     }
1.1335    raeburn  5883:                     my $activerole = 1;
                   5884:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5885:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5886:                     if ($activerole) {
                   5887:                         push(@liveroles,$role);
                   5888:                     }
1.1334    raeburn  5889:                 }
1.1332    raeburn  5890:             }
1.1335    raeburn  5891:             if (@liveroles) {
1.1332    raeburn  5892:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5893:                     my ($accessref,$accessinfo,%access_in_dom);
                   5894:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5895:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5896:                         if (@{$roles_by_num}) {
1.1332    raeburn  5897:                             my %settings;
                   5898:                             if ($env{'request.course.id'} eq $cid) {
                   5899:                                 foreach my $envkey (keys(%env)) {
                   5900:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5901:                                         $settings{$1} = $env{$envkey};
                   5902:                                     }
                   5903:                                 }
                   5904:                             } else {
                   5905:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5906:                             }
                   5907:                             my %setincrs;
                   5908:                             if ($settings{'internal.adhocaccess'}) {
                   5909:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5910:                             }
                   5911:                             my @statuses;
                   5912:                             if ($env{'environment.inststatus'}) {
                   5913:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5914:                             }
                   5915:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5916:                             if (ref($accessref) eq 'HASH') {
                   5917:                                 %access_in_dom = %{$accessref};
                   5918:                             }
                   5919:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5920:                                 my ($curraccess,@okstatus,@personnel);
                   5921:                                 if ($setincrs{$role}) {
                   5922:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5923:                                     if ($curraccess eq 'status') {
                   5924:                                         @okstatus = split(/\&/,$rest);
                   5925:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5926:                                         @personnel = split(/\&/,$rest);
                   5927:                                     }
                   5928:                                 } else {
                   5929:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5930:                                     if (ref($accessinfo) eq 'HASH') {
                   5931:                                         if ($curraccess eq 'status') {
                   5932:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5933:                                                 @okstatus = @{$accessinfo->{$role}};
                   5934:                                             }
                   5935:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5936:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5937:                                                 @personnel = @{$accessinfo->{$role}};
                   5938:                                             }
1.1332    raeburn  5939:                                         }
                   5940:                                     }
                   5941:                                 }
                   5942:                                 if ($curraccess eq 'none') {
                   5943:                                     next;
                   5944:                                 } elsif ($curraccess eq 'all') {
                   5945:                                     push(@possroles,$role);
1.1336    raeburn  5946:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5947:                                     if (grep(/^dh$/,@liveroles)) {
                   5948:                                         push(@possroles,$role);
                   5949:                                     } else {
                   5950:                                         next;
                   5951:                                     }
1.1336    raeburn  5952:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5953:                                     if (grep(/^da$/,@liveroles)) {
                   5954:                                         push(@possroles,$role);
                   5955:                                     } else {
                   5956:                                         next;
                   5957:                                     }
1.1332    raeburn  5958:                                 } elsif ($curraccess eq 'status') {
                   5959:                                     if (@okstatus) {
                   5960:                                         if (!@statuses) {
                   5961:                                             if (grep(/^default$/,@okstatus)) {
                   5962:                                                 push(@possroles,$role);
                   5963:                                             }
                   5964:                                         } else {
                   5965:                                             foreach my $status (@okstatus) {
                   5966:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5967:                                                     push(@possroles,$role);
                   5968:                                                     last;
                   5969:                                                 }
                   5970:                                             }
                   5971:                                         }
                   5972:                                     }
                   5973:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5974:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5975:                                         if ($curraccess eq 'exc') {
                   5976:                                             push(@possroles,$role);
                   5977:                                         }
                   5978:                                     } elsif ($curraccess eq 'inc') {
                   5979:                                         push(@possroles,$role);
                   5980:                                     }
                   5981:                                 }
                   5982:                             }
                   5983:                         }
                   5984:                     }
                   5985:                 }
                   5986:             }
                   5987:         }
                   5988:     }
1.1333    raeburn  5989:     unless (ref($description) eq 'HASH') {
                   5990:         if (ref($roles_by_num) eq 'ARRAY') {
                   5991:             my %desc;
                   5992:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5993:             $description = \%desc;
                   5994:         } else {
                   5995:             $description = {};
                   5996:         }
                   5997:     }
                   5998:     return (\@possroles,$description);
1.1332    raeburn  5999: }
                   6000: 
1.399     www      6001: # ----------------------------------------------------- Frontpage Announcements
                   6002: #
                   6003: #
                   6004: 
                   6005: sub postannounce {
                   6006:     my ($server,$text)=@_;
1.844     albertel 6007:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      6008:     unless ($text=~/\w/) { $text=''; }
                   6009:     return &reply('setannounce:'.&escape($text),$server);
                   6010: }
                   6011: 
                   6012: sub getannounce {
1.448     albertel 6013: 
1.1359    raeburn  6014:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      6015: 	my $announcement='';
1.800     albertel 6016: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 6017: 	close($fh);
1.399     www      6018: 	if ($announcement=~/\w/) { 
                   6019: 	    return 
                   6020:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 6021:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      6022: 	} else {
                   6023: 	    return '';
                   6024: 	}
                   6025:     } else {
                   6026: 	return '';
                   6027:     }
1.351     www      6028: }
1.353     www      6029: 
                   6030: # ---------------------------------------------------------- Course ID routines
                   6031: # Deal with domain's nohist_courseid.db files
                   6032: #
                   6033: 
                   6034: sub courseidput {
1.921     raeburn  6035:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  6036:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  6037:     my $outcome;
                   6038:     if ($caller eq 'timeonly') {
                   6039:         my $cids = '';
                   6040:         foreach my $item (keys(%$storehash)) {
                   6041:             $cids.=&escape($item).'&';
                   6042:         }
                   6043:         $cids=~s/\&$//;
                   6044:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   6045:                           $coursehome);       
                   6046:     } else {
                   6047:         my $items = '';
                   6048:         foreach my $item (keys(%$storehash)) {
                   6049:             $items.= &escape($item).'='.
                   6050:                      &freeze_escape($$storehash{$item}).'&';
                   6051:         }
                   6052:         $items=~s/\&$//;
                   6053:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   6054:                           $coursehome);
1.918     raeburn  6055:     }
                   6056:     if ($outcome eq 'unknown_cmd') {
                   6057:         my $what;
                   6058:         foreach my $cid (keys(%$storehash)) {
                   6059:             $what .= &escape($cid).'=';
1.921     raeburn  6060:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  6061:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  6062:             }
                   6063:             $what =~ s/\:$/&/;
                   6064:         }
                   6065:         $what =~ s/\&$//;  
                   6066:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   6067:     } else {
                   6068:         return $outcome;
                   6069:     }
1.353     www      6070: }
                   6071: 
                   6072: sub courseiddump {
1.921     raeburn  6073:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  6074:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  6075:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  6076:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  6077:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  6078:     my $as_hash = 1;
                   6079:     my %returnhash;
                   6080:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 6081:     my %libserv = &all_library();
                   6082:     foreach my $tryserver (keys(%libserv)) {
                   6083:         if ( (  $hostidflag == 1 
                   6084: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   6085: 	     || (!defined($hostidflag)) ) {
                   6086: 
1.918     raeburn  6087: 	    if (($domfilter eq '') ||
                   6088: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 6089:                 my $rep;
                   6090:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   6091:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   6092:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   6093:                                 &escape($descfilter), &escape($instcodefilter), 
                   6094:                                 &escape($ownerfilter), &escape($coursefilter),
                   6095:                                 &escape($typefilter), &escape($regexp_ok), 
                   6096:                                 $as_hash, &escape($selfenrollonly), 
                   6097:                                 &escape($catfilter), $showhidden, $caller, 
                   6098:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   6099:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  6100:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   6101:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 6102:                 } else {
                   6103:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   6104:                              $sincefilter.':'.&escape($descfilter).':'.
                   6105:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   6106:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   6107:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   6108:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   6109:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   6110:                              &escape($cc_clone).':'.$cloneonly.':'.
                   6111:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  6112:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   6113:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 6114:                 }
                   6115:                      
1.918     raeburn  6116:                 my @pairs=split(/\&/,$rep);
                   6117:                 foreach my $item (@pairs) {
                   6118:                     my ($key,$value)=split(/\=/,$item,2);
                   6119:                     $key = &unescape($key);
                   6120:                     next if ($key =~ /^error: 2 /);
                   6121:                     my $result = &thaw_unescape($value);
                   6122:                     if (ref($result) eq 'HASH') {
                   6123:                         $returnhash{$key}=$result;
                   6124:                     } else {
1.921     raeburn  6125:                         my @responses = split(/:/,$value);
                   6126:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  6127:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  6128:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  6129:                         }
1.1008    raeburn  6130:                     }
1.353     www      6131:                 }
                   6132:             }
                   6133:         }
                   6134:     }
                   6135:     return %returnhash;
                   6136: }
                   6137: 
1.1055    raeburn  6138: sub courselastaccess {
                   6139:     my ($cdom,$cnum,$hostidref) = @_;
                   6140:     my %returnhash;
                   6141:     if ($cdom && $cnum) {
                   6142:         my $chome = &homeserver($cnum,$cdom);
                   6143:         if ($chome ne 'no_host') {
                   6144:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   6145:             &extract_lastaccess(\%returnhash,$rep);
                   6146:         }
                   6147:     } else {
                   6148:         if (!$cdom) { $cdom=''; }
                   6149:         my %libserv = &all_library();
                   6150:         foreach my $tryserver (keys(%libserv)) {
                   6151:             if (ref($hostidref) eq 'ARRAY') {
                   6152:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   6153:             } 
                   6154:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   6155:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   6156:                 &extract_lastaccess(\%returnhash,$rep);
                   6157:             }
                   6158:         }
                   6159:     }
                   6160:     return %returnhash;
                   6161: }
                   6162: 
                   6163: sub extract_lastaccess {
                   6164:     my ($returnhash,$rep) = @_;
                   6165:     if (ref($returnhash) eq 'HASH') {
                   6166:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   6167:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   6168:                  $rep eq '') {
                   6169:             my @pairs=split(/\&/,$rep);
                   6170:             foreach my $item (@pairs) {
                   6171:                 my ($key,$value)=split(/\=/,$item,2);
                   6172:                 $key = &unescape($key);
                   6173:                 next if ($key =~ /^error: 2 /);
                   6174:                 $returnhash->{$key} = &thaw_unescape($value);
                   6175:             }
                   6176:         }
                   6177:     }
                   6178:     return;
                   6179: }
                   6180: 
1.658     raeburn  6181: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  6182: 
                   6183: sub dcmailput {
1.685     raeburn  6184:     my ($domain,$msgid,$message,$server)=@_;
1.1494    raeburn  6185:     my $status = &critical(
1.740     www      6186:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   6187:        &escape($message),$server);
1.662     raeburn  6188:     return $status;
                   6189: }
                   6190: 
1.658     raeburn  6191: sub dcmaildump {
                   6192:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  6193:     my %returnhash=();
1.846     albertel 6194: 
                   6195:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  6196:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   6197:                                                          &escape($enddate).':';
                   6198: 	my @esc_senders=map { &escape($_)} @$senders;
                   6199: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 6200: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 6201:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  6202:             if (($key) && ($value)) {
                   6203:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  6204:             }
                   6205:         }
                   6206:     }
                   6207:     return %returnhash;
                   6208: }
1.662     raeburn  6209: # ---------------------------------------------------------- Domain roles
                   6210: 
                   6211: sub get_domain_roles {
                   6212:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  6213:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  6214:         $startdate = '.';
                   6215:     }
1.1018    raeburn  6216:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  6217:         $enddate = '.';
                   6218:     }
1.922     raeburn  6219:     my $rolelist;
                   6220:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  6221:         $rolelist = join('&',@{$roles});
1.922     raeburn  6222:     }
1.662     raeburn  6223:     my %personnel = ();
1.841     albertel 6224: 
                   6225:     my %servers = &get_servers($dom,'library');
                   6226:     foreach my $tryserver (keys(%servers)) {
                   6227: 	%{$personnel{$tryserver}}=();
                   6228: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   6229: 					    &escape($startdate).':'.
                   6230: 					    &escape($enddate).':'.
                   6231: 					    &escape($rolelist), $tryserver))) {
                   6232: 	    my ($key,$value) = split(/\=/,$line,2);
                   6233: 	    if (($key) && ($value)) {
                   6234: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   6235: 	    }
                   6236: 	}
1.662     raeburn  6237:     }
                   6238:     return %personnel;
                   6239: }
1.658     raeburn  6240: 
1.1332    raeburn  6241: sub get_active_domroles {
                   6242:     my ($dom,$roles) = @_;
                   6243:     return () unless (ref($roles) eq 'ARRAY');
                   6244:     my $now = time;
                   6245:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   6246:     my %domroles;
                   6247:     foreach my $server (keys(%dompersonnel)) {
                   6248:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   6249:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   6250:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   6251:         }
                   6252:     }
                   6253:     return %domroles;
                   6254: }
                   6255: 
1.1057    www      6256: # ----------------------------------------------------------- Interval timing 
1.149     www      6257: 
1.1153    www      6258: {
                   6259: # Caches needed for speedup of navmaps
                   6260: # We don't want to cache this for very long at all (5 seconds at most)
                   6261: # 
                   6262: # The user for whom we cache
                   6263: my $cachedkey='';
                   6264: # The cached times for this user
                   6265: my %cachedtimes=();
                   6266: # When this was last done
1.1282    raeburn  6267: my $cachedtime='';
1.1153    www      6268: 
                   6269: sub load_all_first_access {
1.1308    raeburn  6270:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      6271:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  6272:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   6273:         (!$ignorecache)) {
1.1154    raeburn  6274:         return;
                   6275:     }
                   6276:     $cachedtime=time;
                   6277:     $cachedkey=$uname.':'.$udom;
                   6278:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      6279: }
                   6280: 
1.504     albertel 6281: sub get_first_access {
1.1308    raeburn  6282:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 6283:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 6284:     if ($argsymb) { $symb=$argsymb; }
                   6285:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  6286:     if ($argmap) { $map = $argmap; }
1.926     albertel 6287:     if ($type eq 'course') {
                   6288: 	$res='course';
                   6289:     } elsif ($type eq 'map') {
1.588     albertel 6290: 	$res=&symbread($map);
                   6291:     } else {
                   6292: 	$res=$symb;
                   6293:     }
1.1308    raeburn  6294:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      6295:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 6296: }
                   6297: 
                   6298: sub set_first_access {
1.1162    raeburn  6299:     my ($type,$interval)=@_;
1.790     albertel 6300:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 6301:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 6302:     if ($type eq 'course') {
                   6303: 	$res='course';
                   6304:     } elsif ($type eq 'map') {
1.588     albertel 6305: 	$res=&symbread($map);
                   6306:     } else {
                   6307: 	$res=$symb;
                   6308:     }
1.1153    www      6309:     $cachedkey='';
1.1162    raeburn  6310:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  6311:     if ($firstaccess) {
                   6312:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  6313:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   6314:                  "in $courseid");
1.1386    raeburn  6315:         return 'already_set';
                   6316:     } else {
1.1162    raeburn  6317:         my $start = time;
                   6318: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   6319:                           $udom,$uname);
                   6320:         if ($putres eq 'ok') {
                   6321:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   6322:                  $udom,$uname); 
                   6323:             &appenv(
                   6324:                      {
                   6325:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   6326:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   6327:                      }
                   6328:                   );
1.1365    raeburn  6329:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   6330:                 $cachedtimes{"$courseid\0$res"} = $start;
                   6331:             }
1.1386    raeburn  6332:         } elsif ($putres ne 'refused') {
                   6333:             &logthis("Result: $putres when attempting to set first access time ".
                   6334:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  6335:         }
                   6336:         return $putres;
1.505     albertel 6337:     }
                   6338:     return 'already_set';
1.504     albertel 6339: }
1.1153    www      6340: }
1.1282    raeburn  6341: 
1.110     www      6342: # --------------------------------------------- Set Expire Date for Spreadsheet
                   6343: 
                   6344: sub expirespread {
                   6345:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 6346:     my $cid=$env{'request.course.id'}; 
1.110     www      6347:     if ($cid) {
                   6348:        my $now=time;
                   6349:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6350:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6351:                             $env{'course.'.$cid.'.num'}.
1.110     www      6352: 	        	    ':nohist_expirationdates:'.
                   6353:                             &escape($key).'='.$now,
1.620     albertel 6354:                             $env{'course.'.$cid.'.home'})
1.110     www      6355:     }
                   6356:     return 'ok';
1.14      www      6357: }
                   6358: 
1.109     www      6359: # ----------------------------------------------------- Devalidate Spreadsheets
                   6360: 
                   6361: sub devalidate {
1.325     www      6362:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6363:     my $cid=$env{'request.course.id'}; 
1.109     www      6364:     if ($cid) {
1.391     matthew  6365:         # delete the stored spreadsheets for
                   6366:         # - the student level sheet of this user in course's homespace
                   6367:         # - the assessment level sheet for this resource 
                   6368:         #   for this user in user's homespace
1.553     albertel 6369: 	# - current conditional state info
1.325     www      6370: 	my $key=$uname.':'.$udom.':';
1.109     www      6371:         my $status=
1.299     matthew  6372: 	    &del('nohist_calculatedsheets',
1.391     matthew  6373: 		 [$key.'studentcalc:'],
1.620     albertel 6374: 		 $env{'course.'.$cid.'.domain'},
                   6375: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6376: 		.' '.
                   6377: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6378: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6379:         unless ($status eq 'ok ok') {
                   6380:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6381:                     $uname.' at '.$udom.' for '.
1.109     www      6382: 		    $symb.': '.$status);
1.133     albertel 6383:         }
1.553     albertel 6384: 	&delenv('user.state.'.$cid);
1.109     www      6385:     }
                   6386: }
                   6387: 
1.265     albertel 6388: sub get_scalar {
                   6389:     my ($string,$end) = @_;
                   6390:     my $value;
                   6391:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6392: 	$value = $1;
                   6393:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6394: 	$value = $1;
                   6395:     }
                   6396:     return &unescape($value);
                   6397: }
                   6398: 
                   6399: sub array2str {
                   6400:   my (@array) = @_;
                   6401:   my $result=&arrayref2str(\@array);
                   6402:   $result=~s/^__ARRAY_REF__//;
                   6403:   $result=~s/__END_ARRAY_REF__$//;
                   6404:   return $result;
                   6405: }
                   6406: 
1.204     albertel 6407: sub arrayref2str {
                   6408:   my ($arrayref) = @_;
1.265     albertel 6409:   my $result='__ARRAY_REF__';
1.204     albertel 6410:   foreach my $elem (@$arrayref) {
1.265     albertel 6411:     if(ref($elem) eq 'ARRAY') {
                   6412:       $result.=&arrayref2str($elem).'&';
                   6413:     } elsif(ref($elem) eq 'HASH') {
                   6414:       $result.=&hashref2str($elem).'&';
                   6415:     } elsif(ref($elem)) {
                   6416:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6417:     } else {
                   6418:       $result.=&escape($elem).'&';
                   6419:     }
                   6420:   }
                   6421:   $result=~s/\&$//;
1.265     albertel 6422:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6423:   return $result;
                   6424: }
                   6425: 
1.168     albertel 6426: sub hash2str {
1.204     albertel 6427:   my (%hash) = @_;
                   6428:   my $result=&hashref2str(\%hash);
1.265     albertel 6429:   $result=~s/^__HASH_REF__//;
                   6430:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6431:   return $result;
                   6432: }
                   6433: 
                   6434: sub hashref2str {
                   6435:   my ($hashref)=@_;
1.265     albertel 6436:   my $result='__HASH_REF__';
1.800     albertel 6437:   foreach my $key (sort(keys(%$hashref))) {
                   6438:     if (ref($key) eq 'ARRAY') {
                   6439:       $result.=&arrayref2str($key).'=';
                   6440:     } elsif (ref($key) eq 'HASH') {
                   6441:       $result.=&hashref2str($key).'=';
                   6442:     } elsif (ref($key)) {
1.265     albertel 6443:       $result.='=';
1.800     albertel 6444:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6445:     } else {
1.1132    raeburn  6446: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6447:     }
                   6448: 
1.800     albertel 6449:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6450:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6451:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6452:       $result.=&hashref2str($hashref->{$key}).'&';
                   6453:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6454:        $result.='&';
1.800     albertel 6455:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6456:     } else {
1.800     albertel 6457:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6458:     }
                   6459:   }
1.168     albertel 6460:   $result=~s/\&$//;
1.265     albertel 6461:   $result .= '__END_HASH_REF__';
1.168     albertel 6462:   return $result;
                   6463: }
                   6464: 
                   6465: sub str2hash {
1.265     albertel 6466:     my ($string)=@_;
                   6467:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6468:     return %$hash;
                   6469: }
                   6470: 
                   6471: sub str2hashref {
1.168     albertel 6472:   my ($string) = @_;
1.265     albertel 6473: 
                   6474:   my %hash;
                   6475: 
                   6476:   if($string !~ /^__HASH_REF__/) {
                   6477:       if (! ($string eq '' || !defined($string))) {
                   6478: 	  $hash{'error'}='Not hash reference';
                   6479:       }
                   6480:       return (\%hash, $string);
                   6481:   }
                   6482: 
                   6483:   $string =~ s/^__HASH_REF__//;
                   6484: 
                   6485:   while($string !~ /^__END_HASH_REF__/) {
                   6486:       #key
                   6487:       my $key='';
                   6488:       if($string =~ /^__HASH_REF__/) {
                   6489:           ($key, $string)=&str2hashref($string);
                   6490:           if(defined($key->{'error'})) {
                   6491:               $hash{'error'}='Bad data';
                   6492:               return (\%hash, $string);
                   6493:           }
                   6494:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6495:           ($key, $string)=&str2arrayref($string);
                   6496:           if($key->[0] eq 'Array reference error') {
                   6497:               $hash{'error'}='Bad data';
                   6498:               return (\%hash, $string);
                   6499:           }
                   6500:       } else {
                   6501:           $string =~ s/^(.*?)=//;
1.267     albertel 6502: 	  $key=&unescape($1);
1.265     albertel 6503:       }
                   6504:       $string =~ s/^=//;
                   6505: 
                   6506:       #value
                   6507:       my $value='';
                   6508:       if($string =~ /^__HASH_REF__/) {
                   6509:           ($value, $string)=&str2hashref($string);
                   6510:           if(defined($value->{'error'})) {
                   6511:               $hash{'error'}='Bad data';
                   6512:               return (\%hash, $string);
                   6513:           }
                   6514:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6515:           ($value, $string)=&str2arrayref($string);
                   6516:           if($value->[0] eq 'Array reference error') {
                   6517:               $hash{'error'}='Bad data';
                   6518:               return (\%hash, $string);
                   6519:           }
                   6520:       } else {
                   6521: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6522:       }
                   6523:       $string =~ s/^&//;
                   6524: 
                   6525:       $hash{$key}=$value;
1.204     albertel 6526:   }
1.265     albertel 6527: 
                   6528:   $string =~ s/^__END_HASH_REF__//;
                   6529: 
                   6530:   return (\%hash, $string);
1.204     albertel 6531: }
                   6532: 
                   6533: sub str2array {
1.265     albertel 6534:     my ($string)=@_;
                   6535:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6536:     return @$array;
                   6537: }
                   6538: 
                   6539: sub str2arrayref {
1.204     albertel 6540:   my ($string) = @_;
1.265     albertel 6541:   my @array;
                   6542: 
                   6543:   if($string !~ /^__ARRAY_REF__/) {
                   6544:       if (! ($string eq '' || !defined($string))) {
                   6545: 	  $array[0]='Array reference error';
                   6546:       }
                   6547:       return (\@array, $string);
                   6548:   }
                   6549: 
                   6550:   $string =~ s/^__ARRAY_REF__//;
                   6551: 
                   6552:   while($string !~ /^__END_ARRAY_REF__/) {
                   6553:       my $value='';
                   6554:       if($string =~ /^__HASH_REF__/) {
                   6555:           ($value, $string)=&str2hashref($string);
                   6556:           if(defined($value->{'error'})) {
                   6557:               $array[0] ='Array reference error';
                   6558:               return (\@array, $string);
                   6559:           }
                   6560:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6561:           ($value, $string)=&str2arrayref($string);
                   6562:           if($value->[0] eq 'Array reference error') {
                   6563:               $array[0] ='Array reference error';
                   6564:               return (\@array, $string);
                   6565:           }
                   6566:       } else {
                   6567: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6568:       }
                   6569:       $string =~ s/^&//;
                   6570: 
                   6571:       push(@array, $value);
1.191     harris41 6572:   }
1.265     albertel 6573: 
                   6574:   $string =~ s/^__END_ARRAY_REF__//;
                   6575: 
                   6576:   return (\@array, $string);
1.168     albertel 6577: }
                   6578: 
1.167     albertel 6579: # -------------------------------------------------------------------Temp Store
                   6580: 
1.168     albertel 6581: sub tmpreset {
                   6582:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6583:   if (!$symb) {
                   6584:     $symb=&symbread();
1.620     albertel 6585:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6586:   }
                   6587:   $symb=escape($symb);
                   6588: 
1.620     albertel 6589:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6590:   $namespace=~s/\//\_/g;
                   6591:   $namespace=~s/\W//g;
                   6592: 
1.620     albertel 6593:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6594:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6595:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6596:       $stuname=&get_requestor_ip();
1.591     albertel 6597:   }
1.1117    foxr     6598:   my $path=LONCAPA::tempdir();
1.168     albertel 6599:   my %hash;
                   6600:   if (tie(%hash,'GDBM_File',
                   6601: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6602: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6603:     foreach my $key (keys(%hash)) {
1.180     albertel 6604:       if ($key=~ /:$symb/) {
1.168     albertel 6605: 	delete($hash{$key});
                   6606:       }
                   6607:     }
                   6608:   }
                   6609: }
                   6610: 
1.167     albertel 6611: sub tmpstore {
1.168     albertel 6612:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6613: 
                   6614:   if (!$symb) {
                   6615:     $symb=&symbread();
1.620     albertel 6616:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6617:   }
                   6618:   $symb=escape($symb);
                   6619: 
                   6620:   if (!$namespace) {
                   6621:     # I don't think we would ever want to store this for a course.
                   6622:     # it seems this will only be used if we don't have a course.
1.620     albertel 6623:     #$namespace=$env{'request.course.id'};
1.168     albertel 6624:     #if (!$namespace) {
1.620     albertel 6625:       $namespace=$env{'request.state'};
1.168     albertel 6626:     #}
                   6627:   }
                   6628:   $namespace=~s/\//\_/g;
                   6629:   $namespace=~s/\W//g;
1.620     albertel 6630:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6631:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6632:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6633:       $stuname=&get_requestor_ip();
1.591     albertel 6634:   }
1.168     albertel 6635:   my $now=time;
                   6636:   my %hash;
1.1117    foxr     6637:   my $path=LONCAPA::tempdir();
1.168     albertel 6638:   if (tie(%hash,'GDBM_File',
                   6639: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6640: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6641:     $hash{"version:$symb"}++;
                   6642:     my $version=$hash{"version:$symb"};
                   6643:     my $allkeys=''; 
                   6644:     foreach my $key (keys(%$storehash)) {
                   6645:       $allkeys.=$key.':';
1.591     albertel 6646:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6647:     }
                   6648:     $hash{"$version:$symb:timestamp"}=$now;
                   6649:     $allkeys.='timestamp';
                   6650:     $hash{"$version:keys:$symb"}=$allkeys;
                   6651:     if (untie(%hash)) {
                   6652:       return 'ok';
                   6653:     } else {
                   6654:       return "error:$!";
                   6655:     }
                   6656:   } else {
                   6657:     return "error:$!";
                   6658:   }
                   6659: }
1.167     albertel 6660: 
1.168     albertel 6661: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6662: 
1.168     albertel 6663: sub tmprestore {
                   6664:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6665: 
1.168     albertel 6666:   if (!$symb) {
                   6667:     $symb=&symbread();
1.620     albertel 6668:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6669:   }
                   6670:   $symb=escape($symb);
                   6671: 
1.620     albertel 6672:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6673: 
1.620     albertel 6674:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6675:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6676:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6677:       $stuname=&get_requestor_ip();
1.591     albertel 6678:   }
1.168     albertel 6679:   my %returnhash;
                   6680:   $namespace=~s/\//\_/g;
                   6681:   $namespace=~s/\W//g;
                   6682:   my %hash;
1.1117    foxr     6683:   my $path=LONCAPA::tempdir();
1.168     albertel 6684:   if (tie(%hash,'GDBM_File',
                   6685: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6686: 	  &GDBM_READER(),0640)) {
1.168     albertel 6687:     my $version=$hash{"version:$symb"};
                   6688:     $returnhash{'version'}=$version;
                   6689:     my $scope;
                   6690:     for ($scope=1;$scope<=$version;$scope++) {
                   6691:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6692:       my @keys=split(/:/,$vkeys);
                   6693:       my $key;
                   6694:       $returnhash{"$scope:keys"}=$vkeys;
                   6695:       foreach $key (@keys) {
1.591     albertel 6696: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6697: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6698:       }
                   6699:     }
1.168     albertel 6700:     if (!(untie(%hash))) {
                   6701:       return "error:$!";
                   6702:     }
                   6703:   } else {
                   6704:     return "error:$!";
                   6705:   }
                   6706:   return %returnhash;
1.167     albertel 6707: }
                   6708: 
1.9       www      6709: # ----------------------------------------------------------------------- Store
                   6710: 
                   6711: sub store {
1.1269    raeburn  6712:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6713:     my $home='';
                   6714: 
1.168     albertel 6715:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6716: 
1.213     www      6717:     $symb=&symbclean($symb);
1.122     albertel 6718:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6719: 
1.620     albertel 6720:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6721:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6722: 
                   6723:     &devalidate($symb,$stuname,$domain);
1.109     www      6724: 
                   6725:     $symb=escape($symb);
1.187     www      6726:     if (!$namespace) { 
1.620     albertel 6727:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6728:           return ''; 
                   6729:        } 
                   6730:     }
1.620     albertel 6731:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6732: 
1.1434    raeburn  6733:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6734:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6735: 
1.12      www      6736:     my $namevalue='';
1.800     albertel 6737:     foreach my $key (keys(%$storehash)) {
                   6738:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6739:     }
1.12      www      6740:     $namevalue=~s/\&$//;
1.187     www      6741:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6742:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6743: }
                   6744: 
1.47      www      6745: # -------------------------------------------------------------- Critical Store
                   6746: 
                   6747: sub cstore {
1.1269    raeburn  6748:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6749:     my $home='';
                   6750: 
1.168     albertel 6751:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6752: 
1.213     www      6753:     $symb=&symbclean($symb);
1.122     albertel 6754:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6755: 
1.620     albertel 6756:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6757:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6758: 
                   6759:     &devalidate($symb,$stuname,$domain);
1.109     www      6760: 
                   6761:     $symb=escape($symb);
1.187     www      6762:     if (!$namespace) { 
1.620     albertel 6763:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6764:           return ''; 
                   6765:        } 
                   6766:     }
1.620     albertel 6767:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6768: 
1.1434    raeburn  6769:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6770:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6771: 
1.47      www      6772:     my $namevalue='';
1.800     albertel 6773:     foreach my $key (keys(%$storehash)) {
                   6774:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6775:     }
1.47      www      6776:     $namevalue=~s/\&$//;
1.187     www      6777:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6778:     return critical
1.1269    raeburn  6779:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6780: }
                   6781: 
1.9       www      6782: # --------------------------------------------------------------------- Restore
                   6783: 
                   6784: sub restore {
1.124     www      6785:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6786:     my $home='';
                   6787: 
1.168     albertel 6788:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6789: 
1.122     albertel 6790:     if (!$symb) {
1.1224    raeburn  6791:         return if ($namespace eq 'courserequests');
                   6792:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6793:     } else {
1.1224    raeburn  6794:         unless ($namespace eq 'courserequests') {
                   6795:             $symb=&escape(&symbclean($symb));
                   6796:         }
1.122     albertel 6797:     }
1.188     www      6798:     if (!$namespace) { 
1.620     albertel 6799:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6800:           return ''; 
                   6801:        } 
                   6802:     }
1.620     albertel 6803:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6804:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6805:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6806:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6807: 
1.12      www      6808:     my %returnhash=();
1.800     albertel 6809:     foreach my $line (split(/\&/,$answer)) {
                   6810: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6811:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6812:     }
1.75      www      6813:     my $version;
                   6814:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6815:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6816:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6817:        }
1.75      www      6818:     }
1.13      www      6819:     return %returnhash;
1.34      www      6820: }
                   6821: 
                   6822: # ---------------------------------------------------------- Course Description
1.1118    foxr     6823: #
                   6824: #  
1.34      www      6825: 
                   6826: sub coursedescription {
1.731     albertel 6827:     my ($courseid,$args)=@_;
1.34      www      6828:     $courseid=~s/^\///;
1.49      www      6829:     $courseid=~s/\_/\//g;
1.34      www      6830:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6831:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6832:     my $normalid=$cdomain.'_'.$cnum;
                   6833:     # need to always cache even if we get errors otherwise we keep 
                   6834:     # trying and trying and trying to get the course description.
                   6835:     my %envhash=();
                   6836:     my %returnhash=();
1.731     albertel 6837:     
                   6838:     my $expiretime=600;
                   6839:     if ($env{'request.course.id'} eq $normalid) {
                   6840: 	$expiretime=120;
                   6841:     }
                   6842: 
                   6843:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6844:     if (!$args->{'freshen_cache'}
                   6845: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6846: 	foreach my $key (keys(%env)) {
                   6847: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6848: 	    my ($setting) = $1;
                   6849: 	    $returnhash{$setting} = $env{$key};
                   6850: 	}
                   6851: 	return %returnhash;
                   6852:     }
                   6853: 
1.1118    foxr     6854:     # get the data again
                   6855: 
1.731     albertel 6856:     if (!$args->{'one_time'}) {
                   6857: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6858:     }
1.811     albertel 6859: 
1.34      www      6860:     if ($chome ne 'no_host') {
1.302     albertel 6861:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6862:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6863: 	   my $username = $env{'user.name'}; # Defult username
                   6864: 	   if(defined $args->{'user'}) {
                   6865: 	       $username = $args->{'user'};
                   6866: 	   }
1.129     albertel 6867:            $returnhash{'home'}= $chome;
                   6868: 	   $returnhash{'domain'} = $cdomain;
                   6869: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6870:            if (!defined($returnhash{'type'})) {
                   6871:                $returnhash{'type'} = 'Course';
                   6872:            }
1.130     albertel 6873:            while (my ($name,$value) = each %returnhash) {
1.53      www      6874:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6875:            }
1.270     www      6876:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6877:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6878: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6879:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6880:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6881:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6882:        }
                   6883:     }
1.731     albertel 6884:     if (!$args->{'one_time'}) {
1.949     raeburn  6885: 	&appenv(\%envhash);
1.731     albertel 6886:     }
1.302     albertel 6887:     return %returnhash;
1.461     www      6888: }
                   6889: 
1.1080    raeburn  6890: sub update_released_required {
                   6891:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6892:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6893:         $cid = $env{'request.course.id'};
                   6894:         $cdom = $env{'course.'.$cid.'.domain'};
                   6895:         $cnum = $env{'course.'.$cid.'.num'};
                   6896:         $chome = $env{'course.'.$cid.'.home'};
                   6897:     }
                   6898:     if ($needsrelease) {
                   6899:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6900:         my $needsupdate;
                   6901:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6902:             $needsupdate = 1;
                   6903:         } else {
                   6904:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6905:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6906:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6907:                 $needsupdate = 1;
                   6908:             }
                   6909:         }
                   6910:         if ($needsupdate) {
                   6911:             my %needshash = (
                   6912:                              'internal.releaserequired' => $needsrelease,
                   6913:                             );
                   6914:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6915:             if ($putresult eq 'ok') {
                   6916:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6917:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6918:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6919:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6920:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6921:                 }
                   6922:             }
                   6923:         }
                   6924:     }
                   6925:     return;
                   6926: }
                   6927: 
1.461     www      6928: # -------------------------------------------------See if a user is privileged
                   6929: 
                   6930: sub privileged {
1.1219    raeburn  6931:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6932:     my $now = time;
1.1219    raeburn  6933:     my $roles;
                   6934:     if (ref($possroles) eq 'ARRAY') {
                   6935:         $roles = $possroles; 
                   6936:     } else {
                   6937:         $roles = ['dc','su'];
                   6938:     }
                   6939:     if (ref($possdomains) eq 'ARRAY') {
                   6940:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6941:         foreach my $dom (@{$possdomains}) {
                   6942:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6943:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6944:                 foreach my $role (@{$roles}) {
                   6945:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6946:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6947:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6948:                             return 1 unless (($end && $end < $now) ||
                   6949:                                              ($start && $start > $now));
                   6950:                         }
                   6951:                     }
                   6952:                 }
                   6953:             }
                   6954:         }
                   6955:     } else {
                   6956:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6957:         my $now = time;
1.1170    droeschl 6958: 
1.1275    musolffc 6959:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6960:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6961:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6962:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6963:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6964:             }
1.1219    raeburn  6965:         }
                   6966:     }
                   6967:     return 0;
                   6968: }
1.1170    droeschl 6969: 
1.1219    raeburn  6970: sub privileged_by_domain {
                   6971:     my ($domains,$roles) = @_;
                   6972:     my %privileged = ();
                   6973:     my $cachetime = 60*60*24;
                   6974:     my $now = time;
                   6975:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6976:         return %privileged;
                   6977:     }
                   6978:     foreach my $dom (@{$domains}) {
                   6979:         next if (ref($privileged{$dom}) eq 'HASH');
                   6980:         my $needroles;
                   6981:         foreach my $role (@{$roles}) {
                   6982:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6983:             if (defined($cached)) {
                   6984:                 if (ref($result) eq 'HASH') {
                   6985:                     $privileged{$dom}{$role} = $result;
                   6986:                 }
                   6987:             } else {
                   6988:                 $needroles = 1;
                   6989:             }
                   6990:         }
                   6991:         if ($needroles) {
                   6992:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6993:             $privileged{$dom} = {};
                   6994:             foreach my $server (keys(%dompersonnel)) {
                   6995:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6996:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6997:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6998:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6999:                         next if ($end && $end < $now);
                   7000:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   7001:                             $dompersonnel{$server}{$item};
                   7002:                     }
                   7003:                 }
                   7004:             }
                   7005:             if (ref($privileged{$dom}) eq 'HASH') {
                   7006:                 foreach my $role (@{$roles}) {
                   7007:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   7008:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   7009:                     } else {
                   7010:                         my %hash = ();
                   7011:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   7012:                     }
                   7013:                 }
                   7014:             }
                   7015:         }
                   7016:     }
                   7017:     return %privileged;
1.9       www      7018: }
1.1       albertel 7019: 
1.103     harris41 7020: # -------------------------------------------------------- Get user privileges
1.11      www      7021: 
                   7022: sub rolesinit {
1.1169    droeschl 7023:     my ($domain, $username) = @_;
                   7024:     my %userroles = ('user.login.time' => time);
                   7025:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   7026: 
                   7027:     # firstaccess and timerinterval are related to timed maps/resources. 
                   7028:     # also, blocking can be triggered by an activating timer
                   7029:     # it's saved in the user's %env.
                   7030:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   7031:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   7032:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
1.1517    raeburn  7033:         %timerintchk, %timerintenv, %coauthorenv);
1.1169    droeschl 7034: 
1.1162    raeburn  7035:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 7036:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  7037:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   7038:     }
1.1169    droeschl 7039: 
1.1162    raeburn  7040:     foreach my $key (keys(%timerinterval)) {
                   7041:         my ($cid,$rest) = split(/\0/,$key);
                   7042:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   7043:     }
1.1169    droeschl 7044: 
1.11      www      7045:     my %allroles=();
1.1162    raeburn  7046:     my %allgroups=();
1.1517    raeburn  7047:     my %gotcoauconfig=();
1.1524    raeburn  7048:     my %domdefaults=();
1.11      www      7049: 
1.1274    raeburn  7050:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 7051:         my $role = $rolesdump{$area};
                   7052:         $area =~ s/\_\w\w$//;
                   7053: 
                   7054:         my ($trole, $tend, $tstart, $group_privs);
                   7055: 
                   7056:         if ($role =~ /^cr/) {
                   7057:         # Custom role, defined by a user 
                   7058:         # e.g., user.role.cr/msu/smith/mynewrole
                   7059:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   7060:                 $trole = $1;
                   7061:                 ($tend, $tstart) = split('_', $2);
                   7062:             } else {
                   7063:                 $trole = $role;
                   7064:             }
                   7065:         } elsif ($role =~ m|^gr/|) {
                   7066:         # Role of member in a group, defined within a course/community
                   7067:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   7068:             ($trole, $tend, $tstart) = split(/_/, $role);
                   7069:             next if $tstart eq '-1';
                   7070:             ($trole, $group_privs) = split(/\//, $trole);
                   7071:             $group_privs = &unescape($group_privs);
                   7072:         } else {
                   7073:         # Just a normal role, defined in roles.tab
                   7074:             ($trole, $tend, $tstart) = split(/_/,$role);
                   7075:         }
                   7076: 
                   7077:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   7078:                  $username);
                   7079:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   7080: 
                   7081:         # role expired or not available yet?
                   7082:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   7083:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   7084: 
                   7085:         next if $area eq '' or $trole eq '';
                   7086: 
                   7087:         my $spec = "$trole.$area";
                   7088:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   7089: 
                   7090:         if ($trole =~ /^cr\//) {
                   7091:         # Custom role, defined by a user
                   7092:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7093:         } elsif ($trole eq 'gr') {
                   7094:         # Role of a member in a group, defined within a course/community
                   7095:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   7096:             next;
                   7097:         } else {
                   7098:         # Normal role, defined in roles.tab
                   7099:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.1517    raeburn  7100:             if (($trole eq 'ca') || ($trole eq 'aa')) {
                   7101:                 (undef,my ($audom,$auname)) = split(/\//,$area);
                   7102:                 unless ($gotcoauconfig{$area}) {
                   7103:                     my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
                   7104:                     my %info = &userenvironment($audom,$auname,@ca_settings);
                   7105:                     $gotcoauconfig{$area} = 1;
                   7106:                     foreach my $item (@ca_settings) {
                   7107:                         if (exists($info{$item})) {
1.1519    raeburn  7108:                             my $name = $item;
                   7109:                             if ($item eq 'authoreditors') {
                   7110:                                 $name = 'editors';
1.1524    raeburn  7111:                                 unless ($info{'authoreditors'}) {
                   7112:                                     my %domdefs;
                   7113:                                     if (ref($domdefaults{$audom}) eq 'HASH') {
                   7114:                                         %domdefs = %{$domdefaults{$audom}};
                   7115:                                     } else {
                   7116:                                         %domdefs = &get_domain_defaults($audom);
                   7117:                                         $domdefaults{$audom} = \%domdefs;
                   7118:                                     }
                   7119:                                     if ($domdefs{$name} ne '') {
                   7120:                                         $info{'authoreditors'} = $domdefs{$name};
                   7121:                                     } else {
                   7122:                                         $info{'authoreditors'} = 'edit,xml';
                   7123:                                     }
                   7124:                                 }
1.1519    raeburn  7125:                             }
                   7126:                             $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
1.1517    raeburn  7127:                         }
                   7128:                     }
                   7129:                 }
                   7130:             }
1.1169    droeschl 7131:         }
                   7132: 
                   7133:         my $cid = $tdomain.'_'.$trest;
                   7134:         unless ($firstaccchk{$cid}) {
                   7135:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   7136:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   7137:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   7138:                         $coursetimerstarts{$cid}{$item}; 
                   7139:                 }
                   7140:             }
                   7141:             $firstaccchk{$cid} = 1;
                   7142:         }
                   7143:         unless ($timerintchk{$cid}) {
                   7144:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   7145:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   7146:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   7147:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  7148:                 }
1.12      www      7149:             }
1.1169    droeschl 7150:             $timerintchk{$cid} = 1;
1.191     harris41 7151:         }
1.11      www      7152:     }
1.1169    droeschl 7153: 
1.1341    raeburn  7154:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   7155:                                                           \%allroles, \%allgroups);
1.1169    droeschl 7156:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  7157:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 7158: 
1.1517    raeburn  7159:     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
1.11      www      7160: }
                   7161: 
1.567     raeburn  7162: sub set_arearole {
1.1215    raeburn  7163:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   7164:     unless ($nolog) {
1.567     raeburn  7165: # log the associated role with the area
1.1215    raeburn  7166:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   7167:     }
1.743     albertel 7168:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  7169: }
                   7170: 
                   7171: sub custom_roleprivs {
                   7172:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   7173:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  7174:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 7175:     if (&hostname($homsvr) ne '') {
1.567     raeburn  7176:         my ($rdummy,$roledef)=
                   7177:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   7178:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   7179:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   7180:             if (defined($syspriv)) {
1.1043    raeburn  7181:                 if ($trest =~ /^$match_community$/) {
                   7182:                     $syspriv =~ s/bre\&S//; 
                   7183:                 }
1.567     raeburn  7184:                 $$allroles{'cm./'}.=':'.$syspriv;
                   7185:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   7186:             }
                   7187:             if ($tdomain ne '') {
                   7188:                 if (defined($dompriv)) {
                   7189:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   7190:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   7191:                 }
                   7192:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  7193:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   7194:                         my $rolename = $1;
                   7195:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   7196:                     }
1.567     raeburn  7197:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   7198:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   7199:                 }
                   7200:             }
                   7201:         }
                   7202:     }
                   7203: }
                   7204: 
1.1332    raeburn  7205: sub course_adhocrole_privs {
                   7206:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   7207:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   7208:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   7209:         my (%currprivs,%storeprivs);
                   7210:         foreach my $item (split(/:/,$coursepriv)) {
                   7211:             my ($priv,$restrict) = split(/\&/,$item);
                   7212:             $currprivs{$priv} = $restrict;
                   7213:         }
                   7214:         my (%possadd,%possremove,%full);
                   7215:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   7216:             my ($priv,$restrict)=split(/\&/,$item);
                   7217:             $full{$priv} = $restrict;
                   7218:         }
                   7219:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490    raeburn  7220:             next if ($item eq '');
                   7221:             my ($rule,$rest) = split(/=/,$item);
                   7222:             next unless (($rule eq 'off') || ($rule eq 'on'));
                   7223:             foreach my $priv (split(/:/,$rest)) {
                   7224:                 if ($priv ne '') {
                   7225:                     if ($rule eq 'off') {
                   7226:                         $possremove{$priv} = 1;
                   7227:                     } else {
                   7228:                         $possadd{$priv} = 1;
                   7229:                     }
                   7230:                 }
                   7231:             }
                   7232:         }
                   7233:         foreach my $priv (sort(keys(%full))) {
                   7234:             if (exists($currprivs{$priv})) {
                   7235:                 unless (exists($possremove{$priv})) {
                   7236:                     $storeprivs{$priv} = $currprivs{$priv};
                   7237:                 }
                   7238:             } elsif (exists($possadd{$priv})) {
                   7239:                 $storeprivs{$priv} = $full{$priv};
                   7240:             }
                   7241:         }
                   7242:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   7243:     }
                   7244:     return $coursepriv;
1.1332    raeburn  7245: }
                   7246: 
1.678     raeburn  7247: sub group_roleprivs {
                   7248:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   7249:     my $access = 1;
                   7250:     my $now = time;
                   7251:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   7252:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   7253:     if ($access) {
1.811     albertel 7254:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  7255:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   7256:     }
                   7257: }
1.567     raeburn  7258: 
                   7259: sub standard_roleprivs {
                   7260:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   7261:     if (defined($pr{$trole.':s'})) {
                   7262:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   7263:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   7264:     }
                   7265:     if ($tdomain ne '') {
                   7266:         if (defined($pr{$trole.':d'})) {
                   7267:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   7268:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   7269:         }
                   7270:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   7271:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   7272:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   7273:         }
                   7274:     }
                   7275: }
                   7276: 
                   7277: sub set_userprivs {
1.1064    raeburn  7278:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  7279:     my $author=0;
                   7280:     my $adv=0;
1.1341    raeburn  7281:     my $rar=0;
1.678     raeburn  7282:     my %grouproles = ();
                   7283:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  7284:         my @groupkeys; 
1.1000    raeburn  7285:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  7286:             push(@groupkeys,$role);
                   7287:         }
                   7288:         if (ref($groups_roles) eq 'HASH') {
                   7289:             foreach my $key (keys(%{$groups_roles})) {
                   7290:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   7291:                     push(@groupkeys,$key);
                   7292:                 }
                   7293:             }
                   7294:         }
                   7295:         if (@groupkeys > 0) {
                   7296:             foreach my $role (@groupkeys) {
                   7297:                 my ($trole,$area,$sec,$extendedarea);
                   7298:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   7299:                     $trole = $1;
                   7300:                     $area = $2;
                   7301:                     $sec = $3;
                   7302:                     $extendedarea = $area.$sec;
                   7303:                     if (exists($$allgroups{$area})) {
                   7304:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   7305:                             my $spec = $trole.'.'.$extendedarea;
                   7306:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  7307:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  7308:                         }
1.678     raeburn  7309:                     }
                   7310:                 }
                   7311:             }
                   7312:         }
                   7313:     }
1.800     albertel 7314:     foreach my $group (keys(%grouproles)) {
                   7315:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  7316:     }
1.800     albertel 7317:     foreach my $role (keys(%{$allroles})) {
                   7318:         my %thesepriv;
1.941     raeburn  7319:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 7320:         foreach my $item (split(/:/,$$allroles{$role})) {
                   7321:             if ($item ne '') {
                   7322:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  7323:                 if ($restrictions eq '') {
                   7324:                     $thesepriv{$privilege}='F';
                   7325:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   7326:                     $thesepriv{$privilege}.=$restrictions;
                   7327:                 }
                   7328:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  7329:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  7330:             }
                   7331:         }
                   7332:         my $thesestr='';
1.1104    raeburn  7333:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 7334: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   7335: 	}
                   7336:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  7337:     }
1.1341    raeburn  7338:     return ($author,$adv,$rar);
1.567     raeburn  7339: }
                   7340: 
1.994     raeburn  7341: sub role_status {
1.1104    raeburn  7342:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  7343:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  7344:         my ($one,$two) = split(m{\./},$rolekey,2);
                   7345:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  7346:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  7347:             $$where = '/'.$two;
1.994     raeburn  7348:             $$trolecode=$$role.'.'.$$where;
                   7349:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   7350:             $$tstatus='is';
1.1104    raeburn  7351:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  7352:                 $$tstatus='future';
1.1034    raeburn  7353:                 if ($$tstart<$now) {
                   7354:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  7355:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  7356:                             my (%allroles,%allgroups,$group_privs,
                   7357:                                 %groups_roles,@rolecodes);
1.1002    raeburn  7358:                             my %userroles = (
                   7359:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   7360:                             );
1.1064    raeburn  7361:                             @rolecodes = ('cm'); 
1.1002    raeburn  7362:                             my $spec=$$role.'.'.$$where;
                   7363:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   7364:                             if ($$role =~ /^cr\//) {
                   7365:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  7366:                                 push(@rolecodes,'cr');
1.1002    raeburn  7367:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  7368:                                 push(@rolecodes,$$role);
1.1002    raeburn  7369:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   7370:                                                     $env{'user.name'});
1.1064    raeburn  7371:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  7372:                                 (undef,my $group_privs) = split(/\//,$trole);
                   7373:                                 $group_privs = &unescape($group_privs);
                   7374:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  7375:                                 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  7376:                                 &get_groups_roles($tdomain,$trest,
                   7377:                                                   \%course_roles,\@rolecodes,
                   7378:                                                   \%groups_roles);
1.1002    raeburn  7379:                             } else {
1.1064    raeburn  7380:                                 push(@rolecodes,$$role);
1.1002    raeburn  7381:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7382:                             }
1.1341    raeburn  7383:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7384:                                                                    \%groups_roles);
1.1064    raeburn  7385:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  7386:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7387:                         }
                   7388:                     }
1.1034    raeburn  7389:                     $$tstatus = 'is';
1.1002    raeburn  7390:                 }
1.994     raeburn  7391:             }
                   7392:             if ($$tend) {
1.1104    raeburn  7393:                 if ($$tend<$update) {
1.994     raeburn  7394:                     $$tstatus='expired';
                   7395:                 } elsif ($$tend<$now) {
                   7396:                     $$tstatus='will_not';
                   7397:                 }
                   7398:             }
                   7399:         }
                   7400:     }
                   7401: }
                   7402: 
1.1104    raeburn  7403: sub get_groups_roles {
                   7404:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7405:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7406:                   (ref($rolecodes) eq 'ARRAY') && 
                   7407:                   (ref($groups_roles) eq 'HASH')); 
                   7408:     if (keys(%{$cdom_courseroles}) > 0) {
                   7409:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7410:         if ($cdom ne '' && $cnum ne '') {
                   7411:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7412:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7413:                     my $crsrole = $1;
                   7414:                     my $crssec = $2;
                   7415:                     if ($crsrole =~ /^cr/) {
                   7416:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7417:                             push(@{$rolecodes},'cr');
                   7418:                         }
                   7419:                     } else {
                   7420:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7421:                             push(@{$rolecodes},$crsrole);
                   7422:                         }
                   7423:                     }
                   7424:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7425:                     if ($crssec ne '') {
                   7426:                         $rolekey .= "/$crssec";
                   7427:                     }
                   7428:                     $rolekey .= './';
                   7429:                     $groups_roles->{$rolekey} = $rolecodes;
                   7430:                 }
                   7431:             }
                   7432:         }
                   7433:     }
                   7434:     return;
                   7435: }
                   7436: 
                   7437: sub delete_env_groupprivs {
                   7438:     my ($where,$courseroles,$possroles) = @_;
                   7439:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7440:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7441:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7442:         %{$courseroles->{$udom}} =
                   7443:             &get_my_roles('','','userroles',['active'],
                   7444:                           $possroles,[$udom],1);
                   7445:     }
                   7446:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7447:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7448:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7449:             my $area = '/'.$cdom.'/'.$cnum;
                   7450:             my $privkey = "user.priv.$crsrole.$area";
                   7451:             if ($crssec ne '') {
                   7452:                 $privkey .= '/'.$crssec;
                   7453:             }
                   7454:             $privkey .= ".$area/$group";
                   7455:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7456:         }
                   7457:     }
                   7458:     return;
                   7459: }
                   7460: 
1.994     raeburn  7461: sub check_adhoc_privs {
1.1329    raeburn  7462:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7463:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  7464:     if ($sec) {
                   7465:         $cckey .= '/'.$sec;
                   7466:     } 
1.1185    raeburn  7467:     my $setprivs;
1.994     raeburn  7468:     if ($env{$cckey}) {
                   7469:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7470:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7471:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  7472:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7473:             $setprivs = 1;
1.994     raeburn  7474:         }
                   7475:     } else {
1.1330    raeburn  7476:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7477:         $setprivs = 1;
1.994     raeburn  7478:     }
1.1185    raeburn  7479:     return $setprivs;
1.994     raeburn  7480: }
                   7481: 
                   7482: sub set_adhoc_privileges {
1.1326    raeburn  7483: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  7484:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7485:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  7486:     if ($sec ne '') {
                   7487:         $area .= '/'.$sec;
                   7488:     }
1.994     raeburn  7489:     my $spec = $role.'.'.$area;
                   7490:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  7491:                                   $env{'user.name'},1);
1.1326    raeburn  7492:     my %rolehash = ();
1.1332    raeburn  7493:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7494:         my $rolename = $1;
1.1326    raeburn  7495:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  7496:         my %domdef = &get_domain_defaults($dcdom);
                   7497:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7498:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7499:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7500:             }
                   7501:         }
1.1326    raeburn  7502:     } else {
                   7503:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7504:     }
1.1341    raeburn  7505:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7506:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  7507:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  7508:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7509:             ($caller eq 'tiny')) {
1.1088    raeburn  7510:         &appenv( {'request.role'        => $spec,
                   7511:                   'request.role.domain' => $dcdom,
1.1332    raeburn  7512:                   'request.course.sec'  => $sec,
1.1088    raeburn  7513:                  }
                   7514:                );
                   7515:         my $tadv=0;
                   7516:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7517:         &appenv({'request.role.adv'    => $tadv});
                   7518:     }
1.994     raeburn  7519: }
                   7520: 
1.12      www      7521: # --------------------------------------------------------------- get interface
                   7522: 
                   7523: sub get {
1.131     albertel 7524:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7525:    my $items='';
1.800     albertel 7526:    foreach my $item (@$storearr) {
                   7527:        $items.=&escape($item).'&';
1.191     harris41 7528:    }
1.12      www      7529:    $items=~s/\&$//;
1.620     albertel 7530:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7531:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7532:    my $uhome=&homeserver($uname,$udomain);
                   7533: 
1.133     albertel 7534:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7535:    my @pairs=split(/\&/,$rep);
1.273     albertel 7536:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7537:      return @pairs;
                   7538:    }
1.15      www      7539:    my %returnhash=();
1.42      www      7540:    my $i=0;
1.800     albertel 7541:    foreach my $item (@$storearr) {
                   7542:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7543:       $i++;
1.191     harris41 7544:    }
1.15      www      7545:    return %returnhash;
1.27      www      7546: }
                   7547: 
                   7548: # --------------------------------------------------------------- del interface
                   7549: 
                   7550: sub del {
1.133     albertel 7551:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7552:    my $items='';
1.800     albertel 7553:    foreach my $item (@$storearr) {
                   7554:        $items.=&escape($item).'&';
1.191     harris41 7555:    }
1.984     neumanie 7556: 
1.27      www      7557:    $items=~s/\&$//;
1.620     albertel 7558:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7559:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7560:    my $uhome=&homeserver($uname,$udomain);
                   7561:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7562: }
                   7563: 
                   7564: # -------------------------------------------------------------- dump interface
                   7565: 
1.1180    droeschl 7566: sub unserialize {
                   7567:     my ($rep, $escapedkeys) = @_;
                   7568: 
                   7569:     return {} if $rep =~ /^error/;
                   7570: 
                   7571:     my %returnhash=();
1.1252    raeburn  7572: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7573: 	    my ($key, $value) = split(/=/, $item, 2);
                   7574: 	    $key = unescape($key) unless $escapedkeys;
                   7575: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7576: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7577: 	}
                   7578:     #return %returnhash;
                   7579:     return \%returnhash;
                   7580: }        
                   7581: 
                   7582: # see Lond::dump_with_regexp
                   7583: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7584: sub dump {
1.1462    raeburn  7585:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7586:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7587:     if (!$uname) { $uname=$env{'user.name'}; }
                   7588:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7589: 
1.1266    raeburn  7590:     if ($regexp) {
                   7591:         $regexp=&escape($regexp);
                   7592:     } else {
                   7593:         $regexp='.';
                   7594:     }
1.1180    droeschl 7595:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7596:         # user is hosted on this machine
1.1266    raeburn  7597:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7598:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7599:         return %{unserialize($reply, $escapedkeys)};
                   7600:     }
1.1462    raeburn  7601:     my $rep;
                   7602:     if ($encrypt) {
                   7603:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463    raeburn  7604:     } else {
1.1462    raeburn  7605:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7606:     }
1.755     albertel 7607:     my @pairs=split(/\&/,$rep);
                   7608:     my %returnhash=();
1.1098    foxr     7609:     if (!($rep =~ /^error/ )) {
                   7610: 	foreach my $item (@pairs) {
                   7611: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7612:         $key = unescape($key) unless $escapedkeys;
                   7613:         #$key = &unescape($key);
1.1098    foxr     7614: 	    next if ($key =~ /^error: 2 /);
                   7615: 	    $returnhash{$key}=&thaw_unescape($value);
                   7616: 	}
1.755     albertel 7617:     }
                   7618:     return %returnhash;
1.407     www      7619: }
                   7620: 
1.1098    foxr     7621: 
1.717     albertel 7622: # --------------------------------------------------------- dumpstore interface
                   7623: 
                   7624: sub dumpstore {
                   7625:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7626:    # same as dump but keys must be escaped. They may contain colon separated
                   7627:    # lists of values that may themself contain colons (e.g. symbs).
                   7628:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7629: }
                   7630: 
1.407     www      7631: # -------------------------------------------------------------- keys interface
                   7632: 
                   7633: sub getkeys {
                   7634:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7635:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7636:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7637:    my $uhome=&homeserver($uname,$udomain);
                   7638:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7639:    my @keyarray=();
1.800     albertel 7640:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7641:       next if ($key =~ /^error: 2 /);
1.800     albertel 7642:       push(@keyarray,&unescape($key));
1.407     www      7643:    }
                   7644:    return @keyarray;
1.318     matthew  7645: }
                   7646: 
1.319     matthew  7647: # --------------------------------------------------------------- currentdump
                   7648: sub currentdump {
1.328     matthew  7649:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7650:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7651:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7652:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7653:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7654:    my $rep;
                   7655: 
                   7656:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7657:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7658:                    $courseid)));
                   7659:    } else {
                   7660:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7661:    }
                   7662: 
1.318     matthew  7663:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7664:    #
1.318     matthew  7665:    my %returnhash=();
1.319     matthew  7666:    #
1.1343    raeburn  7667:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7668:        # an old lond will not know currentdump
                   7669:        # Do a dump and make it look like a currentdump
1.822     albertel 7670:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7671:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7672:        my %hash = @tmp;
                   7673:        @tmp=();
1.424     matthew  7674:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7675:    } else {
                   7676:        my @pairs=split(/\&/,$rep);
1.800     albertel 7677:        foreach my $pair (@pairs) {
                   7678:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7679:            my ($symb,$param) = split(/:/,$key);
                   7680:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7681:                                                         &thaw_unescape($value);
1.319     matthew  7682:        }
1.191     harris41 7683:    }
1.12      www      7684:    return %returnhash;
1.424     matthew  7685: }
                   7686: 
                   7687: sub convert_dump_to_currentdump{
                   7688:     my %hash = %{shift()};
                   7689:     my %returnhash;
                   7690:     # Code ripped from lond, essentially.  The only difference
                   7691:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7692:     # we might run in to problems with parameter names =~ /^v\./
                   7693:     while (my ($key,$value) = each(%hash)) {
                   7694:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7695: 	$symb  = &unescape($symb);
                   7696: 	$param = &unescape($param);
1.424     matthew  7697:         next if ($v eq 'version' || $symb eq 'keys');
                   7698:         next if (exists($returnhash{$symb}) &&
                   7699:                  exists($returnhash{$symb}->{$param}) &&
                   7700:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7701:         $returnhash{$symb}->{$param}=$value;
                   7702:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7703:     }
                   7704:     #
                   7705:     # Remove all of the keys in the hashes which keep track of
                   7706:     # the version of the parameter.
                   7707:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7708:         # use a foreach because we are going to delete from the hash.
                   7709:         foreach my $key (keys(%$param_hash)) {
                   7710:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7711:         }
                   7712:     }
                   7713:     return \%returnhash;
1.12      www      7714: }
                   7715: 
1.627     albertel 7716: # ------------------------------------------------------ critical inc interface
                   7717: 
                   7718: sub cinc {
                   7719:     return &inc(@_,'critical');
                   7720: }
                   7721: 
1.449     matthew  7722: # --------------------------------------------------------------- inc interface
                   7723: 
                   7724: sub inc {
1.627     albertel 7725:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7726:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7727:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7728:     my $uhome=&homeserver($uname,$udomain);
                   7729:     my $items='';
                   7730:     if (! ref($store)) {
                   7731:         # got a single value, so use that instead
                   7732:         $items = &escape($store).'=&';
                   7733:     } elsif (ref($store) eq 'SCALAR') {
                   7734:         $items = &escape($$store).'=&';        
                   7735:     } elsif (ref($store) eq 'ARRAY') {
                   7736:         $items = join('=&',map {&escape($_);} @{$store});
                   7737:     } elsif (ref($store) eq 'HASH') {
                   7738:         while (my($key,$value) = each(%{$store})) {
                   7739:             $items.= &escape($key).'='.&escape($value).'&';
                   7740:         }
                   7741:     }
                   7742:     $items=~s/\&$//;
1.627     albertel 7743:     if ($critical) {
                   7744: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7745:     } else {
                   7746: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7747:     }
1.449     matthew  7748: }
                   7749: 
1.12      www      7750: # --------------------------------------------------------------- put interface
                   7751: 
                   7752: sub put {
1.1462    raeburn  7753:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7754:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7755:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7756:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7757:    my $items='';
1.800     albertel 7758:    foreach my $item (keys(%$storehash)) {
                   7759:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7760:    }
1.12      www      7761:    $items=~s/\&$//;
1.1462    raeburn  7762:    if ($encrypt) {
                   7763:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7764:    } else {
                   7765:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7766:    }
1.47      www      7767: }
                   7768: 
1.631     albertel 7769: # ------------------------------------------------------------ newput interface
                   7770: 
                   7771: sub newput {
                   7772:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7773:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7774:    if (!$uname) { $uname=$env{'user.name'}; }
                   7775:    my $uhome=&homeserver($uname,$udomain);
                   7776:    my $items='';
                   7777:    foreach my $key (keys(%$storehash)) {
                   7778:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7779:    }
                   7780:    $items=~s/\&$//;
                   7781:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7782: }
                   7783: 
                   7784: # ---------------------------------------------------------  putstore interface
                   7785: 
1.524     raeburn  7786: sub putstore {
1.1269    raeburn  7787:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7788:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7789:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7790:    my $uhome=&homeserver($uname,$udomain);
                   7791:    my $items='';
1.715     albertel 7792:    foreach my $key (keys(%$storehash)) {
                   7793:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7794:    }
1.715     albertel 7795:    $items=~s/\&$//;
1.716     albertel 7796:    my $esc_symb=&escape($symb);
                   7797:    my $esc_v=&escape($version);
1.715     albertel 7798:    my $reply =
1.716     albertel 7799:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7800: 	      $uhome);
1.1269    raeburn  7801:    if (($tolog) && ($reply eq 'ok')) {
                   7802:        my $namevalue='';
                   7803:        foreach my $key (keys(%{$storehash})) {
                   7804:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7805:        }
1.1434    raeburn  7806:        my $ip = &get_requestor_ip();
                   7807:        $namevalue .= 'ip='.&escape($ip).
1.1269    raeburn  7808:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7809:                      '&version='.$esc_v.
                   7810:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
1.1494    raeburn  7811:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
1.1269    raeburn  7812:    }
1.715     albertel 7813:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7814:        # gfall back to way things use to be done
1.715     albertel 7815:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7816: 			    $uname);
1.524     raeburn  7817:    }
1.715     albertel 7818:    return $reply;
                   7819: }
                   7820: 
                   7821: sub old_putstore {
1.716     albertel 7822:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7823:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7824:     if (!$uname) { $uname=$env{'user.name'}; }
                   7825:     my $uhome=&homeserver($uname,$udomain);
                   7826:     my %newstorehash;
1.800     albertel 7827:     foreach my $item (keys(%$storehash)) {
                   7828: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7829: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7830:     }
                   7831:     my $items='';
                   7832:     my %allitems = ();
1.800     albertel 7833:     foreach my $item (keys(%newstorehash)) {
                   7834: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7835: 	    my $key = $1.':keys:'.$2;
                   7836: 	    $allitems{$key} .= $3.':';
                   7837: 	}
1.800     albertel 7838: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7839:     }
1.800     albertel 7840:     foreach my $item (keys(%allitems)) {
                   7841: 	$allitems{$item} =~ s/\:$//;
                   7842: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7843:     }
                   7844:     $items=~s/\&$//;
                   7845:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7846: }
                   7847: 
1.47      www      7848: # ------------------------------------------------------ critical put interface
                   7849: 
                   7850: sub cput {
1.134     albertel 7851:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7852:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7853:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7854:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7855:    my $items='';
1.800     albertel 7856:    foreach my $item (keys(%$storehash)) {
                   7857:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7858:    }
1.47      www      7859:    $items=~s/\&$//;
1.134     albertel 7860:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7861: }
                   7862: 
                   7863: # -------------------------------------------------------------- eget interface
                   7864: 
                   7865: sub eget {
1.133     albertel 7866:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7867:    my $items='';
1.800     albertel 7868:    foreach my $item (@$storearr) {
                   7869:        $items.=&escape($item).'&';
1.191     harris41 7870:    }
1.12      www      7871:    $items=~s/\&$//;
1.620     albertel 7872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7873:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7874:    my $uhome=&homeserver($uname,$udomain);
                   7875:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7876:    my @pairs=split(/\&/,$rep);
                   7877:    my %returnhash=();
1.42      www      7878:    my $i=0;
1.800     albertel 7879:    foreach my $item (@$storearr) {
                   7880:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7881:       $i++;
1.191     harris41 7882:    }
1.12      www      7883:    return %returnhash;
                   7884: }
                   7885: 
1.667     albertel 7886: # ------------------------------------------------------------ tmpput interface
                   7887: sub tmpput {
1.802     raeburn  7888:     my ($storehash,$server,$context)=@_;
1.667     albertel 7889:     my $items='';
1.800     albertel 7890:     foreach my $item (keys(%$storehash)) {
                   7891: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7892:     }
                   7893:     $items=~s/\&$//;
1.802     raeburn  7894:     if (defined($context)) {
                   7895:         $items .= ':'.&escape($context);
                   7896:     }
1.667     albertel 7897:     return &reply("tmpput:$items",$server);
                   7898: }
                   7899: 
                   7900: # ------------------------------------------------------------ tmpget interface
                   7901: sub tmpget {
1.688     albertel 7902:     my ($token,$server)=@_;
                   7903:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7904:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7905:     my %returnhash;
1.1328    raeburn  7906:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7907:         return %returnhash;
                   7908:     }
1.667     albertel 7909:     foreach my $item (split(/\&/,$rep)) {
                   7910: 	my ($key,$value)=split(/=/,$item);
                   7911: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7912:     }
                   7913:     return %returnhash;
                   7914: }
                   7915: 
1.1113    raeburn  7916: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7917: sub tmpdel {
                   7918:     my ($token,$server)=@_;
                   7919:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7920:     return &reply("tmpdel:$token",$server);
                   7921: }
                   7922: 
1.1198    raeburn  7923: # ------------------------------------------------------------ get_timebased_id 
                   7924: 
                   7925: sub get_timebased_id {
                   7926:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7927:         $maxtries) = @_;
                   7928:     my ($newid,$error,$dellock);
                   7929:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7930:         return ('','ok','invalid call to get suffix');
                   7931:     }
                   7932: 
                   7933: # set defaults for any optional args for which values were not supplied
                   7934:     if ($who eq '') {
                   7935:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7936:     }
                   7937:     if (!$locktries) {
                   7938:         $locktries = 3;
                   7939:     }
                   7940:     if (!$maxtries) {
                   7941:         $maxtries = 10;
                   7942:     }
                   7943:     
                   7944:     if (($cdom eq '') || ($cnum eq '')) {
                   7945:         if ($env{'request.course.id'}) {
                   7946:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7947:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7948:         }
                   7949:         if (($cdom eq '') || ($cnum eq '')) {
                   7950:             return ('','ok','call to get suffix not in course context');
                   7951:         }
                   7952:     }
                   7953: 
                   7954: # construct locking item
                   7955:     my $lockhash = {
                   7956:                       $prefix."\0".'locked_'.$keyid => $who,
                   7957:                    };
                   7958:     my $tries = 0;
                   7959: 
                   7960: # attempt to get lock on nohist_$namespace file
1.1494    raeburn  7961:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198    raeburn  7962:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7963:         $tries ++;
                   7964:         sleep 1;
1.1494    raeburn  7965:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198    raeburn  7966:     }
                   7967: 
                   7968: # attempt to get unique identifier, based on current timestamp
                   7969:     if ($gotlock eq 'ok') {
1.1494    raeburn  7970:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
1.1198    raeburn  7971:         my $id = time;
                   7972:         $newid = $id;
1.1268    raeburn  7973:         if ($idtype eq 'addcode') {
                   7974:             $newid .= &sixnum_code();
                   7975:         }
1.1198    raeburn  7976:         my $idtries = 0;
                   7977:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7978:             if ($idtype eq 'concat') {
                   7979:                 $newid = $id.$idtries;
1.1268    raeburn  7980:             } elsif ($idtype eq 'addcode') {
                   7981:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7982:             } else {
                   7983:                 $newid ++;
                   7984:             }
                   7985:             $idtries ++;
                   7986:         }
                   7987:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7988:             my %new_item =  (
                   7989:                               $prefix."\0".$newid => $who,
                   7990:                             );
1.1494    raeburn  7991:             my $putresult = &put('nohist_'.$namespace,\%new_item,
1.1198    raeburn  7992:                                                  $cdom,$cnum);
                   7993:             if ($putresult ne 'ok') {
                   7994:                 undef($newid);
                   7995:                 $error = 'error saving new item: '.$putresult;
                   7996:             }
                   7997:         } else {
1.1268    raeburn  7998:              undef($newid);
1.1198    raeburn  7999:              $error = ('error: no unique suffix available for the new item ');
                   8000:         }
                   8001: #  remove lock
                   8002:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   8003:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   8004:     } else {
                   8005:         $error = "error: could not obtain lockfile\n";
                   8006:         $dellock = 'ok';
1.1276    raeburn  8007:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   8008:             $dellock = 'nolock';
                   8009:         }
1.1198    raeburn  8010:     }
                   8011:     return ($newid,$dellock,$error);
                   8012: }
                   8013: 
1.1268    raeburn  8014: sub sixnum_code {
                   8015:     my $code;
                   8016:     for (0..6) {
                   8017:         $code .= int( rand(9) );
                   8018:     }
                   8019:     return $code;
                   8020: }
                   8021: 
1.765     albertel 8022: # -------------------------------------------------- portfolio access checking
                   8023: 
                   8024: sub portfolio_access {
1.1270    raeburn  8025:     my ($requrl,$clientip) = @_;
1.765     albertel 8026:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  8027:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  8028:     if ($result) {
                   8029:         my %setters;
                   8030:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473    raeburn  8031:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   8032:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   8033:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8034:                 return 'B';
                   8035:             }
                   8036:         } else {
1.1473    raeburn  8037:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   8038:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8039:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8040:                 return 'B';
                   8041:             }
                   8042:         }
                   8043:     }
1.765     albertel 8044:     if ($result eq 'ok') {
1.766     albertel 8045:        return 'F';
1.765     albertel 8046:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 8047:        return 'A';
1.765     albertel 8048:     }
1.766     albertel 8049:     return '';
1.765     albertel 8050: }
                   8051: 
                   8052: sub get_portfolio_access {
1.1521    raeburn  8053:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash,$portaccessref) = @_;
1.767     albertel 8054: 
                   8055:     if (!ref($access_hash)) {
                   8056: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   8057: 	my %access_controls = &get_access_controls($current_perms,$group,
                   8058: 						   $file_name);
                   8059: 	$access_hash = $access_controls{$file_name};
                   8060:     }
                   8061: 
1.1521    raeburn  8062:     my $portaccess;
                   8063:     if (ref($portaccess) eq 'SCALAR') {
                   8064:         $portaccess = $$portaccessref;
                   8065:     } else {
                   8066:         $portaccess = &usertools_access($unum,$udom,'portaccess',undef,'tools');
                   8067:     }
                   8068: 
1.1522    raeburn  8069:     my ($public,$guest,@domains,@users,@courses,@groups,@ips,@userips);
1.765     albertel 8070:     my $now = time;
                   8071:     if (ref($access_hash) eq 'HASH') {
                   8072:         foreach my $key (keys(%{$access_hash})) {
                   8073:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1521    raeburn  8074:             next if (($scope ne 'ip') && ($portaccess == 0));
1.765     albertel 8075:             if ($start > $now) {
                   8076:                 next;
                   8077:             }
                   8078:             if ($end && $end<$now) {
                   8079:                 next;
                   8080:             }
                   8081:             if ($scope eq 'public') {
                   8082:                 $public = $key;
                   8083:                 last;
                   8084:             } elsif ($scope eq 'guest') {
                   8085:                 $guest = $key;
                   8086:             } elsif ($scope eq 'domains') {
                   8087:                 push(@domains,$key);
                   8088:             } elsif ($scope eq 'users') {
                   8089:                 push(@users,$key);
                   8090:             } elsif ($scope eq 'course') {
                   8091:                 push(@courses,$key);
                   8092:             } elsif ($scope eq 'group') {
                   8093:                 push(@groups,$key);
1.1270    raeburn  8094:             } elsif ($scope eq 'ip') {
                   8095:                 push(@ips,$key);
1.1522    raeburn  8096:             } elsif ($scope eq 'userip') {
                   8097:                 push(@userips,$key);
1.765     albertel 8098:             }
                   8099:         }
                   8100:         if ($public) {
                   8101:             return 'ok';
1.1270    raeburn  8102:         } elsif (@ips > 0) {
                   8103:             my $allowed;
                   8104:             foreach my $ipkey (@ips) {
                   8105:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   8106:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   8107:                         $allowed = 1;
                   8108:                         last; 
                   8109:                     }
                   8110:                 }
                   8111:             }
                   8112:             if ($allowed) {
                   8113:                 return 'ok';
                   8114:             }
1.1522    raeburn  8115:         } elsif (@userips > 0) {
                   8116:             my $allowed;
                   8117:             foreach my $useripkey (@userips) {
                   8118:                 if (ref($access_hash->{$useripkey}{'ip'}) eq 'ARRAY') {
                   8119:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$useripkey}{'ip'}}),$clientip)) {
                   8120:                         $allowed = 1;
                   8121:                         last;
                   8122:                     }
                   8123:                 }
                   8124:             }
                   8125:             if ($allowed) {
                   8126:                 return 'ok';
                   8127:             }
1.765     albertel 8128:         }
                   8129:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   8130:             if ($guest) {
                   8131:                 return $guest;
                   8132:             }
                   8133:         } else {
                   8134:             if (@domains > 0) {
                   8135:                 foreach my $domkey (@domains) {
                   8136:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   8137:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   8138:                             return 'ok';
                   8139:                         }
                   8140:                     }
                   8141:                 }
                   8142:             }
                   8143:             if (@users > 0) {
                   8144:                 foreach my $userkey (@users) {
1.865     raeburn  8145:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   8146:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   8147:                             if (ref($item) eq 'HASH') {
                   8148:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   8149:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   8150:                                     return 'ok';
                   8151:                                 }
                   8152:                             }
                   8153:                         }
                   8154:                     } 
1.765     albertel 8155:                 }
                   8156:             }
                   8157:             my %roleshash;
                   8158:             my @courses_and_groups = @courses;
                   8159:             push(@courses_and_groups,@groups); 
                   8160:             if (@courses_and_groups > 0) {
                   8161:                 my (%allgroups,%allroles); 
                   8162:                 my ($start,$end,$role,$sec,$group);
                   8163:                 foreach my $envkey (%env) {
1.1060    raeburn  8164:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 8165:                         my $cid = $2.'_'.$3; 
                   8166:                         if ($1 eq 'gr') {
                   8167:                             $group = $4;
                   8168:                             $allgroups{$cid}{$group} = $env{$envkey};
                   8169:                         } else {
                   8170:                             if ($4 eq '') {
                   8171:                                 $sec = 'none';
                   8172:                             } else {
                   8173:                                 $sec = $4;
                   8174:                             }
                   8175:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   8176:                         }
1.811     albertel 8177:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 8178:                         my $cid = $2.'_'.$3;
                   8179:                         if ($4 eq '') {
                   8180:                             $sec = 'none';
                   8181:                         } else {
                   8182:                             $sec = $4;
                   8183:                         }
                   8184:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   8185:                     }
                   8186:                 }
                   8187:                 if (keys(%allroles) == 0) {
                   8188:                     return;
                   8189:                 }
                   8190:                 foreach my $key (@courses_and_groups) {
                   8191:                     my %content = %{$$access_hash{$key}};
                   8192:                     my $cnum = $content{'number'};
                   8193:                     my $cdom = $content{'domain'};
                   8194:                     my $cid = $cdom.'_'.$cnum;
                   8195:                     if (!exists($allroles{$cid})) {
                   8196:                         next;
                   8197:                     }    
                   8198:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   8199:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   8200:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   8201:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   8202:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   8203:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   8204:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   8205:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   8206:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   8207:                                         if (grep/^all$/,@sections) {
                   8208:                                             return 'ok';
                   8209:                                         } else {
                   8210:                                             if (grep/^$sec$/,@sections) {
                   8211:                                                 return 'ok';
                   8212:                                             }
                   8213:                                         }
                   8214:                                     }
                   8215:                                 }
                   8216:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   8217:                                     if (grep/^none$/,@groups) {
                   8218:                                         return 'ok';
                   8219:                                     }
                   8220:                                 } else {
                   8221:                                     if (grep/^all$/,@groups) {
                   8222:                                         return 'ok';
                   8223:                                     } 
                   8224:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   8225:                                         if (grep/^$group$/,@groups) {
                   8226:                                             return 'ok';
                   8227:                                         }
                   8228:                                     }
                   8229:                                 } 
                   8230:                             }
                   8231:                         }
                   8232:                     }
                   8233:                 }
                   8234:             }
                   8235:             if ($guest) {
                   8236:                 return $guest;
                   8237:             }
                   8238:         }
                   8239:     }
                   8240:     return;
                   8241: }
                   8242: 
                   8243: sub course_group_datechecker {
                   8244:     my ($dates,$now,$status) = @_;
                   8245:     my ($start,$end) = split(/\./,$dates);
                   8246:     if (!$start && !$end) {
                   8247:         return 'ok';
                   8248:     }
                   8249:     if (grep/^active$/,@{$status}) {
                   8250:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   8251:             return 'ok';
                   8252:         }
                   8253:     }
                   8254:     if (grep/^previous$/,@{$status}) {
                   8255:         if ($end > $now ) {
                   8256:             return 'ok';
                   8257:         }
                   8258:     }
                   8259:     if (grep/^future$/,@{$status}) {
                   8260:         if ($start > $now) {
                   8261:             return 'ok';
                   8262:         }
                   8263:     }
                   8264:     return; 
                   8265: }
                   8266: 
                   8267: sub parse_portfolio_url {
                   8268:     my ($url) = @_;
                   8269: 
                   8270:     my ($type,$udom,$unum,$group,$file_name);
                   8271:     
1.823     albertel 8272:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 8273: 	$type = 1;
                   8274:         $udom = $1;
                   8275:         $unum = $2;
                   8276:         $file_name = $3;
1.823     albertel 8277:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 8278: 	$type = 2;
                   8279:         $udom = $1;
                   8280:         $unum = $2;
                   8281:         $group = $3;
                   8282:         $file_name = $3.'/'.$4;
                   8283:     }
                   8284:     if (wantarray) {
                   8285: 	return ($type,$udom,$unum,$file_name,$group);
                   8286:     }
                   8287:     return $type;
                   8288: }
                   8289: 
                   8290: sub is_portfolio_url {
                   8291:     my ($url) = @_;
                   8292:     return scalar(&parse_portfolio_url($url));
                   8293: }
                   8294: 
1.798     raeburn  8295: sub is_portfolio_file {
                   8296:     my ($file) = @_;
1.820     raeburn  8297:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  8298:         return 1;
                   8299:     }
                   8300:     return;
                   8301: }
                   8302: 
1.1504    raeburn  8303: sub is_coursetool_logo {
                   8304:     my ($uri) = @_;
                   8305:     if ($env{'request.course.id'}) {
                   8306:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8307:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
                   8308:             return 1;
                   8309:         }
                   8310:     }
                   8311:     return;
                   8312: }
                   8313: 
1.976     raeburn  8314: sub usertools_access {
1.1084    raeburn  8315:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  8316:     my ($access,%tools);
                   8317:     if ($context eq '') {
                   8318:         $context = 'tools';
                   8319:     }
                   8320:     if ($context eq 'requestcourses') {
                   8321:         %tools = (
                   8322:                       official   => 1,
                   8323:                       unofficial => 1,
1.1006    raeburn  8324:                       community  => 1,
1.1246    raeburn  8325:                       textbook   => 1,
1.1305    raeburn  8326:                       placement  => 1,
1.1368    raeburn  8327:                       lti        => 1,
1.985     raeburn  8328:                  );
1.1183    raeburn  8329:     } elsif ($context eq 'requestauthor') {
                   8330:         %tools = (
                   8331:                       requestauthor => 1,
                   8332:                  );
1.1517    raeburn  8333:     } elsif ($context eq 'authordefaults') {
                   8334:         %tools = (
                   8335:                       webdav    => 1,
                   8336:                  );
1.985     raeburn  8337:     } else {
                   8338:         %tools = (
                   8339:                       aboutme   => 1,
                   8340:                       blog      => 1,
1.1526    raeburn  8341:                       webdav    => 1,
1.985     raeburn  8342:                       portfolio => 1,
1.1517    raeburn  8343:                       portaccess => 1,
1.1489    raeburn  8344:                       timezone  => 1,
1.985     raeburn  8345:                  );
                   8346:     }
1.976     raeburn  8347:     return if (!defined($tools{$tool}));
                   8348: 
1.1242    raeburn  8349:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  8350:         $udom = $env{'user.domain'};
                   8351:         $uname = $env{'user.name'};
                   8352:     }
                   8353: 
1.978     raeburn  8354:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   8355:         if ($action ne 'reload') {
1.985     raeburn  8356:             if ($context eq 'requestcourses') {
                   8357:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  8358:             } elsif ($context eq 'requestauthor') {
                   8359:                 return $env{'environment.canrequest.author'};
1.1517    raeburn  8360:             } elsif ($context eq 'authordefaults') {
                   8361:                 if ($tool eq 'webdav') {
                   8362:                     return $env{'environment.availabletools.'.$tool};
                   8363:                 }
1.985     raeburn  8364:             } else {
                   8365:                 return $env{'environment.availabletools.'.$tool};
                   8366:             }
                   8367:         }
1.976     raeburn  8368:     }
                   8369: 
1.1183    raeburn  8370:     my ($toolstatus,$inststatus,$envkey);
                   8371:     if ($context eq 'requestauthor') {
1.1517    raeburn  8372:         $envkey = $context;
                   8373:     } elsif ($context eq 'authordefaults') {
                   8374:         if ($tool eq 'webdav') {
                   8375:             $envkey = 'tools.'.$tool;
                   8376:         }
1.1183    raeburn  8377:     } else {
                   8378:         $envkey = $context.'.'.$tool;
                   8379:     }
1.976     raeburn  8380: 
1.985     raeburn  8381:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8382:          ($action ne 'reload')) {
1.1183    raeburn  8383:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  8384:         $inststatus = $env{'environment.inststatus'};
                   8385:     } else {
1.1084    raeburn  8386:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  8387:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  8388:             $inststatus = $userenvref->{'inststatus'};
                   8389:         } else {
1.1183    raeburn  8390:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   8391:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  8392:             $inststatus = $userenv{'inststatus'};
                   8393:         }
1.976     raeburn  8394:     }
                   8395: 
                   8396:     if ($toolstatus ne '') {
                   8397:         if ($toolstatus) {
                   8398:             $access = 1;
                   8399:         } else {
                   8400:             $access = 0;
                   8401:         }
                   8402:         return $access;
                   8403:     }
                   8404: 
1.1084    raeburn  8405:     my ($is_adv,%domdef);
                   8406:     if (ref($is_advref) eq 'HASH') {
                   8407:         $is_adv = $is_advref->{'is_adv'};
                   8408:     } else {
                   8409:         $is_adv = &is_advanced_user($udom,$uname);
                   8410:     }
                   8411:     if (ref($domdefref) eq 'HASH') {
                   8412:         %domdef = %{$domdefref};
                   8413:     } else {
                   8414:         %domdef = &get_domain_defaults($udom);
                   8415:     }
1.976     raeburn  8416:     if (ref($domdef{$tool}) eq 'HASH') {
                   8417:         if ($is_adv) {
                   8418:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8419:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8420:                     $access = 1;
                   8421:                 } else {
                   8422:                     $access = 0;
                   8423:                 }
                   8424:                 return $access;
                   8425:             }
                   8426:         }
                   8427:         if ($inststatus ne '') {
                   8428:             my ($hasaccess,$hasnoaccess);
                   8429:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8430:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8431:                     if ($domdef{$tool}{$affiliation}) {
                   8432:                         $hasaccess = 1;
                   8433:                     } else {
                   8434:                         $hasnoaccess = 1;
                   8435:                     }
                   8436:                 }
                   8437:             }
                   8438:             if ($hasaccess || $hasnoaccess) {
                   8439:                 if ($hasaccess) {
                   8440:                     $access = 1;
                   8441:                 } elsif ($hasnoaccess) {
                   8442:                     $access = 0; 
                   8443:                 }
                   8444:                 return $access;
                   8445:             }
                   8446:         } else {
                   8447:             if ($domdef{$tool}{'default'} ne '') {
                   8448:                 if ($domdef{$tool}{'default'}) {
                   8449:                     $access = 1;
                   8450:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8451:                     $access = 0;
                   8452:                 }
                   8453:                 return $access;
                   8454:             }
                   8455:         }
                   8456:     } else {
1.1177    raeburn  8457:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8458:             $access = 1;
                   8459:         } else {
                   8460:             $access = 0;
                   8461:         }
1.976     raeburn  8462:         return $access;
                   8463:     }
                   8464: }
                   8465: 
1.1050    raeburn  8466: sub is_course_owner {
                   8467:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8468:     if (($udom eq '') || ($uname eq '')) {
                   8469:         $udom = $env{'user.domain'};
                   8470:         $uname = $env{'user.name'};
                   8471:     }
                   8472:     unless (($udom eq '') || ($uname eq '')) {
                   8473:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8474:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8475:                 return 1;
                   8476:             } else {
1.1494    raeburn  8477:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
1.1050    raeburn  8478:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8479:                     return 1;
                   8480:                 }
                   8481:             }
                   8482:         }
                   8483:     }
                   8484:     return;
                   8485: }
                   8486: 
1.976     raeburn  8487: sub is_advanced_user {
1.1512    raeburn  8488:     my ($udom,$uname,$nocache) = @_;
                   8489:     my ($is_adv,$is_author,$use_cache,$hashid);
1.1085    raeburn  8490:     if ($udom ne '' && $uname ne '') {
                   8491:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8492:             if (wantarray) {
                   8493:                 return ($env{'user.adv'},$env{'user.author'});
                   8494:             } else {
                   8495:                 return $env{'user.adv'};
                   8496:             }
1.1512    raeburn  8497:         } elsif (!$nocache) {
                   8498:             $use_cache = 1;
                   8499:             $hashid = "$udom:$uname";  
                   8500:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
                   8501:             if ($cached) {
                   8502:                 ($is_adv,$is_author) = split(/:/,$info);
                   8503:                 if (wantarray) {
                   8504:                     return ($is_adv,$is_author);
                   8505:                 }
                   8506:                 return $is_adv; 
                   8507:             }
1.1085    raeburn  8508:         }
                   8509:     }
1.976     raeburn  8510:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8511:     my %allroles;
                   8512:     foreach my $role (keys(%roleshash)) {
                   8513:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8514:         my $area = '/'.$tdomain.'/'.$trest;
                   8515:         if ($sec ne '') {
                   8516:             $area .= '/'.$sec;
                   8517:         }
                   8518:         if (($area ne '') && ($trole ne '')) {
                   8519:             my $spec=$trole.'.'.$area;
                   8520:             if ($trole =~ /^cr\//) {
                   8521:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8522:             } elsif ($trole ne 'gr') {
                   8523:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8524:             }
1.1128    raeburn  8525:             if ($trole eq 'au') {
                   8526:                 $is_author = 1;
                   8527:             }
1.976     raeburn  8528:         }
                   8529:     }
                   8530:     foreach my $role (keys(%allroles)) {
                   8531:         last if ($is_adv);
                   8532:         foreach my $item (split(/:/,$allroles{$role})) {
                   8533:             if ($item ne '') {
                   8534:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8535:                 if ($privilege eq 'adv') {
                   8536:                     $is_adv = 1;
                   8537:                     last;
                   8538:                 }
                   8539:             }
                   8540:         }
                   8541:     }
1.1512    raeburn  8542:     if ($use_cache) {
                   8543:         my $cachetime = 600;
                   8544:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
                   8545:     }
1.1128    raeburn  8546:     if (wantarray) {
                   8547:         return ($is_adv,$is_author);
                   8548:     }
1.976     raeburn  8549:     return $is_adv;
                   8550: }
1.798     raeburn  8551: 
1.1035    raeburn  8552: sub check_can_request {
1.1368    raeburn  8553:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8554:     my $canreq = 0;
1.1368    raeburn  8555:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8556:         $uname = $env{'user.name'};
                   8557:         $udom = $env{'user.domain'};
                   8558:     }
1.1035    raeburn  8559:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8560:     my @options = ('approval','validate','autolimit');
                   8561:     my $optregex = join('|',@options);
                   8562:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486    raeburn  8563:         my %willtrust;
1.1035    raeburn  8564:         foreach my $type (@{$types}) {
1.1368    raeburn  8565:             if (&usertools_access($uname,$udom,$type,undef,
                   8566:                                   'requestcourses')) {
1.1035    raeburn  8567:                 $canreq ++;
1.1036    raeburn  8568:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  8569:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8570:                 }
1.1368    raeburn  8571:                 if ($dom eq $udom) {
1.1035    raeburn  8572:                     $can_request->{$type} = 1;
                   8573:                 }
                   8574:             }
1.1368    raeburn  8575:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8576:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8577:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8578:                 if (@curr > 0) {
1.1036    raeburn  8579:                     foreach my $item (@curr) {
                   8580:                         if (ref($request_domains) eq 'HASH') {
                   8581:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8582:                             if ($otherdom ne '') {
1.1486    raeburn  8583:                                 unless (exists($willtrust{$otherdom})) {
                   8584:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
                   8585:                                 }
                   8586:                                 if ($willtrust{$otherdom}) {
                   8587:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8588:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8589:                                             push(@{$request_domains->{$type}},$otherdom);
                   8590:                                         }
                   8591:                                     } else {
1.1036    raeburn  8592:                                         push(@{$request_domains->{$type}},$otherdom);
                   8593:                                     }
                   8594:                                 }
                   8595:                             }
                   8596:                         }
                   8597:                     }
1.1368    raeburn  8598:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8599:                         $canreq ++;
1.1035    raeburn  8600:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8601:                             $can_request->{$type} = 1;
                   8602:                         }
                   8603:                     }
                   8604:                 }
                   8605:             }
                   8606:         }
                   8607:     }
                   8608:     return $canreq;
                   8609: }
                   8610: 
1.341     www      8611: # ---------------------------------------------- Custom access rule evaluation
                   8612: 
                   8613: sub customaccess {
                   8614:     my ($priv,$uri)=@_;
1.807     albertel 8615:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8616:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8617:     $udom = &LONCAPA::clean_domain($udom);
                   8618:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8619:     my $access=0;
1.800     albertel 8620:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8621: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8622: 	if ($type eq 'user') {
                   8623: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8624: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8625: 		if ($tdom) {
                   8626: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8627: 		}
1.896     albertel 8628: 		if ($tuname) {
                   8629: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8630: 		}
                   8631: 		$access=($effect eq 'allow');
                   8632: 		last;
                   8633: 	    }
                   8634: 	} else {
                   8635: 	    if ($role) {
                   8636: 		if ($role ne $urole) { next; }
                   8637: 	    }
                   8638: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8639: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8640: 		if ($tdom) {
                   8641: 		    if ($tdom ne $udom) { next; }
                   8642: 		}
                   8643: 		if ($tcrs) {
                   8644: 		    if ($tcrs ne $ucrs) { next; }
                   8645: 		}
                   8646: 		if ($tsec) {
                   8647: 		    if ($tsec ne $usec) { next; }
                   8648: 		}
                   8649: 		$access=($effect eq 'allow');
                   8650: 		last;
                   8651: 	    }
                   8652: 	    if ($realm eq '' && $role eq '') {
                   8653: 		$access=($effect eq 'allow');
                   8654: 	    }
1.402     bowersj2 8655: 	}
1.341     www      8656:     }
                   8657:     return $access;
                   8658: }
                   8659: 
1.103     harris41 8660: # ------------------------------------------------- Check for a user privilege
1.12      www      8661: 
                   8662: sub allowed {
1.1461    raeburn  8663:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8664:     my $ver_orguri=$uri;
1.439     www      8665:     $uri=&deversion($uri);
1.152     www      8666:     my $orguri=$uri;
1.52      www      8667:     $uri=&declutter($uri);
1.809     raeburn  8668: 
1.810     raeburn  8669:     if ($priv eq 'evb') {
1.1478    raeburn  8670: # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8671:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8672:             return $1;
                   8673:         } else {
                   8674:             return;
                   8675:         }
                   8676:     }
                   8677: 
1.620     albertel 8678:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8679: # Free bre access to adm and meta resources
1.1436    raeburn  8680:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8681: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8682: 	&& ($priv eq 'bre')) {
1.14      www      8683: 	return 'F';
1.159     www      8684:     }
                   8685: 
1.545     banghart 8686: # Free bre access to user's own portfolio contents
1.714     raeburn  8687:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8688:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8689: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8690:         my %setters;
1.1473    raeburn  8691:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8692:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8693:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8694:             return 'B';
                   8695:         } else {
                   8696:             return 'F';
                   8697:         }
1.545     banghart 8698:     }
                   8699: 
1.762     raeburn  8700: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8701:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8702:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8703:         if (exists($env{'request.course.id'})) {
                   8704:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8705:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8706:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8707:                 my $courseprivid=$env{'request.course.id'};
                   8708:                 $courseprivid=~s/\_/\//;
                   8709:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8710:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8711:                     return $1; 
1.762     raeburn  8712:                 } else {
                   8713:                     if ($env{'request.course.sec'}) {
                   8714:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8715:                     }
                   8716:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8717:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8718:                         return $2;
                   8719:                     }
1.714     raeburn  8720:                 }
                   8721:             }
                   8722:         }
                   8723:     }
                   8724: 
1.159     www      8725: # Free bre to public access
                   8726: 
                   8727:     if ($priv eq 'bre') {
1.1362    raeburn  8728:         my $copyright;
                   8729:         unless ($uri =~ /ext\.tool/) {
                   8730:             $copyright=&metadata($uri,'copyright');
                   8731:         }
1.620     albertel 8732: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8733:            return 'F'; 
                   8734:         }
1.238     www      8735:         if ($copyright eq 'priv') {
                   8736:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8737: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8738: 		return '';
                   8739:             }
                   8740:         }
                   8741:         if ($copyright eq 'domain') {
                   8742:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8743: 	    unless (($env{'user.domain'} eq $1) ||
                   8744:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8745: 		return '';
                   8746:             }
1.262     matthew  8747:         }
1.620     albertel 8748:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8749:             # Library role, so allow browsing of resources in this domain.
                   8750:             return 'F';
1.238     www      8751:         }
1.341     www      8752:         if ($copyright eq 'custom') {
                   8753: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8754:         }
1.14      www      8755:     }
1.264     matthew  8756:     # Domain coordinator is trying to create a course
1.620     albertel 8757:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8758:         # uri is the requested domain in this case.
                   8759:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8760:         # a role of dc for the domain in question.
1.620     albertel 8761:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8762:     }
1.29      www      8763: 
1.52      www      8764:     my $thisallowed='';
                   8765:     my $statecond=0;
                   8766:     my $courseprivid='';
                   8767: 
1.1039    raeburn  8768:     my $ownaccess;
1.1043    raeburn  8769:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8770:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8771:         if ($uri eq '') {
                   8772:             $ownaccess = 1;
                   8773:         } else {
                   8774:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8775:                 my $udom = $env{'user.domain'};
                   8776:                 my $uname = $env{'user.name'};
                   8777:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8778:                     $ownaccess = 1;
1.1040    raeburn  8779:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8780:                     unless ($uri =~ m{\.\./}) {
                   8781:                         $ownaccess = 1;
                   8782:                     }
                   8783:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8784:                     my $now = time;
                   8785:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8786:                         my $adom = $1;
                   8787:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8788:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452    raeburn  8789:                                 my ($start,$end) = split(/\./,$env{$key});
                   8790:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8791:                                     $ownaccess = 1;
                   8792:                                     last;
                   8793:                                 }
                   8794:                             }
                   8795:                         }
                   8796:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8797:                         my $adom = $1;
                   8798:                         my $aname = $2;
1.1042    raeburn  8799:                         foreach my $role ('ca','aa') { 
                   8800:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8801:                                 my ($start,$end) =
1.1452    raeburn  8802:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8803:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8804:                                     $ownaccess = 1;
                   8805:                                     last;
                   8806:                                 }
1.1039    raeburn  8807:                             }
                   8808:                         }
                   8809:                     }
                   8810:                 }
                   8811:             }
                   8812:         }
                   8813:     }
                   8814: 
1.52      www      8815: # Course
                   8816: 
1.620     albertel 8817:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8818:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8819:             $thisallowed.=$1;
                   8820:         }
1.52      www      8821:     }
1.29      www      8822: 
1.52      www      8823: # Domain
                   8824: 
1.620     albertel 8825:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8826:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8827:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8828:             $thisallowed.=$1;
                   8829:         }
1.12      www      8830:     }
1.52      www      8831: 
1.1141    raeburn  8832: # User who is not author or co-author might still be able to edit
                   8833: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8834:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8835:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8836:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8837:             $thisallowed.=$1;
                   8838:         }
                   8839:     }
                   8840: 
1.52      www      8841: # Course: uri itself is a course
1.66      www      8842:     my $courseuri=$uri;
                   8843:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8844:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8845: 
1.620     albertel 8846:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8847:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8848:         if ($priv eq 'mip') {
                   8849:             my $rem = $1;
                   8850:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8851:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8852:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8853:                 if ($cdom ne '') {
1.1410    raeburn  8854:                     my %passwdconf = &get_passwdconf($cdom);
                   8855:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8856:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8857:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8858:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8859:                                 unless (@inststatuses) {
                   8860:                                     @inststatuses = ('default');
                   8861:                                 }
                   8862:                                 foreach my $status (@inststatuses) {
                   8863:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8864:                                         $thisallowed.=$rem;
                   8865:                                     }
                   8866:                                 }
                   8867:                             }
                   8868:                         }
1.1409    raeburn  8869:                     }
                   8870:                 }
                   8871:             }
                   8872:         } else {
                   8873:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8874:                 $thisallowed.=$1;
                   8875:             }
1.1039    raeburn  8876:         }
1.12      www      8877:     }
1.29      www      8878: 
1.665     albertel 8879: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8880: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8881:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8882: 	$thisallowed='';
1.671     raeburn  8883:         my ($match)=&is_on_map($uri);
                   8884:         if ($match) {
                   8885:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8886:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8887:                 my $value = $1;
1.1461    raeburn  8888:                 my $deeplinkblock;
                   8889:                 unless ($nodeeplinkcheck) {
                   8890:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8891:                 }
1.1402    raeburn  8892:                 if ($deeplinkblock) {
                   8893:                     $thisallowed='D';
                   8894:                 } elsif ($noblockcheck) {
1.1281    raeburn  8895:                     $thisallowed.=$value;
1.1162    raeburn  8896:                 } else {
1.1424    raeburn  8897:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8898:                     if (@blockers > 0) {
                   8899:                         $thisallowed = 'B';
                   8900:                     } else {
                   8901:                         $thisallowed.=$value;
                   8902:                     }
1.1162    raeburn  8903:                 }
1.671     raeburn  8904:             }
                   8905:         } else {
1.705     albertel 8906:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8907:             if ($refuri) {
                   8908:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8909:                     $thisallowed='F';
1.671     raeburn  8910:                 } else {
                   8911:                     $refuri=&declutter($refuri);
                   8912:                     my ($match) = &is_on_map($refuri);
                   8913:                     if ($match) {
1.1461    raeburn  8914:                         my $deeplinkblock;
                   8915:                         unless ($nodeeplinkcheck) {
                   8916:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8917:                         }
1.1402    raeburn  8918:                         if ($deeplinkblock) {
                   8919:                             $thisallowed='D';
                   8920:                         } elsif ($noblockcheck) {
1.1281    raeburn  8921:                             $thisallowed='F';
1.1162    raeburn  8922:                         } else {
1.1426    raeburn  8923:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8924:                             if (@blockers > 0) {
                   8925:                                 $thisallowed = 'B';
                   8926:                             } else {
                   8927:                                 $thisallowed='F';
                   8928:                             }
1.1162    raeburn  8929:                         }
1.671     raeburn  8930:                     }
1.669     raeburn  8931:                 }
1.671     raeburn  8932:             }
                   8933:         }
1.314     www      8934:     }
1.492     albertel 8935: 
1.766     albertel 8936:     if ($priv eq 'bre'
                   8937: 	&& $thisallowed ne 'F' 
                   8938: 	&& $thisallowed ne '2'
                   8939: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8940: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8941:     }
1.1250    raeburn  8942: 
1.52      www      8943: # Full access at system, domain or course-wide level? Exit.
1.29      www      8944:     if ($thisallowed=~/F/) {
                   8945: 	return 'F';
                   8946:     }
                   8947: 
1.52      www      8948: # If this is generating or modifying users, exit with special codes
1.29      www      8949: 
1.1517    raeburn  8950:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
1.643     www      8951: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8952: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8953: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8954: 	    unless ($auname) { return $thisallowed; }
                   8955: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8956: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8957: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8958: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
1.1517    raeburn  8959: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
                   8960:             my ($audom,$auname)=split('/',$uri);
                   8961:             unless ($auname) { return $thisallowed; }
                   8962:             unless (($env{'request.role'} eq "dc./$audom") ||
                   8963:                     ($env{'request.role'} eq "ca./$uri")) {
                   8964:                 return '';
                   8965:             }
1.642     albertel 8966: 	}
1.52      www      8967: 	return $thisallowed;
                   8968:     }
                   8969: #
1.103     harris41 8970: # Gathered so far: system, domain and course wide privileges
1.52      www      8971: #
                   8972: # Course: See if uri or referer is an individual resource that is part of 
                   8973: # the course
                   8974: 
1.620     albertel 8975:     if ($env{'request.course.id'}) {
1.232     www      8976: 
1.1504    raeburn  8977:         if ($priv eq 'bre') {
                   8978:             if (&is_coursetool_logo($uri)) {
                   8979:                 return 'F';
                   8980:             }
                   8981:         }
                   8982: 
1.1409    raeburn  8983: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8984: 
                   8985:         if ($priv eq 'mip') {
                   8986:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8987:                 return $thisallowed;
                   8988:             } else {
                   8989:                 return '';
                   8990:             }
                   8991:         }
                   8992: 
1.620     albertel 8993:        $courseprivid=$env{'request.course.id'};
                   8994:        if ($env{'request.course.sec'}) {
                   8995:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8996:        }
                   8997:        $courseprivid=~s/\_/\//;
                   8998:        my $checkreferer=1;
1.232     www      8999:        my ($match,$cond)=&is_on_map($uri);
                   9000:        if ($match) {
                   9001:            $statecond=$cond;
1.620     albertel 9002:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 9003:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  9004:                my $value = $1;
                   9005:                if ($priv eq 'bre') {
1.1461    raeburn  9006:                    my $deeplinkblock;
                   9007:                    unless ($nodeeplinkcheck) {
                   9008:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   9009:                    }
1.1458    raeburn  9010:                    if ($deeplinkblock) {
                   9011:                        $thisallowed = 'D';
                   9012:                    } elsif ($noblockcheck) {
1.1281    raeburn  9013:                        $thisallowed.=$value;
1.1162    raeburn  9014:                    } else {
1.1424    raeburn  9015:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  9016:                        if (@blockers > 0) {
                   9017:                            $thisallowed = 'B';
                   9018:                        } else {
                   9019:                            $thisallowed.=$value;
                   9020:                        }
1.1162    raeburn  9021:                    }
                   9022:                } else {
                   9023:                    $thisallowed.=$value;
                   9024:                }
1.52      www      9025:                $checkreferer=0;
                   9026:            }
1.29      www      9027:        }
1.1424    raeburn  9028: 
1.148     www      9029:        if ($checkreferer) {
1.620     albertel 9030: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      9031:             unless ($refuri) {
1.800     albertel 9032:                 foreach my $key (keys(%env)) {
                   9033: 		    if ($key=~/^httpref\..*\*/) {
                   9034: 			my $pattern=$key;
1.156     www      9035:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      9036:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   9037:                         $pattern=~s/\//\\\//g;
1.152     www      9038:                         if ($orguri=~/$pattern/) {
1.800     albertel 9039: 			    $refuri=$env{$key};
1.148     www      9040:                         }
                   9041:                     }
1.191     harris41 9042:                 }
1.148     www      9043:             }
1.232     www      9044: 
1.148     www      9045:          if ($refuri) { 
1.152     www      9046: 	  $refuri=&declutter($refuri);
1.232     www      9047:           my ($match,$cond)=&is_on_map($refuri);
                   9048:             if ($match) {
                   9049:               my $refstatecond=$cond;
1.620     albertel 9050:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 9051:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  9052:                   my $value = $1;
                   9053:                   if ($priv eq 'bre') {
1.1461    raeburn  9054:                       my $deeplinkblock;
                   9055:                       unless ($nodeeplinkcheck) {
                   9056:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   9057:                       }
1.1402    raeburn  9058:                       if ($deeplinkblock) {
                   9059:                           $thisallowed = 'D';
                   9060:                       } elsif ($noblockcheck) {
1.1281    raeburn  9061:                           $thisallowed.=$value;
1.1162    raeburn  9062:                       } else {
1.1426    raeburn  9063:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  9064:                           if (@blockers > 0) {
                   9065:                               $thisallowed = 'B';
                   9066:                           } else {
                   9067:                               $thisallowed.=$value;
                   9068:                           }
1.1162    raeburn  9069:                       }
                   9070:                   } else {
                   9071:                       $thisallowed.=$value;
                   9072:                   }
1.53      www      9073:                   $uri=$refuri;
                   9074:                   $statecond=$refstatecond;
1.52      www      9075:               }
                   9076:           }
1.148     www      9077:         }
1.29      www      9078:        }
1.52      www      9079:    }
1.29      www      9080: 
1.52      www      9081: #
1.103     harris41 9082: # Gathered now: all privileges that could apply, and condition number
1.52      www      9083: # 
                   9084: #
                   9085: # Full or no access?
                   9086: #
1.29      www      9087: 
1.52      www      9088:     if ($thisallowed=~/F/) {
                   9089: 	return 'F';
                   9090:     }
1.29      www      9091: 
1.52      www      9092:     unless ($thisallowed) {
                   9093:         return '';
                   9094:     }
1.29      www      9095: 
1.52      www      9096: # Restrictions exist, deal with them
                   9097: #
                   9098: #   C:according to course preferences
                   9099: #   R:according to resource settings
                   9100: #   L:unless locked
                   9101: #   X:according to user session state
                   9102: #
                   9103: 
                   9104: # Possibly locked functionality, check all courses
1.1454    raeburn  9105: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      9106: # Locks might take effect only after 10 minutes cache expiration for other
1.1454    raeburn  9107: # courses, and 2 minutes for current course, in which user has st or ta role
                   9108: # which is neither expired nor a future role (unless current course).
1.52      www      9109: 
1.1454    raeburn  9110:     my ($needlockcheck,$now,$crsonly);
1.52      www      9111:     if ($thisallowed=~/L/) {
1.1454    raeburn  9112:         $now = time;
                   9113:         if ($priv eq 'bre') {
                   9114:             if ($uri ne '') {
                   9115:                 if ($orguri =~ m{^/+res/}) {
                   9116:                     if ($uri =~ m{^lib/templates/}) {
                   9117:                         if ($env{'request.course.id'}) {
                   9118:                             $crsonly = 1;
                   9119:                             $needlockcheck = 1;
                   9120:                         }
                   9121:                     } else {
                   9122:                         $needlockcheck = 1;
                   9123:                     }
                   9124:                 } elsif ($env{'request.course.id'}) {
                   9125:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   9126:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   9127:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   9128:                         $crsonly = 1;
                   9129:                     }
                   9130:                     $needlockcheck = 1;
                   9131:                 }
                   9132:             }
                   9133:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   9134:             $needlockcheck = 1;
                   9135:         }
                   9136:     }
                   9137:     if ($needlockcheck) {
1.1453    raeburn  9138:         foreach my $envkey (keys(%env)) {
1.54      www      9139:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   9140:                my $courseid=$2;
                   9141:                my $roleid=$1.'.'.$2;
1.92      www      9142:                $courseid=~s/^\///;
1.1453    raeburn  9143:                unless ($env{'request.role'} eq $roleid) {
                   9144:                    my ($start,$end) = split(/\./,$env{$envkey});
                   9145:                    next unless (($now >= $start) && (!$end || $end > $now));
                   9146:                }
1.54      www      9147:                my $expiretime=600;
1.620     albertel 9148:                if ($env{'request.role'} eq $roleid) {
1.54      www      9149: 		  $expiretime=120;
                   9150:                }
                   9151: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   9152:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 9153:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 9154: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      9155:                }
1.620     albertel 9156:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   9157:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   9158: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   9159:                        &log($env{'user.domain'},$env{'user.name'},
                   9160:                             $env{'user.home'},
1.57      www      9161:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      9162:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 9163:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      9164: 		       return '';
                   9165:                    }
                   9166:                }
1.620     albertel 9167:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   9168:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455    raeburn  9169: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 9170:                        &log($env{'user.domain'},$env{'user.name'},
                   9171:                             $env{'user.home'},
1.57      www      9172:                             'Locked by priv: '.$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:                }
                   9178: 	   }
1.29      www      9179:        }
1.52      www      9180:     }
1.1424    raeburn  9181: 
1.52      www      9182: #
                   9183: # Rest of the restrictions depend on selected course
                   9184: #
                   9185: 
1.620     albertel 9186:     unless ($env{'request.course.id'}) {
1.766     albertel 9187: 	if ($thisallowed eq 'A') {
                   9188: 	    return 'A';
1.814     raeburn  9189:         } elsif ($thisallowed eq 'B') {
                   9190:             return 'B';
1.766     albertel 9191: 	} else {
                   9192: 	    return '1';
                   9193: 	}
1.52      www      9194:     }
1.29      www      9195: 
1.52      www      9196: #
                   9197: # Now user is definitely in a course
                   9198: #
1.53      www      9199: 
                   9200: 
                   9201: # Course preferences
                   9202: 
                   9203:    if ($thisallowed=~/C/) {
1.620     albertel 9204:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   9205:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   9206:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 9207: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  9208: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 9209: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   9210: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   9211: 			$env{'request.course.id'});
                   9212: 	   }
1.237     www      9213:            return '';
                   9214:        }
                   9215: 
1.620     albertel 9216:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 9217: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  9218: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 9219: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   9220: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   9221: 			$env{'request.course.id'});
                   9222: 	   }
1.54      www      9223:            return '';
                   9224:        }
1.53      www      9225:    }
                   9226: 
                   9227: # Resource preferences
                   9228: 
                   9229:    if ($thisallowed=~/R/) {
1.620     albertel 9230:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 9231:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  9232: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 9233: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   9234: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   9235: 	   }
                   9236: 	   return '';
1.54      www      9237:        }
1.53      www      9238:    }
1.30      www      9239: 
1.1461    raeburn  9240: # Restricted for deeplinked session?
                   9241: 
                   9242:     if ($env{'request.deeplink.login'}) {
                   9243:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   9244:             if (!$symb) { $symb=&symbread($uri,1); }
                   9245:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   9246:                 return '';
                   9247:             }
                   9248:         }
                   9249:     }
                   9250: 
1.246     www      9251: # Restricted by state or randomout?
1.30      www      9252: 
1.52      www      9253:    if ($thisallowed=~/X/) {
1.620     albertel 9254:       if ($env{'acc.randomout'}) {
1.579     albertel 9255: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 9256:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      9257:             return ''; 
                   9258:          }
1.247     www      9259:       }
                   9260:       if (&condval($statecond)) {
1.52      www      9261: 	 return '2';
                   9262:       } else {
                   9263:          return '';
                   9264:       }
                   9265:    }
1.30      www      9266: 
1.766     albertel 9267:     if ($thisallowed eq 'A') {
                   9268: 	return 'A';
1.814     raeburn  9269:     } elsif ($thisallowed eq 'B') {
                   9270:         return 'B';
1.1402    raeburn  9271:     } elsif ($thisallowed eq 'D') {
                   9272:         return 'D';
1.766     albertel 9273:     }
1.52      www      9274:    return 'F';
1.232     www      9275: }
1.1162    raeburn  9276: 
1.1192    raeburn  9277: # ------------------------------------------- Check construction space access
                   9278: 
                   9279: sub constructaccess {
                   9280:     my ($url,$setpriv)=@_;
                   9281: 
                   9282: # We do not allow editing of previous versions of files
                   9283:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   9284: 
                   9285: # Get username and domain from URL
                   9286:     my ($ownername,$ownerdomain,$ownerhome);
                   9287: 
                   9288:     ($ownerdomain,$ownername) =
1.1325    raeburn  9289:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  9290: 
                   9291: # The URL does not really point to any authorspace, forget it
                   9292:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   9293: 
                   9294: # Now we need to see if the user has access to the authorspace of
                   9295: # $ownername at $ownerdomain
                   9296: 
                   9297:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   9298: # Real author for this?
                   9299:        $ownerhome = $env{'user.home'};
                   9300:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   9301:           return ($ownername,$ownerdomain,$ownerhome);
                   9302:        }
1.1506    raeburn  9303:     } elsif (&is_course($ownerdomain,$ownername)) {
                   9304: # Course Authoring Space?
1.1312    raeburn  9305:         if ($env{'request.course.id'}) {
                   9306:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   9307:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   9308:                 if (&allowed('mdc',$env{'request.course.id'})) {
1.1520    raeburn  9309:                     return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
                   9310:                     unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
                   9311:                         my %domdefs = &get_domain_defaults($ownerdomain);
                   9312:                         my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   9313:                         unless (($type eq 'community') || ($type eq 'placement')) {
                   9314:                             $type = 'unofficial';
                   9315:                             if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
                   9316:                                 $type = 'official';
                   9317:                             } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
                   9318:                                 $type = 'textbook';
                   9319:                             } else {
                   9320:                                 $type = 'unofficial';
                   9321:                             }
                   9322:                         }
                   9323:                         return if ($domdefs{$type.'crsauthor'} eq '0');
                   9324:                     }
1.1312    raeburn  9325:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   9326:                     return ($ownername,$ownerdomain,$ownerhome);
                   9327:                 }
                   9328:             }
                   9329:         }
1.1506    raeburn  9330:         return '';
                   9331:     } else {
                   9332: # Co-author for this?
                   9333:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   9334:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   9335:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   9336:             return ($ownername,$ownerdomain,$ownerhome);
                   9337:         }
1.1192    raeburn  9338:     }
                   9339: 
                   9340: # We don't have any access right now. If we are not possibly going to do anything about this,
                   9341: # we might as well leave
                   9342:    unless ($setpriv) { return ''; }
                   9343: 
                   9344: # Backdoor access?
                   9345:     my $allowed=&allowed('eco',$ownerdomain);
                   9346: # Nope
                   9347:     unless ($allowed) { return ''; }
                   9348: # Looks like we may have access, but could be locked by the owner of the construction space
                   9349:     if ($allowed eq 'U') {
                   9350:         my %blocked=&get('environment',['domcoord.author'],
                   9351:                          $ownerdomain,$ownername);
                   9352: # Is blocked by owner
                   9353:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   9354:     }
                   9355:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   9356: # Grant temporary access
                   9357:         my $then=$env{'user.login.time'};
1.1209    raeburn  9358:         my $update=$env{'user.update.time'};
1.1192    raeburn  9359:         if (!$update) { $update = $then; }
                   9360:         my $refresh=$env{'user.refresh.time'};
                   9361:         if (!$refresh) { $refresh = $update; }
                   9362:         my $now = time;
                   9363:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   9364:                            $now,'ca','constructaccess');
                   9365:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   9366:         return($ownername,$ownerdomain,$ownerhome);
                   9367:     }
                   9368: # No business here
                   9369:     return '';
                   9370: }
                   9371: 
1.1282    raeburn  9372: # ----------------------------------------------------------- Content Blocking
                   9373: 
                   9374: {
                   9375: # Caches for faster Course Contents display where content blocking
                   9376: # is in operation (i.e., interval param set) for timed quiz.
                   9377: #
                   9378: # User for whom data are being temporarily cached.
                   9379: my $cacheduser='';
1.1424    raeburn  9380: # Course for which data are being temporarily cached.
                   9381: my $cachedcid='';
1.1282    raeburn  9382: # Cached blockers for this user (a hash of blocking items). 
                   9383: my %cachedblockers=();
                   9384: # When the data were last cached.
                   9385: my $cachedlast='';
                   9386: 
                   9387: sub load_all_blockers {
1.1427    raeburn  9388:     my ($uname,$udom)=@_;
1.1282    raeburn  9389:     if (($uname ne '') && ($udom ne '')) { 
                   9390:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  9391:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  9392:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  9393:             return;
                   9394:         }
                   9395:     }
                   9396:     $cachedlast=time;
                   9397:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  9398:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  9399:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  9400:     return;
1.1282    raeburn  9401: }
                   9402: 
1.1162    raeburn  9403: sub get_comm_blocks {
                   9404:     my ($cdom,$cnum) = @_;
                   9405:     if ($cdom eq '' || $cnum eq '') {
                   9406:         return unless ($env{'request.course.id'});
                   9407:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9408:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9409:     }
                   9410:     my %commblocks;
                   9411:     my $hashid=$cdom.'_'.$cnum;
                   9412:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   9413:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   9414:         %commblocks = %{$blocksref};
                   9415:     } else {
1.1494    raeburn  9416:         %commblocks = &dump('comm_block',$cdom,$cnum);
1.1162    raeburn  9417:         my $cachetime = 600;
                   9418:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   9419:     }
                   9420:     return %commblocks;
                   9421: }
                   9422: 
1.1282    raeburn  9423: sub get_commblock_resources {
                   9424:     my ($blocks) = @_;
                   9425:     my %blockers = ();
                   9426:     return %blockers unless ($env{'request.course.id'});
1.1470    raeburn  9427:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9428:     if ($env{'request.course.sec'}) {
                   9429:         $courseurl .= '/'.$env{'request.course.sec'};
                   9430:     }
                   9431:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  9432:     my %commblocks;
                   9433:     if (ref($blocks) eq 'HASH') {
                   9434:         %commblocks = %{$blocks};
                   9435:     } else {
                   9436:         %commblocks = &get_comm_blocks();
                   9437:     }
1.1282    raeburn  9438:     return %blockers unless (keys(%commblocks) > 0); 
                   9439:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9440:     return %blockers unless (ref($navmap));
1.1162    raeburn  9441:     my $now = time;
                   9442:     foreach my $block (keys(%commblocks)) {
                   9443:         if ($block =~ /^(\d+)____(\d+)$/) {
                   9444:             my ($start,$end) = ($1,$2);
                   9445:             if ($start <= $now && $end >= $now) {
                   9446:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9447:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   9448:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  9449:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9450:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  9451:                             }
                   9452:                         }
                   9453:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  9454:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9455:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  9456:                             }
                   9457:                         }
                   9458:                     }
                   9459:                 }
                   9460:             }
                   9461:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   9462:             my $item = $1;
                   9463:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9464:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471    raeburn  9465:                     my (@interval,$mapname);
1.1282    raeburn  9466:                     my $type = 'map';
                   9467:                     if ($item eq 'course') {
                   9468:                         $type = 'course';
                   9469:                         @interval=&EXT("resource.0.interval");
                   9470:                     } else {
                   9471:                         if ($item =~ /___\d+___/) {
                   9472:                             $type = 'resource';
                   9473:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  9474:                         } else {
1.1471    raeburn  9475:                             $mapname = &deversion($item);
                   9476:                             if (ref($navmap)) {
                   9477:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9478:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9479:                             }
                   9480:                         }
1.1282    raeburn  9481:                     }
1.1310    raeburn  9482:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  9483:                         my $timelimit = $1; 
1.1282    raeburn  9484:                         my $first_access;
                   9485:                         if ($type eq 'resource') {
                   9486:                             $first_access=&get_first_access($interval[1],$item);
                   9487:                         } elsif ($type eq 'map') {
                   9488:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9489:                         } else {
                   9490:                             $first_access=&get_first_access($interval[1]);
                   9491:                         }
                   9492:                         if ($first_access) {
1.1292    raeburn  9493:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  9494:                             if ($timesup > $now) {
                   9495:                                 my $activeblock;
1.1471    raeburn  9496:                                 if ($type eq 'resource') {
                   9497:                                     if (ref($navmap)) {
                   9498:                                         my $res = $navmap->getBySymb($item);
                   9499:                                         if ($res->answerable()) {
                   9500:                                             $activeblock = 1;
                   9501:                                         }
                   9502:                                     }
                   9503:                                 } elsif ($type eq 'map') {
                   9504:                                     my $mapsymb = &symbread($mapname,1);
                   9505:                                     if (($mapsymb) && (ref($navmap))) {
                   9506:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9507:                                         if (ref($mapres)) {
                   9508:                                             my $first = $mapres->map_start();
                   9509:                                             my $finish = $mapres->map_finish();
                   9510:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9511:                                             if (ref($it)) {
                   9512:                                                 my $res;
                   9513:                                                 while ($res = $it->next(undef,1)) {
                   9514:                                                     next unless (ref($res));
                   9515:                                                     my $symb = $res->symb();
                   9516:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9517:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9518:                                                     if ($interval[1] eq 'map') {
                   9519:                                                         if ($res->answerable()) {
                   9520:                                                             $activeblock = 1;
                   9521:                                                             last;
                   9522:                                                         }
                   9523:                                                     }
                   9524:                                                 }
                   9525:                                             }
                   9526:                                         }
1.1282    raeburn  9527:                                     }
                   9528:                                 }
                   9529:                                 if ($activeblock) {
                   9530:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9531:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9532:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9533:                                          }
                   9534:                                     }
                   9535:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9536:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9537:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9538:                                         }
1.1162    raeburn  9539:                                     }
                   9540:                                 }
                   9541:                             }
                   9542:                         }
                   9543:                     }
                   9544:                 }
                   9545:             }
                   9546:         }
                   9547:     }
1.1282    raeburn  9548:     return %blockers;
1.1162    raeburn  9549: }
                   9550: 
1.1282    raeburn  9551: sub has_comm_blocking {
1.1427    raeburn  9552:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  9553:     my @blockers;
                   9554:     return unless ($env{'request.course.id'});
                   9555:     return unless ($priv eq 'bre');
                   9556:     return if ($env{'request.state'} eq 'construct');
1.1470    raeburn  9557:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9558:     if ($env{'request.course.sec'}) {
                   9559:         $courseurl .= '/'.$env{'request.course.sec'};
                   9560:     }
                   9561:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427    raeburn  9562:     my %blockinfo;
                   9563:     if (ref($blocks) eq 'HASH') {
                   9564:         %blockinfo = &get_commblock_resources($blocks);
                   9565:     } else {
                   9566:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9567:         %blockinfo = %cachedblockers;
                   9568:     }
                   9569:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  9570:     my (%possibles,@symbs);
                   9571:     if (!$symb) {
1.1427    raeburn  9572:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9573:     }
1.1282    raeburn  9574:     if ($symb) {
                   9575:         @symbs = ($symb);
                   9576:     } elsif (keys(%possibles)) { 
                   9577:         @symbs = keys(%possibles);
                   9578:     }
                   9579:     my $noblock;
                   9580:     foreach my $symb (@symbs) {
                   9581:         last if ($noblock);
                   9582:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  9583:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  9584:             if ($block =~ /^firstaccess____(.+)$/) {
                   9585:                 my $item = $1;
1.1424    raeburn  9586:                 unless ($blocked) {
                   9587:                     if (($item eq $map) || ($item eq $symb)) {
                   9588:                         $noblock = 1;
                   9589:                         last;
                   9590:                     }
1.1282    raeburn  9591:                 }
                   9592:             }
1.1427    raeburn  9593:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9594:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9595:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  9596:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9597:                             push(@blockers,$block);
                   9598:                         }
                   9599:                     }
                   9600:                 }
1.1427    raeburn  9601:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9602:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  9603:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9604:                             push(@blockers,$block);
                   9605:                         }
1.1282    raeburn  9606:                     }
                   9607:                 }
1.1162    raeburn  9608:             }
                   9609:         }
                   9610:     }
1.1424    raeburn  9611:     unless ($noblock) { 
                   9612:         return @blockers;
                   9613:     }
                   9614:     return;
1.1282    raeburn  9615: }
1.1162    raeburn  9616: }
                   9617: 
1.1402    raeburn  9618: sub deeplink_check {
                   9619:     my ($priv,$symb,$uri) = @_;
                   9620:     return unless ($env{'request.course.id'});
                   9621:     return unless ($priv eq 'bre');
                   9622:     return if ($env{'request.state'} eq 'construct');
                   9623:     return if ($env{'request.role.adv'});
                   9624:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9625:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9626:     my (%possibles,@symbs);
                   9627:     if (!$symb) {
                   9628:         $symb = &symbread($uri,1,1,1,\%possibles);
                   9629:     }
                   9630:     if ($symb) {
                   9631:         @symbs = ($symb);
                   9632:     } elsif (keys(%possibles)) {
                   9633:         @symbs = keys(%possibles);
                   9634:     }
                   9635: 
1.1461    raeburn  9636:     my ($deeplink_symb,$allow);
                   9637:     if ($env{'request.deeplink.login'}) {
                   9638:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402    raeburn  9639:     }
                   9640:     foreach my $symb (@symbs) {
                   9641:         last if ($allow);
                   9642:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9643:         if ($deeplink eq '') {
                   9644:             $allow = 1;
                   9645:         } else {
1.1463    raeburn  9646:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9647:             if ($state ne 'only') {
1.1402    raeburn  9648:                 $allow = 1;
1.1463    raeburn  9649:             } else {
                   9650:                 my $check_deeplink_entry;
                   9651:                 if ($protect ne 'none') {
                   9652:                     my ($acctype,$item) = split(/:/,$protect);
                   9653:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9654:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9655:                             $check_deeplink_entry = 1
                   9656:                         }
                   9657:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9658:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9659:                             $check_deeplink_entry = 1;
                   9660:                         }
                   9661:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9662:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9663:                             $check_deeplink_entry = 1;
                   9664:                         }
                   9665:                     }
                   9666:                 }
                   9667:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402    raeburn  9668:                     if ($scope eq 'res') {
1.1461    raeburn  9669:                         if ($symb eq $deeplink_symb) {
1.1402    raeburn  9670:                             $allow = 1;
                   9671:                         }
1.1459    raeburn  9672:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463    raeburn  9673:                         my ($map_from_symb,$map_from_login);
1.1461    raeburn  9674:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9675:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9676:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9677:                         } else {
                   9678:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9679:                         }
1.1459    raeburn  9680:                         if (($map_from_symb) && ($map_from_login)) {
                   9681:                             if ($map_from_symb eq $map_from_login) {
                   9682:                                 $allow = 1;
                   9683:                             } elsif ($scope eq 'rec') {
                   9684:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9685:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9686:                                     $allow = 1;
                   9687:                                 }
                   9688:                             }
                   9689:                         }
1.1402    raeburn  9690:                     }
                   9691:                 }
                   9692:             }
                   9693:         }
                   9694:     }
                   9695:     return if ($allow);
                   9696:     return 1;
                   9697: }
                   9698: 
1.1282    raeburn  9699: # -------------------------------- Deversion and split uri into path an filename   
                   9700: 
1.1133    foxr     9701: #
1.1282    raeburn  9702: #   Removes the version from a URI and
1.1133    foxr     9703: #   splits it in to its filename and path to the filename.
                   9704: #   Seems like File::Basename could have done this more clearly.
                   9705: #   Parameters:
                   9706: #      $uri   - input URI
                   9707: #   Returns:
                   9708: #     Two element list consisting of 
                   9709: #     $pathname  - the URI up to and excluding the trailing /
                   9710: #     $filename  - The part of the URI following the last /
                   9711: #  NOTE:
                   9712: #    Another realization of this is simply:
                   9713: #    use File::Basename;
                   9714: #    ...
                   9715: #    $uri = shift;
                   9716: #    $filename = basename($uri);
                   9717: #    $path     = dirname($uri);
                   9718: #    return ($filename, $path);
                   9719: #
                   9720: #     The implementation below is probably faster however.
                   9721: #
1.710     albertel 9722: sub split_uri_for_cond {
                   9723:     my $uri=&deversion(&declutter(shift));
                   9724:     my @uriparts=split(/\//,$uri);
                   9725:     my $filename=pop(@uriparts);
                   9726:     my $pathname=join('/',@uriparts);
                   9727:     return ($pathname,$filename);
                   9728: }
1.232     www      9729: # --------------------------------------------------- Is a resource on the map?
                   9730: 
                   9731: sub is_on_map {
1.710     albertel 9732:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9733:     #Trying to find the conditional for the file
1.620     albertel 9734:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9735: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9736:     if ($match) {
1.289     bowersj2 9737: 	return (1,$1);
                   9738:     } else {
1.434     www      9739: 	return (0,0);
1.289     bowersj2 9740:     }
1.12      www      9741: }
                   9742: 
1.427     www      9743: # --------------------------------------------------------- Get symb from alias
                   9744: 
                   9745: sub get_symb_from_alias {
                   9746:     my $symb=shift;
                   9747:     my ($map,$resid,$url)=&decode_symb($symb);
                   9748: # Already is a symb
                   9749:     if ($url) { return $symb; }
                   9750: # Must be an alias
                   9751:     my $aliassymb='';
                   9752:     my %bighash;
1.620     albertel 9753:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9754:                             &GDBM_READER(),0640)) {
                   9755:         my $rid=$bighash{'mapalias_'.$symb};
                   9756: 	if ($rid) {
                   9757: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9758: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9759: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9760: 	}
                   9761:         untie %bighash;
                   9762:     }
                   9763:     return $aliassymb;
                   9764: }
                   9765: 
1.12      www      9766: # ----------------------------------------------------------------- Define Role
                   9767: 
                   9768: sub definerole {
                   9769:   if (allowed('mcr','/')) {
1.1326    raeburn  9770:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9771:     foreach my $role (split(':',$sysrole)) {
                   9772: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9773:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9774:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9775: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9776:                return "refused:s:$crole&$cqual"; 
                   9777:             }
                   9778:         }
1.191     harris41 9779:     }
1.800     albertel 9780:     foreach my $role (split(':',$domrole)) {
                   9781: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9782:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9783:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9784: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9785:                return "refused:d:$crole&$cqual"; 
                   9786:             }
                   9787:         }
1.191     harris41 9788:     }
1.800     albertel 9789:     foreach my $role (split(':',$courole)) {
                   9790: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9791:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9792:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9793: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9794:                return "refused:c:$crole&$cqual"; 
                   9795:             }
                   9796:         }
1.191     harris41 9797:     }
1.1326    raeburn  9798:     my $uhome;
                   9799:     if (($uname ne '') && ($udom ne '')) {
                   9800:         $uhome = &homeserver($uname,$udom);
                   9801:         return $uhome if ($uhome eq 'no_host');
                   9802:     } else {
                   9803:         $uname = $env{'user.name'};
                   9804:         $udom = $env{'user.domain'};
                   9805:         $uhome = $env{'user.home'};
                   9806:     }
1.620     albertel 9807:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9808:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9809:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9810:     return reply($command,$uhome);
1.12      www      9811:   } else {
                   9812:     return 'refused';
                   9813:   }
1.105     harris41 9814: }
                   9815: 
                   9816: # ---------------- Make a metadata query against the network of library servers
                   9817: 
                   9818: sub metadata_query {
1.1237    raeburn  9819:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9820:     my %rhash;
1.845     albertel 9821:     my %libserv = &all_library();
1.244     matthew  9822:     my @server_list = (defined($server_array) ? @$server_array
                   9823:                                               : keys(%libserv) );
                   9824:     for my $server (@server_list) {
1.1237    raeburn  9825:         my $domains = ''; 
                   9826:         if (ref($domains_hash) eq 'HASH') {
                   9827:             $domains = $domains_hash->{$server}; 
                   9828:         }
1.118     harris41 9829: 	unless ($custom or $customshow) {
1.1237    raeburn  9830: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9831: 	    $rhash{$server}=$reply;
                   9832: 	}
                   9833: 	else {
                   9834: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9835: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9836: 			     $server);
                   9837: 	    $rhash{$server}=$reply;
                   9838: 	}
1.112     harris41 9839:     }
1.118     harris41 9840:     return \%rhash;
1.240     www      9841: }
                   9842: 
                   9843: # ----------------------------------------- Send log queries and wait for reply
                   9844: 
                   9845: sub log_query {
                   9846:     my ($uname,$udom,$query,%filters)=@_;
                   9847:     my $uhome=&homeserver($uname,$udom);
                   9848:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9849:     my $uhost=&hostname($uhome);
1.800     albertel 9850:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9851:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9852:                        $uhome);
1.479     albertel 9853:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9854:     return get_query_reply($queryid);
                   9855: }
                   9856: 
1.818     raeburn  9857: # -------------------------- Update MySQL table for portfolio file
                   9858: 
                   9859: sub update_portfolio_table {
1.821     raeburn  9860:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9861:     if ($group ne '') {
                   9862:         $file_name =~s /^\Q$group\E//;
                   9863:     }
1.818     raeburn  9864:     my $homeserver = &homeserver($uname,$udom);
                   9865:     my $queryid=
1.821     raeburn  9866:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9867:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9868:     my $reply = &get_query_reply($queryid);
                   9869:     return $reply;
                   9870: }
                   9871: 
1.899     raeburn  9872: # -------------------------- Update MySQL allusers table
                   9873: 
                   9874: sub update_allusers_table {
                   9875:     my ($uname,$udom,$names) = @_;
                   9876:     my $homeserver = &homeserver($uname,$udom);
                   9877:     my $queryid=
                   9878:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9879:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9880:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9881:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9882:                'generation='.&escape($names->{'generation'}).'%%'.
                   9883:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9884:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9885:     return;
1.899     raeburn  9886: }
                   9887: 
1.508     raeburn  9888: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9889: 
                   9890: sub fetch_enrollment_query {
1.511     raeburn  9891:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9892:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9893:     my $maxtries = 1;
1.508     raeburn  9894:     if ($context eq 'automated') {
                   9895:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9896:         $sleep = 2;
                   9897:         $loopmax = 100;
1.547     raeburn  9898:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9899:     } else {
                   9900:         $homeserver = &homeserver($cnum,$dom);
                   9901:     }
1.838     albertel 9902:     my $host=&hostname($homeserver);
1.506     raeburn  9903:     my $cmd = '';
1.1000    raeburn  9904:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9905:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9906:     }
                   9907:     $cmd =~ s/%%$//;
                   9908:     $cmd = &escape($cmd);
                   9909:     my $query = 'fetchenrollment';
1.620     albertel 9910:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9911:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9912:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9913:         return 'error: '.$queryid;
                   9914:     }
1.1317    raeburn  9915:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9916:     my $tries = 1;
                   9917:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9918:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9919:         $tries ++;
                   9920:     }
1.526     raeburn  9921:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9922:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9923:     } else {
1.901     albertel 9924:         my @responses = split(/:/,$reply);
1.1322    raeburn  9925:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9926:             foreach my $line (@responses) {
                   9927:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9928:                 $$replyref{$key} = $value;
                   9929:             }
                   9930:         } else {
1.1117    foxr     9931:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9932:             foreach my $line (@responses) {
                   9933:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9934:                 $$replyref{$key} = $value;
                   9935:                 if ($value > 0) {
1.800     albertel 9936:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9937:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9938:                         my $destname = $pathname.'/'.$filename;
                   9939:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9940:                         if ($xml_classlist =~ /^error/) {
                   9941:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9942:                         } else {
1.1359    raeburn  9943:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9944:                                 print FILE &unescape($xml_classlist);
                   9945:                                 close(FILE);
1.526     raeburn  9946:                             } else {
                   9947:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9948:                             }
                   9949:                         }
                   9950:                     }
                   9951:                 }
                   9952:             }
                   9953:         }
                   9954:         return 'ok';
                   9955:     }
                   9956:     return 'error';
                   9957: }
                   9958: 
1.242     www      9959: sub get_query_reply {
1.1471    raeburn  9960:     my ($queryid,$sleep,$loopmax) = @_;
1.1317    raeburn  9961:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9962:         $sleep = 0.2;
                   9963:     }
                   9964:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9965:         $loopmax = 100;
                   9966:     }
1.1117    foxr     9967:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9968:     my $reply='';
1.1317    raeburn  9969:     for (1..$loopmax) {
                   9970: 	sleep($sleep);
1.240     www      9971:         if (-e $replyfile.'.end') {
1.1359    raeburn  9972: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9973: 		$reply = join('',<$fh>);
                   9974: 		close($fh);
1.240     www      9975: 	   } else { return 'error: reply_file_error'; }
1.242     www      9976:            return &unescape($reply);
                   9977: 	}
1.240     www      9978:     }
1.242     www      9979:     return 'timeout:'.$queryid;
1.240     www      9980: }
                   9981: 
                   9982: sub courselog_query {
1.241     www      9983: #
                   9984: # possible filters:
                   9985: # url: url or symb
                   9986: # username
                   9987: # domain
                   9988: # action: view, submit, grade
                   9989: # start: timestamp
                   9990: # end: timestamp
                   9991: #
1.240     www      9992:     my (%filters)=@_;
1.620     albertel 9993:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9994:     if ($filters{'url'}) {
                   9995: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9996:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9997:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9998:     }
1.620     albertel 9999:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10000:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      10001:     return &log_query($cname,$cdom,'courselog',%filters);
                   10002: }
                   10003: 
                   10004: sub userlog_query {
1.858     raeburn  10005: #
                   10006: # possible filters:
                   10007: # action: log check role
                   10008: # start: timestamp
                   10009: # end: timestamp
                   10010: #
1.240     www      10011:     my ($uname,$udom,%filters)=@_;
                   10012:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      10013: }
                   10014: 
1.506     raeburn  10015: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   10016: 
                   10017: sub auto_run {
1.508     raeburn  10018:     my ($cnum,$cdom) = @_;
1.876     raeburn  10019:     my $response = 0;
                   10020:     my $settings;
                   10021:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   10022:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   10023:         $settings = $domconfig{'autoenroll'};
                   10024:         if ($settings->{'run'} eq '1') {
                   10025:             $response = 1;
                   10026:         }
                   10027:     } else {
1.934     raeburn  10028:         my $homeserver;
                   10029:         if (&is_course($cdom,$cnum)) {
                   10030:             $homeserver = &homeserver($cnum,$cdom);
                   10031:         } else {
                   10032:             $homeserver = &domain($cdom,'primary');
                   10033:         }
                   10034:         if ($homeserver ne 'no_host') {
                   10035:             $response = &reply('autorun:'.$cdom,$homeserver);
                   10036:         }
1.876     raeburn  10037:     }
1.506     raeburn  10038:     return $response;
                   10039: }
1.776     albertel 10040: 
1.506     raeburn  10041: sub auto_get_sections {
1.508     raeburn  10042:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  10043:     my $homeserver;
                   10044:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   10045:         $homeserver = &homeserver($cnum,$cdom);
                   10046:     }
                   10047:     if (!defined($homeserver)) { 
                   10048:         if ($cdom =~ /^$match_domain$/) {
                   10049:             $homeserver = &domain($cdom,'primary');
                   10050:         }
                   10051:     }
                   10052:     my @secs;
                   10053:     if (defined($homeserver)) {
                   10054:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   10055:         unless ($response eq 'refused') {
                   10056:             @secs = split(/:/,$response);
                   10057:         }
1.506     raeburn  10058:     }
                   10059:     return @secs;
                   10060: }
1.776     albertel 10061: 
1.506     raeburn  10062: sub auto_new_course {
1.1099    raeburn  10063:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  10064:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  10065:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  10066:     return $response;
                   10067: }
1.776     albertel 10068: 
1.506     raeburn  10069: sub auto_validate_courseID {
1.508     raeburn  10070:     my ($cnum,$cdom,$inst_course_id) = @_;
                   10071:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  10072:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  10073:     return $response;
                   10074: }
1.776     albertel 10075: 
1.1007    raeburn  10076: sub auto_validate_instcode {
1.1020    raeburn  10077:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  10078:     my ($homeserver,$response);
                   10079:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   10080:         $homeserver = &homeserver($cnum,$cdom);
                   10081:     }
                   10082:     if (!defined($homeserver)) {
                   10083:         if ($cdom =~ /^$match_domain$/) {
                   10084:             $homeserver = &domain($cdom,'primary');
                   10085:         }
                   10086:     }
1.1065    raeburn  10087:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   10088:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  10089:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   10090:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  10091: }
                   10092: 
1.1444    raeburn  10093: sub auto_validate_inst_crosslist {
                   10094:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   10095:     my ($homeserver,$response);
                   10096:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   10097:         $homeserver = &homeserver($cnum,$cdom);
                   10098:     }
                   10099:     if (!defined($homeserver)) {
                   10100:         if ($cdom =~ /^$match_domain$/) {
                   10101:             $homeserver = &domain($cdom,'primary');
                   10102:         }
                   10103:     }
                   10104:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   10105:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   10106:                          &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445    raeburn  10107:                          &escape($coowner),$homeserver);
1.1444    raeburn  10108:     }
                   10109:     return $response;
                   10110: }
                   10111: 
1.506     raeburn  10112: sub auto_create_password {
1.873     raeburn  10113:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   10114:     my ($homeserver,$response);
1.506     raeburn  10115:     my $create_passwd = 0;
                   10116:     my $authchk = '';
1.873     raeburn  10117:     if ($udom =~ /^$match_domain$/) {
                   10118:         $homeserver = &domain($udom,'primary');
                   10119:     }
                   10120:     if ($homeserver eq '') {
                   10121:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   10122:             $homeserver = &homeserver($cnum,$cdom);
                   10123:         }
                   10124:     }
                   10125:     if ($homeserver eq '') {
                   10126:         $authchk = 'nodomain';
1.506     raeburn  10127:     } else {
1.873     raeburn  10128:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   10129:         if ($response eq 'refused') {
                   10130:             $authchk = 'refused';
                   10131:         } else {
1.901     albertel 10132:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  10133:         }
1.506     raeburn  10134:     }
                   10135:     return ($authparam,$create_passwd,$authchk);
                   10136: }
                   10137: 
1.706     raeburn  10138: sub auto_photo_permission {
                   10139:     my ($cnum,$cdom,$students) = @_;
                   10140:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 10141:     my ($outcome,$perm_reqd,$conditions) = 
                   10142: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 10143:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   10144: 	return (undef,undef);
                   10145:     }
1.706     raeburn  10146:     return ($outcome,$perm_reqd,$conditions);
                   10147: }
                   10148: 
                   10149: sub auto_checkphotos {
                   10150:     my ($uname,$udom,$pid) = @_;
                   10151:     my $homeserver = &homeserver($uname,$udom);
                   10152:     my ($result,$resulttype);
                   10153:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 10154: 				   &escape($uname).':'.&escape($pid),
                   10155: 				   $homeserver));
1.709     albertel 10156:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   10157: 	return (undef,undef);
                   10158:     }
1.706     raeburn  10159:     if ($outcome) {
                   10160:         ($result,$resulttype) = split(/:/,$outcome);
                   10161:     } 
                   10162:     return ($result,$resulttype);
                   10163: }
                   10164: 
                   10165: sub auto_photochoice {
                   10166:     my ($cnum,$cdom) = @_;
                   10167:     my $homeserver = &homeserver($cnum,$cdom);
                   10168:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 10169: 						       &escape($cdom),
                   10170: 						       $homeserver)));
1.709     albertel 10171:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   10172: 	return (undef,undef);
                   10173:     }
1.706     raeburn  10174:     return ($update,$comment);
                   10175: }
                   10176: 
                   10177: sub auto_photoupdate {
                   10178:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   10179:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 10180:     my $host=&hostname($homeserver);
1.706     raeburn  10181:     my $cmd = '';
                   10182:     my $maxtries = 1;
1.800     albertel 10183:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   10184:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  10185:     }
                   10186:     $cmd =~ s/%%$//;
                   10187:     $cmd = &escape($cmd);
                   10188:     my $query = 'institutionalphotos';
                   10189:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   10190:     unless ($queryid=~/^\Q$host\E\_/) {
                   10191:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   10192:         return 'error: '.$queryid;
                   10193:     }
                   10194:     my $reply = &get_query_reply($queryid);
                   10195:     my $tries = 1;
                   10196:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   10197:         $reply = &get_query_reply($queryid);
                   10198:         $tries ++;
                   10199:     }
                   10200:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   10201:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   10202:     } else {
                   10203:         my @responses = split(/:/,$reply);
                   10204:         my $outcome = shift(@responses); 
                   10205:         foreach my $item (@responses) {
                   10206:             my ($key,$value) = split(/=/,$item);
                   10207:             $$photo{$key} = $value;
                   10208:         }
                   10209:         return $outcome;
                   10210:     }
                   10211:     return 'error';
                   10212: }
                   10213: 
1.521     raeburn  10214: sub auto_instcode_format {
1.793     albertel 10215:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   10216: 	$cat_order) = @_;
1.521     raeburn  10217:     my $courses = '';
1.772     raeburn  10218:     my @homeservers;
1.521     raeburn  10219:     if ($caller eq 'global') {
1.841     albertel 10220: 	my %servers = &get_servers($codedom,'library');
                   10221: 	foreach my $tryserver (keys(%servers)) {
                   10222: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10223: 		push(@homeservers,$tryserver);
                   10224: 	    }
1.584     raeburn  10225:         }
1.1022    raeburn  10226:     } elsif ($caller eq 'requests') {
                   10227:         if ($codedom =~ /^$match_domain$/) {
                   10228:             my $chome = &domain($codedom,'primary');
                   10229:             unless ($chome eq 'no_host') {
                   10230:                 push(@homeservers,$chome);
                   10231:             }
                   10232:         }
1.521     raeburn  10233:     } else {
1.772     raeburn  10234:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  10235:     }
1.793     albertel 10236:     foreach my $code (keys(%{$instcodes})) {
                   10237:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  10238:     }
                   10239:     chop($courses);
1.772     raeburn  10240:     my $ok_response = 0;
                   10241:     my $response;
                   10242:     while (@homeservers > 0 && $ok_response == 0) {
                   10243:         my $server = shift(@homeservers); 
                   10244:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   10245:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   10246:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 10247: 		split(/:/,$response);
1.772     raeburn  10248:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   10249:             push(@{$codetitles},&str2array($codetitles_str));
                   10250:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   10251:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   10252:             $ok_response = 1;
                   10253:         }
                   10254:     }
                   10255:     if ($ok_response) {
1.521     raeburn  10256:         return 'ok';
1.772     raeburn  10257:     } else {
                   10258:         return $response;
1.521     raeburn  10259:     }
                   10260: }
                   10261: 
1.792     raeburn  10262: sub auto_instcode_defaults {
                   10263:     my ($domain,$returnhash,$code_order) = @_;
                   10264:     my @homeservers;
1.841     albertel 10265: 
                   10266:     my %servers = &get_servers($domain,'library');
                   10267:     foreach my $tryserver (keys(%servers)) {
                   10268: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10269: 	    push(@homeservers,$tryserver);
                   10270: 	}
1.792     raeburn  10271:     }
1.841     albertel 10272: 
1.792     raeburn  10273:     my $response;
1.841     albertel 10274:     foreach my $server (@homeservers) {
1.792     raeburn  10275:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 10276:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   10277: 	
                   10278: 	foreach my $pair (split(/\&/,$response)) {
                   10279: 	    my ($name,$value)=split(/\=/,$pair);
                   10280: 	    if ($name eq 'code_order') {
                   10281: 		@{$code_order} = split(/\&/,&unescape($value));
                   10282: 	    } else {
                   10283: 		$returnhash->{&unescape($name)}=&unescape($value);
                   10284: 	    }
                   10285: 	}
                   10286: 	return 'ok';
1.792     raeburn  10287:     }
1.841     albertel 10288: 
                   10289:     return $response;
1.1003    raeburn  10290: }
                   10291: 
                   10292: sub auto_possible_instcodes {
1.1007    raeburn  10293:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   10294:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   10295:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10296:         return;
                   10297:     }
1.1003    raeburn  10298:     my (@homeservers,$uhome);
                   10299:     if (defined(&domain($domain,'primary'))) {
                   10300:         $uhome=&domain($domain,'primary');
                   10301:         push(@homeservers,&domain($domain,'primary'));
                   10302:     } else {
                   10303:         my %servers = &get_servers($domain,'library');
                   10304:         foreach my $tryserver (keys(%servers)) {
                   10305:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10306:                 push(@homeservers,$tryserver);
                   10307:             }
                   10308:         }
                   10309:     }
                   10310:     my $response;
                   10311:     foreach my $server (@homeservers) {
                   10312:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   10313:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  10314:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   10315:             split(':',$response);
                   10316:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   10317:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  10318:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  10319:             my ($name,$value)=split('=',$item);
                   10320:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  10321:         }
                   10322:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  10323:             my ($name,$value)=split('=',$item);
                   10324:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  10325:         }
                   10326:         return 'ok';
                   10327:     }
                   10328:     return $response;
                   10329: }
1.792     raeburn  10330: 
1.1010    raeburn  10331: sub auto_courserequest_checks {
                   10332:     my ($dom) = @_;
1.1020    raeburn  10333:     my ($homeserver,%validations);
                   10334:     if ($dom =~ /^$match_domain$/) {
                   10335:         $homeserver = &domain($dom,'primary');
                   10336:     }
                   10337:     unless ($homeserver eq 'no_host') {
                   10338:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   10339:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10340:             my @items = split(/&/,$response);
                   10341:             foreach my $item (@items) {
                   10342:                 my ($key,$value) = split('=',$item);
                   10343:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   10344:             }
                   10345:         }
                   10346:     }
1.1010    raeburn  10347:     return %validations; 
                   10348: }
                   10349: 
1.1020    raeburn  10350: sub auto_courserequest_validation {
1.1255    raeburn  10351:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  10352:     my ($homeserver,$response);
                   10353:     if ($dom =~ /^$match_domain$/) {
                   10354:         $homeserver = &domain($dom,'primary');
                   10355:     }
1.1255    raeburn  10356:     unless ($homeserver eq 'no_host') {
                   10357:         my $customdata;
                   10358:         if (ref($custominfo) eq 'HASH') {
                   10359:             $customdata = &freeze_escape($custominfo);
                   10360:         }
1.1020    raeburn  10361:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  10362:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  10363:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   10364:                                     $customdata,$homeserver));
1.1020    raeburn  10365:     }
                   10366:     return $response;
                   10367: }
                   10368: 
1.777     albertel 10369: sub auto_validate_class_sec {
1.918     raeburn  10370:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  10371:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  10372:     my $ownerlist;
                   10373:     if (ref($owners) eq 'ARRAY') {
                   10374:         $ownerlist = join(',',@{$owners});
                   10375:     } else {
                   10376:         $ownerlist = $owners;
                   10377:     }
1.773     raeburn  10378:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  10379:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  10380:     return $response;
                   10381: }
                   10382: 
1.1460    raeburn  10383: sub auto_instsec_reformat {
                   10384:     my ($cdom,$action,$instsecref) = @_;
                   10385:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   10386:     my @homeservers;
                   10387:     if (defined(&domain($cdom,'primary'))) {
                   10388:         push(@homeservers,&domain($cdom,'primary'));
                   10389:     } else {
                   10390:         my %servers = &get_servers($cdom,'library');
                   10391:         foreach my $tryserver (keys(%servers)) {
                   10392:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10393:                 push(@homeservers,$tryserver);
                   10394:             }
                   10395:         }
                   10396:     }
                   10397:     my $response;
                   10398:     my %reformatted = %{$instsecref};
                   10399:     foreach my $server (@homeservers) {
                   10400:         if (ref($instsecref) eq 'HASH') {
                   10401:             my $info = &freeze_escape($instsecref);
                   10402:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   10403:                                 $action.':'.$info,$server);
                   10404:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   10405:             my @items = split(/&/,$response);
                   10406:             foreach my $item (@items) {
                   10407:                 my ($key,$value) = split(/=/,$item);
                   10408:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   10409:             }
                   10410:         }
                   10411:     }
                   10412:     return %reformatted;
                   10413: }
                   10414: 
1.1367    raeburn  10415: sub auto_validate_instclasses {
                   10416:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   10417:     my ($homeserver,%validations);
                   10418:     $homeserver = &homeserver($cnum,$cdom);
                   10419:     unless ($homeserver eq 'no_host') {
                   10420:         my $ownerlist;
                   10421:         if (ref($owners) eq 'ARRAY') {
                   10422:             $ownerlist = join(',',@{$owners});
                   10423:         } else {
                   10424:             $ownerlist = $owners;
                   10425:         }
                   10426:         if (ref($classesref) eq 'HASH') {
                   10427:             my $classes = &freeze_escape($classesref);
                   10428:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   10429:                                 ':'.$cdom.':'.$classes,$homeserver);
                   10430:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10431:                 my @items = split(/&/,$response);
                   10432:                 foreach my $item (@items) {
                   10433:                     my ($key,$value) = split('=',$item);
                   10434:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   10435:                 }
                   10436:             }
                   10437:         }
                   10438:     }
                   10439:     return %validations;
                   10440: }
                   10441: 
1.1248    raeburn  10442: sub auto_crsreq_update {
                   10443:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  10444:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  10445:     my ($homeserver,%crsreqresponse);
                   10446:     if ($cdom =~ /^$match_domain$/) {
                   10447:         $homeserver = &domain($cdom,'primary');
                   10448:     }
                   10449:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10450:         my $info;
                   10451:         if (ref($inbound) eq 'HASH') {
                   10452:             $info = &freeze_escape($inbound);
                   10453:         }
                   10454:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   10455:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   10456:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  10457:                             &escape($title).':'.&escape($code).':'.
                   10458:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   10459:                             $homeserver);
1.1248    raeburn  10460:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10461:             my @items = split(/&/,$response);
                   10462:             foreach my $item (@items) {
                   10463:                 my ($key,$value) = split('=',$item);
                   10464:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   10465:             }
                   10466:         }
                   10467:     }
                   10468:     return \%crsreqresponse;
                   10469: }
                   10470: 
1.1305    raeburn  10471: sub auto_export_grades {
1.1309    raeburn  10472:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   10473:     my ($homeserver,%exportresponse);
                   10474:     if ($cdom =~ /^$match_domain$/) {
                   10475:         $homeserver = &domain($cdom,'primary');
                   10476:     }
                   10477:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10478:         my $info;
                   10479:         if (ref($inforef) eq 'HASH') {
                   10480:             $info = &freeze_escape($inforef);
                   10481:         }
                   10482:         if (ref($gradesref) eq 'HASH') {
                   10483:             my $grades = &freeze_escape($gradesref);
                   10484:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10485:                                 $info.':'.$grades,$homeserver);
                   10486:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10487:                 my @items = split(/&/,$response);
                   10488:                 foreach my $item (@items) {
                   10489:                     my ($key,$value) = split('=',$item);
                   10490:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10491:                 }
                   10492:             }
                   10493:         }
                   10494:     }
                   10495:     return \%exportresponse;
1.1305    raeburn  10496: }
                   10497: 
1.1287    raeburn  10498: sub check_instcode_cloning {
                   10499:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10500:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10501:         return;
                   10502:     }
                   10503:     my $canclone;
                   10504:     if (@{$code_order} > 0) {
                   10505:         my $instcoderegexp ='^';
                   10506:         my @clonecodes = split(/\&/,$cloner);
                   10507:         foreach my $item (@{$code_order}) {
                   10508:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10509:                 foreach my $pair (@clonecodes) {
                   10510:                     my ($key,$val) = split(/\=/,$pair,2);
                   10511:                     $val = &unescape($val);
                   10512:                     if ($key eq $item) {
                   10513:                         $instcoderegexp .= '('.$val.')';
                   10514:                         last;
                   10515:                     }
                   10516:                 }
                   10517:             } else {
                   10518:                 $instcoderegexp .= $codedefaults->{$item};
                   10519:             }
                   10520:         }
                   10521:         $instcoderegexp .= '$';
                   10522:         my (@from,@to);
                   10523:         eval {
                   10524:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10525:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10526:         };
                   10527:         if ((@from > 0) && (@to > 0)) {
                   10528:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10529:             if (!@diffs) {
                   10530:                 $canclone = 1;
                   10531:             }
                   10532:         }
                   10533:     }
                   10534:     return $canclone;
                   10535: }
                   10536: 
                   10537: sub default_instcode_cloning {
                   10538:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10539:     my (%codedefaults,@code_order,$canclone);
                   10540:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10541:         %codedefaults = %{$codedefaultsref};
                   10542:         @code_order = @{$codeorderref};
                   10543:     } elsif ($clonedom) {
                   10544:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10545:     }
                   10546:     if (($domdefclone) && (@code_order)) {
                   10547:         my @clonecodes = split(/\+/,$domdefclone);
                   10548:         my $instcoderegexp ='^';
                   10549:         foreach my $item (@code_order) {
                   10550:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10551:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10552:             } else {
                   10553:                 $instcoderegexp .= $codedefaults{$item};
                   10554:             }
                   10555:         }
                   10556:         $instcoderegexp .= '$';
                   10557:         my (@from,@to);
                   10558:         eval {
                   10559:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10560:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10561:         };
                   10562:         if ((@from > 0) && (@to > 0)) {
                   10563:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10564:             if (!@diffs) {
                   10565:                 $canclone = 1;
                   10566:             }
                   10567:         }
                   10568:     }
                   10569:     return $canclone;
                   10570: }
                   10571: 
1.679     raeburn  10572: # ------------------------------------------------------- Course Group routines
                   10573: 
                   10574: sub get_coursegroups {
1.809     raeburn  10575:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10576:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10577: }
                   10578: 
1.679     raeburn  10579: sub modify_coursegroup {
                   10580:     my ($cdom,$cnum,$groupsettings) = @_;
                   10581:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10582: }
                   10583: 
1.809     raeburn  10584: sub toggle_coursegroup_status {
                   10585:     my ($cdom,$cnum,$group,$action) = @_;
                   10586:     my ($from_namespace,$to_namespace);
                   10587:     if ($action eq 'delete') {
                   10588:         $from_namespace = 'coursegroups';
                   10589:         $to_namespace = 'deleted_groups';
                   10590:     } else {
                   10591:         $from_namespace = 'deleted_groups';
                   10592:         $to_namespace = 'coursegroups';
                   10593:     }
                   10594:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10595:     if (my $tmp = &error(%curr_group)) {
                   10596:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10597:         return ('read error',$tmp);
                   10598:     } else {
                   10599:         my %savedsettings = %curr_group; 
1.809     raeburn  10600:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10601:         my $deloutcome;
                   10602:         if ($result eq 'ok') {
1.809     raeburn  10603:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10604:         } else {
                   10605:             return ('write error',$result);
                   10606:         }
                   10607:         if ($deloutcome eq 'ok') {
                   10608:             return 'ok';
                   10609:         } else {
                   10610:             return ('delete error',$deloutcome);
                   10611:         }
                   10612:     }
                   10613: }
                   10614: 
1.679     raeburn  10615: sub modify_group_roles {
1.1512    raeburn  10616:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
                   10617:         $othdomby,$requester) = @_;
1.679     raeburn  10618:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10619:     my $role = 'gr/'.&escape($userprivs);
                   10620:     my ($uname,$udom) = split(/:/,$user);
1.1512    raeburn  10621:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
                   10622:                              $othdomby,$requester);
1.684     raeburn  10623:     if ($result eq 'ok') {
                   10624:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10625:     }
1.679     raeburn  10626:     return $result;
                   10627: }
                   10628: 
                   10629: sub modify_coursegroup_membership {
                   10630:     my ($cdom,$cnum,$membership) = @_;
                   10631:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10632:     return $result;
                   10633: }
                   10634: 
1.682     raeburn  10635: sub get_active_groups {
                   10636:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10637:     my $now = time;
                   10638:     my %groups = ();
                   10639:     foreach my $key (keys(%env)) {
1.811     albertel 10640:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10641:             my ($start,$end) = split(/\./,$env{$key});
                   10642:             if (($end!=0) && ($end<$now)) { next; }
                   10643:             if (($start!=0) && ($start>$now)) { next; }
                   10644:             if ($1 eq $cdom && $2 eq $cnum) {
                   10645:                 $groups{$3} = $env{$key} ;
                   10646:             }
                   10647:         }
                   10648:     }
                   10649:     return %groups;
                   10650: }
                   10651: 
1.683     raeburn  10652: sub get_group_membership {
                   10653:     my ($cdom,$cnum,$group) = @_;
                   10654:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10655: }
                   10656: 
                   10657: sub get_users_groups {
                   10658:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10659:     my @usersgroups;
1.683     raeburn  10660:     my $cachetime=1800;
                   10661: 
                   10662:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10663:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10664:     if (defined($cached)) {
1.734     albertel 10665:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10666:     } else {  
                   10667:         $grouplist = '';
1.816     raeburn  10668:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10669:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10670:         my $access_end = $env{'course.'.$courseid.
                   10671:                               '.default_enrollment_end_date'};
                   10672:         my $now = time;
                   10673:         foreach my $key (keys(%roleshash)) {
                   10674:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10675:                 my $group = $1;
                   10676:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10677:                     my $start = $2;
                   10678:                     my $end = $1;
                   10679:                     if ($start == -1) { next; } # deleted from group
                   10680:                     if (($start!=0) && ($start>$now)) { next; }
                   10681:                     if (($end!=0) && ($end<$now)) {
                   10682:                         if ($access_end && $access_end < $now) {
                   10683:                             if ($access_end - $end < 86400) {
                   10684:                                 push(@usersgroups,$group);
1.733     raeburn  10685:                             }
                   10686:                         }
1.817     raeburn  10687:                         next;
1.733     raeburn  10688:                     }
1.817     raeburn  10689:                     push(@usersgroups,$group);
1.683     raeburn  10690:                 }
                   10691:             }
                   10692:         }
1.817     raeburn  10693:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10694:         $grouplist = join(':',@usersgroups);
                   10695:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10696:     }
1.733     raeburn  10697:     return @usersgroups;
1.683     raeburn  10698: }
                   10699: 
                   10700: sub devalidate_getgroups_cache {
                   10701:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10702:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10703: 
1.683     raeburn  10704:     my $hashid="$udom:$uname:$courseid";
                   10705:     &devalidate_cache_new('getgroups',$hashid);
                   10706: }
                   10707: 
1.12      www      10708: # ------------------------------------------------------------------ Plain Text
                   10709: 
                   10710: sub plaintext {
1.988     raeburn  10711:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10712:     if ($short =~ m{^cr/}) {
1.758     albertel 10713: 	return (split('/',$short))[-1];
                   10714:     }
1.742     raeburn  10715:     if (!defined($cid)) {
                   10716:         $cid = $env{'request.course.id'};
                   10717:     }
                   10718:     my %rolenames = (
1.1008    raeburn  10719:                       Course    => 'std',
                   10720:                       Community => 'alt1',
1.1305    raeburn  10721:                       Placement => 'std',
1.742     raeburn  10722:                     );
1.1037    raeburn  10723:     if ($cid ne '') {
                   10724:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10725:             unless ($forcedefault) {
                   10726:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10727:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10728:                 return &Apache::lonlocal::mt($roletext);
                   10729:             }
                   10730:         }
                   10731:     }
                   10732:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10733:         (defined($rolenames{$type})) && 
                   10734:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10735:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10736:     } elsif ($cid ne '') {
                   10737:         my $crstype = $env{'course.'.$cid.'.type'};
                   10738:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10739:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10740:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10741:         }
1.742     raeburn  10742:     }
1.1037    raeburn  10743:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10744: }
                   10745: 
                   10746: # ----------------------------------------------------------------- Assign Role
                   10747: 
                   10748: sub assignrole {
1.957     raeburn  10749:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
1.1512    raeburn  10750:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
1.1517    raeburn  10751:     my ($mrole,$rolelogcontext);
1.21      www      10752:     if ($role =~ /^cr\//) {
1.393     www      10753:         my $cwosec=$url;
1.811     albertel 10754:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.1502    raeburn  10755:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
1.1512    raeburn  10756:             my $refused = 1;
                   10757:             if ($context eq 'requestcourses') {
                   10758:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10759:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10760:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10761:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10762:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10763:                             if ($crsenv{'internal.courseowner'} eq
                   10764:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
                   10765:                                 $refused = '';
                   10766:                             }
                   10767:                         }
                   10768:                     }
                   10769:                 }
                   10770:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
                   10771:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10772:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
                   10773:                 my $key = "$uname:$udom:$role:$sec";
                   10774:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
                   10775:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10776:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10777:                         $refused = '';
                   10778:                     }
                   10779:                 }
                   10780:             }
                   10781:             if ($refused) {
                   10782:                 &logthis('Refused custom assignrole: '.
                   10783:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10784:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10785:                 return 'refused';
                   10786:             }
1.104     www      10787:         }
1.21      www      10788:         $mrole='cr';
1.678     raeburn  10789:     } elsif ($role =~ /^gr\//) {
                   10790:         my $cwogrp=$url;
1.811     albertel 10791:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.1512    raeburn  10792:         if (!&allowed('mdg',$cwogrp)) {
                   10793:             my $refused = 1;
                   10794:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
                   10795:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
                   10796:                 my $key = "$uname:$udom:$reqrole:$reqsec";
                   10797:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
                   10798:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10799:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10800:                         $refused = '';
                   10801:                     }
                   10802:                 }
                   10803:             }
                   10804:             if ($refused) {
                   10805:                 &logthis('Refused group assignrole: '.
                   10806:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10807:                          $env{'user.name'}.' at '.$env{'user.domain'});
                   10808:                 return 'refused';
                   10809:             }
1.678     raeburn  10810:         }
                   10811:         $mrole='gr';
1.21      www      10812:     } else {
1.82      www      10813:         my $cwosec=$url;
1.811     albertel 10814:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10815:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10816:             my $refused;
                   10817:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10818:                 if (!(&allowed('c'.$role,$url))) {
                   10819:                     $refused = 1;
                   10820:                 }
                   10821:             } else {
                   10822:                 $refused = 1;
                   10823:             }
1.947     raeburn  10824:             if ($refused) {
1.1045    raeburn  10825:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1512    raeburn  10826:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
                   10827:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10828:                     my %crsenv;
                   10829:                     if ($role eq 'cc' || $role eq 'co') {
                   10830:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10831:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10832:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10833:                                 if ($crsenv{'internal.courseowner'} eq 
                   10834:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10835:                                     $refused = '';
                   10836:                                 }
                   10837:                             }
                   10838:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10839:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10840:                                 if ($crsenv{'internal.courseowner'} eq 
                   10841:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10842:                                     $refused = '';
                   10843:                                 }
                   10844:                             }
                   10845:                         }
                   10846:                     }
1.1368    raeburn  10847:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10848:                     if ($role eq 'st') {
                   10849:                         $refused = '';
1.1377    raeburn  10850:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10851:                         $refused = '';
                   10852:                     }
1.1512    raeburn  10853:                 } elsif ($othdomby eq 'othdombyuser') {
                   10854:                     my ($key,%queuedrolereq);
                   10855:                     if ($context eq 'course') {
                   10856:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
                   10857:                         $key = "$uname:$udom:$role:$sec";
                   10858:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
                   10859:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10860:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10861:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
                   10862:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
                   10863:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10864:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
                   10865:                                         $refused = '';
                   10866:                                     }
                   10867:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
                   10868:                                     $refused = '';
                   10869:                                 }
                   10870:                             }
                   10871:                         }
                   10872:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
                   10873:                         my $key = "$uname:$udom:$role"; 
                   10874:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
                   10875:                         if (($audom ne '') && ($auname ne '')) {
                   10876:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
                   10877:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10878:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10879:                                     $refused = '';
                   10880:                                 }
                   10881:                             }
                   10882:                         }
                   10883:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
                   10884:                         my $key = "$uname:$udom:$role";
                   10885:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
                   10886:                         if ($roledom ne '') {
                   10887:                             my $confname = $roledom.'-domainconfig';
                   10888:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
                   10889:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10890:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10891:                                     $refused = '';
                   10892:                                 }
                   10893:                             }
                   10894:                         }
                   10895:                     }
1.1017    raeburn  10896:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10897:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10898:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10899:                         my $wrongcc;
                   10900:                         if ($cnum =~ /^$match_community$/) {
                   10901:                             $wrongcc = 1 if ($role eq 'cc');
                   10902:                         } else {
                   10903:                             $wrongcc = 1 if ($role eq 'co');
                   10904:                         }
                   10905:                         unless ($wrongcc) {
                   10906:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10907:                             if ($crsenv{'internal.courseowner'} eq 
                   10908:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10909:                                 $refused = '';
                   10910:                             }
1.1017    raeburn  10911:                         }
                   10912:                     }
1.1183    raeburn  10913:                 } elsif ($context eq 'requestauthor') {
                   10914:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10915:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10916:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10917:                             $refused = '';
                   10918:                         } else {
                   10919:                             my %domdefaults = &get_domain_defaults($udom);
                   10920:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10921:                                 my $checkbystatus;
                   10922:                                 if ($env{'user.adv'}) { 
                   10923:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10924:                                     if ($disposition eq 'automatic') {
                   10925:                                         $refused = '';
                   10926:                                     } elsif ($disposition eq '') {
                   10927:                                         $checkbystatus = 1;
                   10928:                                     } 
                   10929:                                 } else {
                   10930:                                     $checkbystatus = 1;
                   10931:                                 }
                   10932:                                 if ($checkbystatus) {
                   10933:                                     if ($env{'environment.inststatus'}) {
                   10934:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10935:                                         foreach my $type (@inststatuses) {
                   10936:                                             if (($type ne '') &&
                   10937:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10938:                                                 $refused = '';
                   10939:                                             }
                   10940:                                         }
                   10941:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10942:                                         $refused = '';
                   10943:                                     }
                   10944:                                 }
                   10945:                             }
                   10946:                         }
                   10947:                     }
1.1517    raeburn  10948:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
                   10949:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
                   10950:                         my ($audom,$auname) = ($1,$2);
                   10951:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
                   10952:                             ($env{"environment.internal.manager.$url"})) {
                   10953:                             $refused = '';
                   10954:                             $rolelogcontext = 'coauthor';
                   10955:                         }
                   10956:                     }
1.1017    raeburn  10957:                 }
                   10958:                 if ($refused) {
1.947     raeburn  10959:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10960:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10961: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10962:                     return 'refused';
                   10963:                 }
1.932     raeburn  10964:             }
1.1131    raeburn  10965:         } elsif ($role eq 'au') {
                   10966:             if ($url ne '/'.$udom.'/') {
                   10967:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10968:                          ' to assign author role for '.$uname.':'.$udom.
                   10969:                          ' in domain: '.$url.' refused (wrong domain).');
                   10970:                 return 'refused';
                   10971:             }
1.104     www      10972:         }
1.21      www      10973:         $mrole=$role;
                   10974:     }
1.620     albertel 10975:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10976:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10977:     if ($end) { $command.='_'.$end; }
1.21      www      10978:     if ($start) {
                   10979: 	if ($end) { 
1.81      www      10980:            $command.='_'.$start; 
1.21      www      10981:         } else {
1.81      www      10982:            $command.='_0_'.$start;
1.21      www      10983:         }
                   10984:     }
1.739     raeburn  10985:     my $origstart = $start;
                   10986:     my $origend = $end;
1.957     raeburn  10987:     my $delflag;
1.357     www      10988: # actually delete
                   10989:     if ($deleteflag) {
1.373     www      10990: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10991: # modify command to delete the role
1.620     albertel 10992:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10993:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10994: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10995: # set start and finish to negative values for userrolelog
                   10996:            $start=-1;
                   10997:            $end=-1;
1.957     raeburn  10998:            $delflag = 1;
1.357     www      10999:         }
                   11000:     }
                   11001: # send command
1.349     www      11002:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      11003: # log new user role if status is ok
1.349     www      11004:     if ($answer eq 'ok') {
1.663     raeburn  11005: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  11006:         if (($role eq 'cc') || ($role eq 'in') ||
                   11007:             ($role eq 'ep') || ($role eq 'ad') ||
                   11008:             ($role eq 'ta') || ($role eq 'st') ||
                   11009:             ($role=~/^cr/) || ($role eq 'gr') ||
                   11010:             ($role eq 'co')) {
1.1200    raeburn  11011: # for course roles, perform group memberships changes triggered by role change.
                   11012:             unless ($role =~ /^gr/) {
                   11013:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   11014:                                                  $origstart,$selfenroll,$context);
                   11015:             }
1.1184    raeburn  11016:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1512    raeburn  11017:                            $selfenroll,$context,$othdomby,$requester);
1.1184    raeburn  11018:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  11019:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   11020:                  ($role eq 'da')) {
1.1184    raeburn  11021:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1512    raeburn  11022:                            $context,$othdomby,$requester);
1.1184    raeburn  11023:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
1.1517    raeburn  11024:             if ($rolelogcontext eq '') {
                   11025:                 $rolelogcontext = $context;
                   11026:             }
1.1184    raeburn  11027:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1517    raeburn  11028:                              $rolelogcontext,$othdomby,$requester); 
1.1184    raeburn  11029:         }
1.1053    raeburn  11030:         if ($role eq 'cc') {
                   11031:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   11032:         }
1.349     www      11033:     }
                   11034:     return $answer;
1.169     harris41 11035: }
                   11036: 
1.1053    raeburn  11037: sub autoupdate_coowners {
                   11038:     my ($url,$end,$start,$uname,$udom) = @_;
                   11039:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   11040:     if (($cdom ne '') && ($cnum ne '')) {
                   11041:         my $now = time;
                   11042:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   11043:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   11044:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   11045:             my $instcode = $coursehash{'internal.coursecode'};
1.1444    raeburn  11046:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  11047:             if ($instcode ne '') {
1.1056    raeburn  11048:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   11049:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  11050:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  11051:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444    raeburn  11052:                         unless ($result eq 'valid') {
                   11053:                             if ($xlists ne '') {
                   11054:                                 foreach my $xlist (split(',',$xlists)) {
                   11055:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   11056:                                     $result =
1.1446    raeburn  11057:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   11058:                                                                       $inst_crosslist,$uname.':'.$udom);
                   11059:                                     last if ($result eq 'valid');
1.1444    raeburn  11060:                                 }
                   11061:                             }
                   11062:                         }
1.1056    raeburn  11063:                         if ($result eq 'valid') {
                   11064:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  11065:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   11066:                                     push(@newcoowners,$coowner);
                   11067:                                 }
                   11068:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   11069:                                     push(@newcoowners,$uname.':'.$udom);
                   11070:                                 }
                   11071:                                 @newcoowners = sort(@newcoowners);
                   11072:                             } else {
                   11073:                                 push(@newcoowners,$uname.':'.$udom);
                   11074:                             }
1.1444    raeburn  11075:                         } elsif ($coursehash{'internal.co-owners'}) {
                   11076:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   11077:                                 unless ($coowner eq $uname.':'.$udom) {
                   11078:                                     push(@newcoowners,$coowner);
1.1053    raeburn  11079:                                 }
1.1444    raeburn  11080:                             }
                   11081:                             unless (@newcoowners > 0) {
                   11082:                                 $delcoowners = 1;
                   11083:                                 $coowners = '';
1.1053    raeburn  11084:                             }
                   11085:                         }
                   11086:                         if (@newcoowners || $delcoowners) {
                   11087:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   11088:                                             $delcoowners,@newcoowners);
                   11089:                         }
                   11090:                     }
                   11091:                 }
                   11092:             }
                   11093:         }
                   11094:     }
                   11095: }
                   11096: 
                   11097: sub store_coowners {
                   11098:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   11099:     my $cid = $cdom.'_'.$cnum;
                   11100:     my ($coowners,$delresult,$putresult);
                   11101:     if (@newcoowners) {
                   11102:         $coowners = join(',',@newcoowners);
                   11103:         my %coownershash = (
                   11104:                             'internal.co-owners' => $coowners,
                   11105:                            );
                   11106:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   11107:         if ($putresult eq 'ok') {
                   11108:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   11109:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   11110:             }
                   11111:         }
                   11112:     }
                   11113:     if ($delcoowners) {
                   11114:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   11115:         if ($delresult eq 'ok') {
                   11116:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   11117:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   11118:             }
                   11119:         }
                   11120:     }
                   11121:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   11122:         my %crsinfo =
1.1494    raeburn  11123:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
1.1053    raeburn  11124:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   11125:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
1.1494    raeburn  11126:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
1.1053    raeburn  11127:         }
                   11128:     }
                   11129: }
                   11130: 
1.169     harris41 11131: # -------------------------------------------------- Modify user authentication
1.197     www      11132: # Overrides without validation
                   11133: 
1.169     harris41 11134: sub modifyuserauth {
                   11135:     my ($udom,$uname,$umode,$upass)=@_;
                   11136:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  11137:     my $allowed;
                   11138:     if (&allowed('mau',$udom)) {
                   11139:         $allowed = 1;
                   11140:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   11141:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   11142:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   11143:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11144:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11145:         if (($cdom ne '') && ($cnum ne '')) {
                   11146:             my $is_owner = &is_course_owner($cdom,$cnum);
                   11147:             if ($is_owner) {
                   11148:                 $allowed = 1;
                   11149:             }
                   11150:         }
                   11151:     }
                   11152:     unless ($allowed) { return 'refused'; }
1.197     www      11153:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 11154:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   11155:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 11156:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   11157: 		     &escape($upass),$uhome);
1.1434    raeburn  11158:     my $ip = &get_requestor_ip();
1.620     albertel 11159:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      11160:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434    raeburn  11161:          '(Remote '.$ip.'): '.$reply);
1.197     www      11162:     &log($udom,,$uname,$uhome,
1.620     albertel 11163:         'Authentication changed by '.$env{'user.domain'}.', '.
                   11164:                                      $env{'user.name'}.', '.$umode.
1.1435    raeburn  11165:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 11166:     unless ($reply eq 'ok') {
1.197     www      11167:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 11168: 	return 'error: '.$reply;
                   11169:     }   
1.170     harris41 11170:     return 'ok';
1.80      www      11171: }
                   11172: 
1.81      www      11173: # --------------------------------------------------------------- Modify a user
1.80      www      11174: 
1.81      www      11175: sub modifyuser {
1.206     matthew  11176:     my ($udom,    $uname, $uid,
                   11177:         $umode,   $upass, $first,
                   11178:         $middle,  $last,  $gene,
1.1058    raeburn  11179:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 11180:     $udom= &LONCAPA::clean_domain($udom);
                   11181:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  11182:     my $showcandelete = 'none';
                   11183:     if (ref($candelete) eq 'ARRAY') {
                   11184:         if (@{$candelete} > 0) {
                   11185:             $showcandelete = join(', ',@{$candelete});
                   11186:         }
                   11187:     }
1.81      www      11188:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      11189:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  11190: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  11191:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   11192:                                      ' desiredhome not specified'). 
1.620     albertel 11193:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   11194:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 11195:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  11196:     my $newuser;
                   11197:     if ($uhome eq 'no_host') {
                   11198:         $newuser = 1;
1.1368    raeburn  11199:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   11200:                 ($umode eq 'lti')) {
                   11201:             return 'error: more information needed to create new user';
                   11202:         }
1.1075    raeburn  11203:     }
1.80      www      11204: # ----------------------------------------------------------------- Create User
1.406     albertel 11205:     if (($uhome eq 'no_host') && 
1.1368    raeburn  11206: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      11207:         my $unhome='';
1.844     albertel 11208:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  11209:             $unhome = $desiredhome;
1.620     albertel 11210: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   11211: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  11212:         } else { # load balancing routine for determining $unhome
1.81      www      11213:             my $loadm=10000000;
1.841     albertel 11214: 	    my %servers = &get_servers($udom,'library');
                   11215: 	    foreach my $tryserver (keys(%servers)) {
                   11216: 		my $answer=reply('load',$tryserver);
                   11217: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   11218: 		    $loadm=$answer;
                   11219: 		    $unhome=$tryserver;
                   11220: 		}
1.80      www      11221: 	    }
                   11222:         }
                   11223:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  11224: 	    return 'error: unable to find a home server for '.$uname.
                   11225:                    ' in domain '.$udom;
1.80      www      11226:         }
                   11227:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   11228:                          &escape($upass),$unhome);
                   11229: 	unless ($reply eq 'ok') {
                   11230:             return 'error: '.$reply;
                   11231:         }   
1.230     stredwic 11232:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      11233:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  11234: 	    return 'error: unable verify users home machine.';
1.80      www      11235:         }
1.209     matthew  11236:     }   # End of creation of new user
1.80      www      11237: # ---------------------------------------------------------------------- Add ID
                   11238:     if ($uid) {
                   11239:        $uid=~tr/A-Z/a-z/;
                   11240:        my %uidhash=&idrget($udom,$uname);
1.196     www      11241:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   11242:          && (!$forceid)) {
1.80      www      11243: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  11244: 	      return 'error: user id "'.$uid.'" does not match '.
                   11245:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      11246:           }
                   11247:        } else {
1.1300    raeburn  11248: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      11249:        }
                   11250:     }
                   11251: # -------------------------------------------------------------- Add names, etc
1.313     matthew  11252:     my @tmp=&get('environment',
1.899     raeburn  11253: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  11254:                     'permanentemail','inststatus'],
1.134     albertel 11255: 		   $udom,$uname);
1.1075    raeburn  11256:     my (%names,%oldnames);
1.313     matthew  11257:     if ($tmp[0] =~ m/^error:.*/) { 
                   11258:         %names=(); 
                   11259:     } else {
                   11260:         %names = @tmp;
1.1075    raeburn  11261:         %oldnames = %names;
1.313     matthew  11262:     }
1.388     www      11263: #
1.1058    raeburn  11264: # If name, email and/or uid are blank (e.g., because an uploaded file
                   11265: # of users did not contain them), do not overwrite existing values
                   11266: # unless field is in $candelete array ref.  
                   11267: #
                   11268: 
                   11269:     my @fields = ('firstname','middlename','lastname','generation',
                   11270:                   'permanentemail','id');
                   11271:     my %newvalues;
                   11272:     if (ref($candelete) eq 'ARRAY') {
                   11273:         foreach my $field (@fields) {
                   11274:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   11275:                 if ($field eq 'firstname') {
                   11276:                     $names{$field} = $first;
                   11277:                 } elsif ($field eq 'middlename') {
                   11278:                     $names{$field} = $middle;
                   11279:                 } elsif ($field eq 'lastname') {
                   11280:                     $names{$field} = $last;
                   11281:                 } elsif ($field eq 'generation') { 
                   11282:                     $names{$field} = $gene;
                   11283:                 } elsif ($field eq 'permanentemail') {
                   11284:                     $names{$field} = $email;
                   11285:                 } elsif ($field eq 'id') {
                   11286:                     $names{$field}  = $uid;
                   11287:                 }
                   11288:             }
                   11289:         }
                   11290:     }
1.388     www      11291:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  11292:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      11293:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  11294:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      11295:     if ($email) {
                   11296:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  11297:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      11298:     }
1.899     raeburn  11299:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  11300:     if (defined($inststatus)) {
                   11301:         $names{'inststatus'} = '';
                   11302:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   11303:         if (ref($usertypes) eq 'HASH') {
                   11304:             my @okstatuses; 
                   11305:             foreach my $item (split(/:/,$inststatus)) {
                   11306:                 if (defined($usertypes->{$item})) {
                   11307:                     push(@okstatuses,$item);  
                   11308:                 }
                   11309:             }
                   11310:             if (@okstatuses) {
                   11311:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   11312:             }
                   11313:         }
                   11314:     }
1.1075    raeburn  11315:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  11316:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  11317:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  11318:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   11319:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   11320:     } else {
                   11321:         $logmsg .= ' during self creation';
                   11322:     }
1.1075    raeburn  11323:     my $changed;
                   11324:     if ($newuser) {
                   11325:         $changed = 1;
                   11326:     } else {
                   11327:         foreach my $field (@fields) {
                   11328:             if ($names{$field} ne $oldnames{$field}) {
                   11329:                 $changed = 1;
                   11330:                 last;
                   11331:             }
                   11332:         }
                   11333:     }
                   11334:     unless ($changed) {
                   11335:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   11336:         &logthis($logmsg);
                   11337:         return 'ok';
                   11338:     }
                   11339:     my $reply = &put('environment', \%names, $udom,$uname);
                   11340:     if ($reply ne 'ok') { 
                   11341:         return 'error: '.$reply;
                   11342:     }
1.1087    raeburn  11343:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
1.1494    raeburn  11344:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
1.1087    raeburn  11345:     }
1.1075    raeburn  11346:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   11347:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   11348:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  11349:     &logthis($logmsg);
1.134     albertel 11350:     return 'ok';
1.80      www      11351: }
                   11352: 
1.81      www      11353: # -------------------------------------------------------------- Modify student
1.80      www      11354: 
1.81      www      11355: sub modifystudent {
                   11356:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  11357:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  11358:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 11359:     if (!$cid) {
1.620     albertel 11360: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 11361: 	    return 'not_in_class';
                   11362: 	}
1.80      www      11363:     }
                   11364: # --------------------------------------------------------------- Make the user
1.81      www      11365:     my $reply=&modifyuser
1.209     matthew  11366: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  11367:          $desiredhome,$email,$inststatus);
1.80      www      11368:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  11369:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  11370:     # student's environment
1.297     matthew  11371:     $uid = undef if (!$forceid);
1.455     albertel 11372:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  11373:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  11374:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  11375:     return $reply;
                   11376: }
                   11377: 
                   11378: sub modify_student_enrollment {
1.1216    raeburn  11379:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1512    raeburn  11380:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
1.455     albertel 11381:     my ($cdom,$cnum,$chome);
                   11382:     if (!$cid) {
1.620     albertel 11383: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 11384: 	    return 'not_in_class';
                   11385: 	}
1.620     albertel 11386: 	$cdom=$env{'course.'.$cid.'.domain'};
                   11387: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 11388:     } else {
                   11389: 	($cdom,$cnum)=split(/_/,$cid);
                   11390:     }
1.620     albertel 11391:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 11392:     if (!$chome) {
1.457     raeburn  11393: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  11394:     }
1.455     albertel 11395:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  11396:     # Make sure the user exists
1.81      www      11397:     my $uhome=&homeserver($uname,$udom);
                   11398:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11399: 	return 'error: no such user';
                   11400:     }
1.297     matthew  11401:     # Get student data if we were not given enough information
                   11402:     if (!defined($first)  || $first  eq '' || 
                   11403:         !defined($last)   || $last   eq '' || 
                   11404:         !defined($uid)    || $uid    eq '' || 
                   11405:         !defined($middle) || $middle eq '' || 
                   11406:         !defined($gene)   || $gene   eq '') {
1.294     matthew  11407:         # They did not supply us with enough data to enroll the student, so
                   11408:         # we need to pick up more information.
1.297     matthew  11409:         my %tmp = &get('environment',
1.294     matthew  11410:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  11411:                        ,$udom,$uname);
                   11412: 
1.800     albertel 11413:         #foreach my $key (keys(%tmp)) {
                   11414:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 11415:         #}
1.294     matthew  11416:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   11417:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   11418:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  11419:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  11420:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   11421:     }
1.556     albertel 11422:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  11423:     my $user = "$uname:$udom";
1.1494    raeburn  11424:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
1.487     albertel 11425:     my $reply=cput('classlist',
1.1148    raeburn  11426: 		   {$user => 
1.1314    raeburn  11427: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 11428: 		   $cdom,$cnum);
1.1148    raeburn  11429:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   11430:         &devalidate_getsection_cache($udom,$uname,$cid);
                   11431:     } else { 
1.81      www      11432: 	return 'error: '.$reply;
                   11433:     }
1.297     matthew  11434:     # Add student role to user
1.83      www      11435:     my $uurl='/'.$cid;
1.81      www      11436:     $uurl=~s/\_/\//g;
                   11437:     if ($usec) {
                   11438: 	$uurl.='/'.$usec;
                   11439:     }
1.1148    raeburn  11440:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
1.1512    raeburn  11441:                              $selfenroll,$context,$othdomby,$requester);
1.1148    raeburn  11442:     if ($result ne 'ok') {
                   11443:         if ($old_entry{$user} ne '') {
                   11444:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   11445:         } else {
                   11446:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   11447:         }
                   11448:     }
                   11449:     return $result; 
1.21      www      11450: }
                   11451: 
1.556     albertel 11452: sub format_name {
                   11453:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   11454:     my $name;
                   11455:     if ($first ne 'lastname') {
                   11456: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   11457:     } else {
                   11458: 	if ($lastname=~/\S/) {
                   11459: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   11460: 	    $name=~s/\s+,/,/;
                   11461: 	} else {
                   11462: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   11463: 	}
                   11464:     }
                   11465:     $name=~s/^\s+//;
                   11466:     $name=~s/\s+$//;
                   11467:     $name=~s/\s+/ /g;
                   11468:     return $name;
                   11469: }
                   11470: 
1.84      www      11471: # ------------------------------------------------- Write to course preferences
                   11472: 
                   11473: sub writecoursepref {
                   11474:     my ($courseid,%prefs)=@_;
                   11475:     $courseid=~s/^\///;
                   11476:     $courseid=~s/\_/\//g;
                   11477:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   11478:     my $chome=homeserver($cnum,$cdomain);
                   11479:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   11480: 	return 'error: no such course';
                   11481:     }
                   11482:     my $cstring='';
1.800     albertel 11483:     foreach my $pref (keys(%prefs)) {
                   11484: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 11485:     }
1.84      www      11486:     $cstring=~s/\&$//;
                   11487:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   11488: }
                   11489: 
                   11490: # ---------------------------------------------------------- Make/modify course
                   11491: 
                   11492: sub createcourse {
1.741     raeburn  11493:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  11494:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      11495:     $url=&declutter($url);
                   11496:     my $cid='';
1.1028    raeburn  11497:     if ($context eq 'requestcourses') {
                   11498:         my $can_create = 0;
                   11499:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   11500:         if ($udom eq $ownerdom) {
1.1423    raeburn  11501:             my $reload;
                   11502:             if (($callercontext eq 'auto') &&
                   11503:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   11504:                 $reload = 'reload';
                   11505:             }
                   11506:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  11507:                                   $context)) {
                   11508:                 $can_create = 1;
                   11509:             }
                   11510:         } else {
                   11511:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   11512:                                            $category);
                   11513:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   11514:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   11515:                 if (@curr > 0) {
                   11516:                     my @options = qw(approval validate autolimit);
                   11517:                     my $optregex = join('|',@options);
                   11518:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   11519:                         $can_create = 1;
                   11520:                     }
                   11521:                 }
                   11522:             }
                   11523:         }
                   11524:         if ($can_create) {
                   11525:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   11526:                 unless (&allowed('ccc',$udom)) {
                   11527:                     return 'refused'; 
                   11528:                 }
1.1017    raeburn  11529:             }
                   11530:         } else {
                   11531:             return 'refused';
                   11532:         }
1.1028    raeburn  11533:     } elsif (!&allowed('ccc',$udom)) {
                   11534:         return 'refused';
1.84      www      11535:     }
1.1011    raeburn  11536: # --------------------------------------------------------------- Get Unique ID
                   11537:     my $uname;
                   11538:     if ($cnum =~ /^$match_courseid$/) {
                   11539:         my $chome=&homeserver($cnum,$udom,'true');
                   11540:         if (($chome eq '') || ($chome eq 'no_host')) {
                   11541:             $uname = $cnum;
                   11542:         } else {
1.1038    raeburn  11543:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11544:         }
                   11545:     } else {
1.1038    raeburn  11546:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11547:     }
                   11548:     return $uname if ($uname =~ /^error/);
                   11549: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  11550:     if (!defined($course_server)) {
                   11551:         if (defined(&domain($udom,'primary'))) {
                   11552:             $course_server = &domain($udom,'primary');
                   11553:         } else {
                   11554:             $course_server = $env{'user.home'}; 
                   11555:         }
                   11556:     }
                   11557:     my %host_servers =
1.1494    raeburn  11558:         &get_servers($udom,'library');
1.1052    raeburn  11559:     unless ($host_servers{$course_server}) {
                   11560:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11561:     }
1.84      www      11562: # ------------------------------------------------------------- Make the course
                   11563:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11564:                       $course_server);
1.84      www      11565:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11566:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11567:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11568: 	return 'error: no such course';
                   11569:     }
1.271     www      11570: # ----------------------------------------------------------------- Course made
1.516     raeburn  11571: # log existence
1.1029    raeburn  11572:     my $now = time;
1.918     raeburn  11573:     my $newcourse = {
                   11574:                     $udom.'_'.$uname => {
1.921     raeburn  11575:                                      description => $description,
                   11576:                                      inst_code   => $inst_code,
                   11577:                                      owner       => $course_owner,
                   11578:                                      type        => $crstype,
1.1029    raeburn  11579:                                      creator     => $env{'user.name'}.':'.
                   11580:                                                     $env{'user.domain'},
                   11581:                                      created     => $now,
                   11582:                                      context     => $context,
1.918     raeburn  11583:                                                 },
                   11584:                     };
1.921     raeburn  11585:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11586: # set toplevel url
1.271     www      11587:     my $topurl=$url;
                   11588:     unless ($nonstandard) {
                   11589: # ------------------------------------------ For standard courses, make top url
                   11590:         my $mapurl=&clutter($url);
1.278     www      11591:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11592:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11593: <map>
                   11594: <resource id="1" type="start"></resource>
                   11595: <resource id="2" src="$mapurl"></resource>
                   11596: <resource id="3" type="finish"></resource>
                   11597: <link index="1" from="1" to="2"></link>
                   11598: <link index="2" from="2" to="3"></link>
                   11599: </map>
                   11600: ENDINITMAP
                   11601:         $topurl=&declutter(
1.638     albertel 11602:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11603:                           );
                   11604:     }
                   11605: # ----------------------------------------------------------- Write preferences
1.84      www      11606:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11607:                      ('description'              => $description,
                   11608:                       'url'                      => $topurl,
                   11609:                       'internal.creator'         => $env{'user.name'}.':'.
                   11610:                                                     $env{'user.domain'},
                   11611:                       'internal.created'         => $now,
                   11612:                       'internal.creationcontext' => $context)
                   11613:                     );
1.84      www      11614:     return '/'.$udom.'/'.$uname;
                   11615: }
                   11616: 
1.1011    raeburn  11617: # ------------------------------------------------------------------- Create ID
                   11618: sub generate_coursenum {
1.1038    raeburn  11619:     my ($udom,$crstype) = @_;
1.1011    raeburn  11620:     my $domdesc = &domain($udom);
                   11621:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11622:     my $first;
                   11623:     if ($crstype eq 'Community') {
                   11624:         $first = '0';
                   11625:     } else {
                   11626:         $first = int(1+rand(9)); 
                   11627:     } 
                   11628:     my $uname=$first.
1.1011    raeburn  11629:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11630:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11631:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11632: # ----------------------------------------------- Make sure that does not exist
                   11633:     my $uhome=&homeserver($uname,$udom,'true');
                   11634:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11635:         if ($crstype eq 'Community') {
                   11636:             $first = '0';
                   11637:         } else {
                   11638:             $first = int(1+rand(9));
                   11639:         }
                   11640:         $uname=$first.
1.1011    raeburn  11641:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11642:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11643:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11644:         $uhome=&homeserver($uname,$udom,'true');
                   11645:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11646:             return 'error: unable to generate unique course-ID';
                   11647:         }
                   11648:     }
                   11649:     return $uname;
                   11650: }
                   11651: 
1.813     albertel 11652: sub is_course {
1.1167    droeschl 11653:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11654:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   11655: 
1.1381    raeburn  11656:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11657:     my $uhome=&homeserver($cnum,$cdom);
                   11658:     my $iscourse;
                   11659:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  11660:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  11661:     } else {
                   11662:         my $hashid = $cdom.':'.$cnum;
                   11663:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11664:         unless (defined($cached)) {
                   11665:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11666:                                         $cnum,undef,undef,'.');
                   11667:             $iscourse = 0;
                   11668:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11669:                 $iscourse = 1;
                   11670:             }
                   11671:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11672:         }
                   11673:     }
                   11674:     return unless ($iscourse);
1.1167    droeschl 11675:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11676: }
                   11677: 
1.1015    raeburn  11678: sub store_userdata {
                   11679:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11680:     my $result;
1.1016    raeburn  11681:     if ($datakey ne '') {
1.1013    raeburn  11682:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11683:             if ($udom eq '' || $uname eq '') {
                   11684:                 $udom = $env{'user.domain'};
                   11685:                 $uname = $env{'user.name'};
                   11686:             }
                   11687:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11688:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11689:                 $result = 'error: no_host';
                   11690:             } else {
1.1434    raeburn  11691:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11692:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11693: 
                   11694:                 my $namevalue='';
                   11695:                 foreach my $key (keys(%{$storehash})) {
                   11696:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11697:                 }
                   11698:                 $namevalue=~s/\&$//;
1.1224    raeburn  11699:                 unless ($namespace eq 'courserequests') {
                   11700:                     $datakey = &escape($datakey);
                   11701:                 }
1.1105    raeburn  11702:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11703:                                   $namevalue,$uhome);
1.1013    raeburn  11704:             }
                   11705:         } else {
                   11706:             $result = 'error: data to store was not a hash reference'; 
                   11707:         }
                   11708:     } else {
                   11709:         $result= 'error: invalid requestkey'; 
                   11710:     }
                   11711:     return $result;
                   11712: }
                   11713: 
1.21      www      11714: # ---------------------------------------------------------- Assign Custom Role
                   11715: 
                   11716: sub assigncustomrole {
1.1512    raeburn  11717:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
                   11718:         $selfenroll,$context,$othdomby,$requester)=@_;
1.21      www      11719:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.1512    raeburn  11720:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
                   11721:                        $requester);
1.21      www      11722: }
                   11723: 
                   11724: # ----------------------------------------------------------------- Revoke Role
                   11725: 
                   11726: sub revokerole {
1.957     raeburn  11727:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11728:     my $now=time;
1.965     raeburn  11729:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11730: }
                   11731: 
                   11732: # ---------------------------------------------------------- Revoke Custom Role
                   11733: 
                   11734: sub revokecustomrole {
1.957     raeburn  11735:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11736:     my $now=time;
1.357     www      11737:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11738:            $deleteflag,$selfenroll,$context);
1.17      www      11739: }
                   11740: 
1.533     banghart 11741: # ------------------------------------------------------------ Disk usage
1.535     albertel 11742: sub diskusage {
1.955     raeburn  11743:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11744:     $directorypath =~ s/\/$//;
                   11745:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11746:                        .&escape($getpropath).':'.&escape($uname).':'
                   11747:                        .&escape($udom),homeserver($uname,$udom));
                   11748:     if ($listing eq 'unknown_cmd') {
                   11749:         if ($getpropath) {
                   11750:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11751:         }
                   11752:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11753:     }
1.514     albertel 11754:     return $listing;
1.512     banghart 11755: }
                   11756: 
1.566     banghart 11757: sub is_locked {
1.1096    raeburn  11758:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11759:     my @check;
                   11760:     my $is_locked;
1.1093    raeburn  11761:     push (@check,$file_name);
1.613     albertel 11762:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11763: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11764:     my ($tmp)=keys(%locked);
                   11765:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11766:     
1.566     banghart 11767:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11768:         $is_locked = 'false';
                   11769:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11770:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11771:                $is_locked = 'true';
1.1096    raeburn  11772:                if (ref($which) eq 'ARRAY') {
                   11773:                    push(@{$which},$entry);
                   11774:                } else {
                   11775:                    last;
                   11776:                }
1.745     raeburn  11777:            }
                   11778:        }
1.566     banghart 11779:     } else {
                   11780:         $is_locked = 'false';
                   11781:     }
1.1093    raeburn  11782:     return $is_locked;
1.566     banghart 11783: }
                   11784: 
1.759     albertel 11785: sub declutter_portfile {
                   11786:     my ($file) = @_;
1.833     albertel 11787:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11788:     return $file;
                   11789: }
                   11790: 
1.559     banghart 11791: # ------------------------------------------------------------- Mark as Read Only
                   11792: 
                   11793: sub mark_as_readonly {
                   11794:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11795:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11796:     my ($tmp)=keys(%current_permissions);
                   11797:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11798:     foreach my $file (@{$files}) {
1.759     albertel 11799: 	$file = &declutter_portfile($file);
1.561     banghart 11800:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11801:     }
1.613     albertel 11802:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11803:     return;
                   11804: }
                   11805: 
1.572     banghart 11806: # ------------------------------------------------------------Save Selected Files
                   11807: 
                   11808: sub save_selected_files {
                   11809:     my ($user, $path, @files) = @_;
                   11810:     my $filename = $user."savedfiles";
1.573     banghart 11811:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  11812:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11813:     foreach my $file (@files) {
1.620     albertel 11814:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11815:     }
                   11816:     foreach my $file (@other_files) {
1.574     banghart 11817:         print (OUT $file."\n");
1.572     banghart 11818:     }
1.574     banghart 11819:     close (OUT);
1.572     banghart 11820:     return 'ok';
                   11821: }
                   11822: 
1.574     banghart 11823: sub clear_selected_files {
                   11824:     my ($user) = @_;
                   11825:     my $filename = $user."savedfiles";
1.1359    raeburn  11826:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11827:     print (OUT undef);
                   11828:     close (OUT);
                   11829:     return ("ok");    
                   11830: }
                   11831: 
1.572     banghart 11832: sub files_in_path {
                   11833:     my ($user, $path) = @_;
                   11834:     my $filename = $user."savedfiles";
                   11835:     my %return_files;
1.1359    raeburn  11836:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11837:     while (my $line_in = <IN>) {
1.574     banghart 11838:         chomp ($line_in);
                   11839:         my @paths_and_file = split (m!/!, $line_in);
                   11840:         my $file_part = pop (@paths_and_file);
                   11841:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11842:         $path_part.='/';
                   11843:         my $path_and_file = $path_part.$file_part;
                   11844:         if ($path_part eq $path) {
                   11845:             $return_files{$file_part}= 'selected';
                   11846:         }
                   11847:     }
1.574     banghart 11848:     close (IN);
                   11849:     return (\%return_files);
1.572     banghart 11850: }
                   11851: 
                   11852: # called in portfolio select mode, to show files selected NOT in current directory
                   11853: sub files_not_in_path {
                   11854:     my ($user, $path) = @_;
                   11855:     my $filename = $user."savedfiles";
                   11856:     my @return_files;
                   11857:     my $path_part;
1.1359    raeburn  11858:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11859:     while (my $line = <IN>) {
1.572     banghart 11860:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11861:         my @paths_and_file = split(m|/|, $line);
                   11862:         my $file_part = pop(@paths_and_file);
                   11863:         chomp($file_part);
                   11864:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11865:         $path_part .= '/';
                   11866:         my $path_and_file = $path_part.$file_part;
                   11867:         if ($path_part ne $path) {
1.800     albertel 11868:             push(@return_files, ($path_and_file));
1.572     banghart 11869:         }
                   11870:     }
1.800     albertel 11871:     close(OUT);
1.574     banghart 11872:     return (@return_files);
1.572     banghart 11873: }
                   11874: 
1.1273    raeburn  11875: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11876:  
                   11877: sub portfiles_versioning {
                   11878:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11879:     my $portfolio_root = '/userfiles/portfolio';
                   11880:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11881:     foreach my $file (@{$portfiles}) {
                   11882:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11883:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11884:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11885:         my $getpropath = 1;
                   11886:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11887:                                              $stu_name,$getpropath);
                   11888:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11889:         my $new_answer = 
                   11890:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11891:         if ($new_answer ne 'problem getting file') {
                   11892:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11893:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11894:                               [$symb,$env{'request.course.id'},'graded']);
                   11895:         }
                   11896:     }
                   11897: }
                   11898: 
                   11899: sub get_next_version {
                   11900:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11901:     my $version;
                   11902:     if (ref($dir_list) eq 'ARRAY') {
                   11903:         foreach my $row (@{$dir_list}) {
                   11904:             my ($file) = split(/\&/,$row,2);
                   11905:             my ($file_name,$file_version,$file_ext) =
                   11906:                 &file_name_version_ext($file);
                   11907:             if (($file_name eq $answer_name) &&
                   11908:                 ($file_ext eq $answer_ext)) {
                   11909:                      # gets here if filename and extension match,
                   11910:                      # regardless of version
                   11911:                 if ($file_version ne '') {
                   11912:                     # a versioned file is found  so save it for later
                   11913:                     if ($file_version > $version) {
                   11914:                         $version = $file_version;
                   11915:                     }
                   11916:                 }
                   11917:             }
                   11918:         }
                   11919:     }
                   11920:     $version ++;
                   11921:     return($version);
                   11922: }
                   11923: 
                   11924: sub version_selected_portfile {
                   11925:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11926:     my ($answer_name,$answer_ver,$answer_ext) =
                   11927:         &file_name_version_ext($file_name);
                   11928:     my $new_answer;
                   11929:     $env{'form.copy'} =
                   11930:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11931:     if($env{'form.copy'} eq '-1') {
                   11932:         $new_answer = 'problem getting file';
                   11933:     } else {
                   11934:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11935:         my $copy_result = 
                   11936:             &finishuserfileupload($stu_name,$domain,'copy',
                   11937:                                   '/portfolio'.$directory.$new_answer);
                   11938:     }
                   11939:     undef($env{'form.copy'});
                   11940:     return ($new_answer);
                   11941: }
                   11942: 
                   11943: sub file_name_version_ext {
                   11944:     my ($file)=@_;
                   11945:     my @file_parts = split(/\./, $file);
                   11946:     my ($name,$version,$ext);
                   11947:     if (@file_parts > 1) {
                   11948:         $ext=pop(@file_parts);
                   11949:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11950:             $version=pop(@file_parts);
                   11951:         }
                   11952:         $name=join('.',@file_parts);
                   11953:     } else {
                   11954:         $name=join('.',@file_parts);
                   11955:     }
                   11956:     return($name,$version,$ext);
                   11957: }
                   11958: 
1.745     raeburn  11959: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11960: 
1.745     raeburn  11961: sub get_portfile_permissions {
                   11962:     my ($domain,$user) = @_;
1.613     albertel 11963:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11964:     my ($tmp)=keys(%current_permissions);
                   11965:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11966:     return \%current_permissions;
                   11967: }
                   11968: 
                   11969: #---------------------------------------------Get portfolio file access controls
                   11970: 
1.749     raeburn  11971: sub get_access_controls {
1.745     raeburn  11972:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11973:     my %access;
                   11974:     my $real_file = $file;
                   11975:     $file =~ s/\.meta$//;
1.745     raeburn  11976:     if (defined($file)) {
1.749     raeburn  11977:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11978:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11979:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11980:             }
                   11981:         }
1.745     raeburn  11982:     } else {
1.749     raeburn  11983:         foreach my $key (keys(%{$current_permissions})) {
                   11984:             if ($key =~ /\0accesscontrol$/) {
                   11985:                 if (defined($group)) {
                   11986:                     if ($key !~ m-^\Q$group\E/-) {
                   11987:                         next;
                   11988:                     }
                   11989:                 }
                   11990:                 my ($fullpath) = split(/\0/,$key);
                   11991:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11992:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11993:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11994:                     }
                   11995:                 }
                   11996:             }
                   11997:         }
                   11998:     }
                   11999:     return %access;
                   12000: }
                   12001: 
                   12002: sub modify_access_controls {
                   12003:     my ($file_name,$changes,$domain,$user)=@_;
                   12004:     my ($outcome,$deloutcome);
                   12005:     my %store_permissions;
                   12006:     my %new_values;
                   12007:     my %new_control;
                   12008:     my %translation;
                   12009:     my @deletions = ();
                   12010:     my $now = time;
                   12011:     if (exists($$changes{'activate'})) {
                   12012:         if (ref($$changes{'activate'}) eq 'HASH') {
                   12013:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   12014:             my $numnew = scalar(@newitems);
                   12015:             for (my $i=0; $i<$numnew; $i++) {
                   12016:                 my $newkey = $newitems[$i];
                   12017:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  12018:                 if ($newkey =~ /^\d+:/) { 
                   12019:                     $newkey =~ s/^(\d+)/$newid/;
                   12020:                     $translation{$1} = $newid;
                   12021:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   12022:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   12023:                     $translation{$1} = $newid;
                   12024:                 }
1.749     raeburn  12025:                 $new_values{$file_name."\0".$newkey} = 
                   12026:                                           $$changes{'activate'}{$newitems[$i]};
                   12027:                 $new_control{$newkey} = $now;
                   12028:             }
                   12029:         }
                   12030:     }
                   12031:     my %todelete;
                   12032:     my %changed_items;
                   12033:     foreach my $action ('delete','update') {
                   12034:         if (exists($$changes{$action})) {
                   12035:             if (ref($$changes{$action}) eq 'HASH') {
                   12036:                 foreach my $key (keys(%{$$changes{$action}})) {
                   12037:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   12038:                     if ($action eq 'delete') { 
                   12039:                         $todelete{$itemnum} = 1;
                   12040:                     } else {
                   12041:                         $changed_items{$itemnum} = $key;
                   12042:                     }
                   12043:                 }
1.745     raeburn  12044:             }
                   12045:         }
1.749     raeburn  12046:     }
                   12047:     # get lock on access controls for file.
                   12048:     my $lockhash = {
                   12049:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   12050:                                                        ':'.$env{'user.domain'},
                   12051:                    }; 
                   12052:     my $tries = 0;
                   12053:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   12054:    
1.1288    damieng  12055:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  12056:         $tries ++;
1.1289    damieng  12057:         sleep(0.1);
1.749     raeburn  12058:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   12059:     }
                   12060:     if ($gotlock eq 'ok') {
                   12061:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   12062:         my ($tmp)=keys(%curr_permissions);
                   12063:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   12064:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   12065:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   12066:             if (ref($curr_controls) eq 'HASH') {
                   12067:                 foreach my $control_item (keys(%{$curr_controls})) {
                   12068:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   12069:                     if (defined($todelete{$itemnum})) {
                   12070:                         push(@deletions,$file_name."\0".$control_item);
                   12071:                     } else {
                   12072:                         if (defined($changed_items{$itemnum})) {
                   12073:                             $new_control{$changed_items{$itemnum}} = $now;
                   12074:                             push(@deletions,$file_name."\0".$control_item);
                   12075:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   12076:                         } else {
                   12077:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   12078:                         }
                   12079:                     }
1.745     raeburn  12080:                 }
                   12081:             }
                   12082:         }
1.970     raeburn  12083:         my ($group);
                   12084:         if (&is_course($domain,$user)) {
                   12085:             ($group,my $file) = split(/\//,$file_name,2);
                   12086:         }
1.749     raeburn  12087:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   12088:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   12089:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   12090:         #  remove lock
                   12091:         my @del_lock = ($file_name."\0".'locked_access_records');
                   12092:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  12093:         my $sqlresult =
1.970     raeburn  12094:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  12095:                                     $group);
1.749     raeburn  12096:     } else {
                   12097:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  12098:     }
1.749     raeburn  12099:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  12100: }
                   12101: 
1.827     raeburn  12102: sub make_public_indefinitely {
1.1271    raeburn  12103:     my (@requrl) = @_;
                   12104:     return &automated_portfile_access('public',\@requrl);
                   12105: }
                   12106: 
                   12107: sub automated_portfile_access {
                   12108:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  12109:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   12110:         return 'invalid';
                   12111:     }
1.1271    raeburn  12112:     my %urls;
                   12113:     if (ref($addsref) eq 'ARRAY') {
                   12114:         foreach my $requrl (@{$addsref}) {
                   12115:             if (&is_portfolio_url($requrl)) {
                   12116:                 unless (exists($urls{$requrl})) {
                   12117:                     $urls{$requrl} = 'add';
                   12118:                 }
                   12119:             }
                   12120:         }
                   12121:     }
                   12122:     if (ref($delsref) eq 'ARRAY') {
                   12123:         foreach my $requrl (@{$delsref}) { 
                   12124:             if (&is_portfolio_url($requrl)) {
                   12125:                 unless (exists($urls{$requrl})) {
                   12126:                     $urls{$requrl} = 'delete'; 
                   12127:                 }
                   12128:             }
                   12129:         }
                   12130:     }
                   12131:     unless (keys(%urls)) {
                   12132:         return 'invalid';
                   12133:     }
                   12134:     my $ip;
                   12135:     if ($accesstype eq 'ip') {
                   12136:         if (ref($info) eq 'HASH') {
                   12137:             if ($info->{'ip'} ne '') {
                   12138:                 $ip = $info->{'ip'};
                   12139:             }
                   12140:         }
                   12141:         if ($ip eq '') {
                   12142:             return 'invalid';
                   12143:         }
                   12144:     }
                   12145:     my $errors;
1.827     raeburn  12146:     my $now = time;
1.1271    raeburn  12147:     my %current_perms;
                   12148:     foreach my $requrl (sort(keys(%urls))) {
                   12149:         my $action;
                   12150:         if ($urls{$requrl} eq 'add') {
                   12151:             $action = 'activate';
                   12152:         } else {
                   12153:             $action = 'none';
                   12154:         }
                   12155:         my $aclnum = 0;
1.827     raeburn  12156:         my (undef,$udom,$unum,$file_name,$group) =
                   12157:             &parse_portfolio_url($requrl);
1.1271    raeburn  12158:         unless (exists($current_perms{$unum.':'.$udom})) {
                   12159:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   12160:         }
                   12161:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  12162:                                                    $group,$file_name);
                   12163:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   12164:             my ($num,$scope,$end,$start) = 
                   12165:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  12166:             if ($scope eq $accesstype) {
                   12167:                 if (($start <= $now) && ($end == 0)) {
                   12168:                     if ($accesstype eq 'ip') {
                   12169:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   12170:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   12171:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   12172:                                     if ($urls{$requrl} eq 'add') {
                   12173:                                         $action = 'none';
                   12174:                                         last;
                   12175:                                     } else {
                   12176:                                         $action = 'delete';
                   12177:                                         $aclnum = $num;
                   12178:                                         last;
                   12179:                                     }
                   12180:                                 }
                   12181:                             }
                   12182:                         }
                   12183:                     } elsif ($accesstype eq 'public') {
                   12184:                         if ($urls{$requrl} eq 'add') {
                   12185:                             $action = 'none';
                   12186:                             last;
                   12187:                         } else {
                   12188:                             $action = 'delete';
                   12189:                             $aclnum = $num;
                   12190:                             last;
                   12191:                         }
                   12192:                     }
                   12193:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  12194:                     $action = 'update';
                   12195:                     $aclnum = $num;
1.1271    raeburn  12196:                     last;
1.827     raeburn  12197:                 }
                   12198:             }
                   12199:         }
                   12200:         if ($action eq 'none') {
1.1271    raeburn  12201:             next;
1.827     raeburn  12202:         } else {
                   12203:             my %changes;
                   12204:             my $newend = 0;
                   12205:             my $newstart = $now;
1.1271    raeburn  12206:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  12207:             $changes{$action}{$newkey} = {
1.1271    raeburn  12208:                 type => $accesstype,
1.827     raeburn  12209:                 time => {
                   12210:                     start => $newstart,
                   12211:                     end   => $newend,
                   12212:                 },
                   12213:             };
1.1271    raeburn  12214:             if ($accesstype eq 'ip') {
                   12215:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   12216:             }
1.827     raeburn  12217:             my ($outcome,$deloutcome,$new_values,$translation) =
                   12218:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  12219:             unless ($outcome eq 'ok') {
                   12220:                 $errors .= $outcome.' ';
                   12221:             }
1.827     raeburn  12222:         }
1.1271    raeburn  12223:     }
                   12224:     if ($errors) {
                   12225:         $errors =~ s/\s$//;
                   12226:         return $errors;
1.827     raeburn  12227:     } else {
1.1271    raeburn  12228:         return 'ok';
1.827     raeburn  12229:     }
                   12230: }
                   12231: 
1.745     raeburn  12232: #------------------------------------------------------Get Marked as Read Only
                   12233: 
                   12234: sub get_marked_as_readonly {
                   12235:     my ($domain,$user,$what,$group) = @_;
                   12236:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 12237:     my @readonly_files;
1.629     banghart 12238:     my $cmp1=$what;
                   12239:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  12240:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   12241:         if (defined($group)) {
                   12242:             if ($file_name !~ m-^\Q$group\E/-) {
                   12243:                 next;
                   12244:             }
                   12245:         }
1.561     banghart 12246:         if (ref($value) eq "ARRAY"){
                   12247:             foreach my $stored_what (@{$value}) {
1.629     banghart 12248:                 my $cmp2=$stored_what;
1.759     albertel 12249:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  12250:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  12251:                 }
1.629     banghart 12252:                 if ($cmp1 eq $cmp2) {
1.561     banghart 12253:                     push(@readonly_files, $file_name);
1.745     raeburn  12254:                     last;
1.563     banghart 12255:                 } elsif (!defined($what)) {
                   12256:                     push(@readonly_files, $file_name);
1.745     raeburn  12257:                     last;
1.561     banghart 12258:                 }
                   12259:             }
1.745     raeburn  12260:         }
1.561     banghart 12261:     }
                   12262:     return @readonly_files;
                   12263: }
1.577     banghart 12264: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 12265: 
1.577     banghart 12266: sub get_marked_as_readonly_hash {
1.745     raeburn  12267:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 12268:     my %readonly_files;
1.745     raeburn  12269:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   12270:         if (defined($group)) {
                   12271:             if ($file_name !~ m-^\Q$group\E/-) {
                   12272:                 next;
                   12273:             }
                   12274:         }
1.577     banghart 12275:         if (ref($value) eq "ARRAY"){
                   12276:             foreach my $stored_what (@{$value}) {
1.745     raeburn  12277:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 12278:                     foreach my $lock_descriptor(@{$stored_what}) {
                   12279:                         if ($lock_descriptor eq 'graded') {
                   12280:                             $readonly_files{$file_name} = 'graded';
                   12281:                         } elsif ($lock_descriptor eq 'handback') {
                   12282:                             $readonly_files{$file_name} = 'handback';
                   12283:                         } else {
                   12284:                             if (!exists($readonly_files{$file_name})) {
                   12285:                                 $readonly_files{$file_name} = 'locked';
                   12286:                             }
                   12287:                         }
1.745     raeburn  12288:                     }
1.750     banghart 12289:                 } 
1.577     banghart 12290:             }
                   12291:         } 
                   12292:     }
                   12293:     return %readonly_files;
                   12294: }
1.559     banghart 12295: # ------------------------------------------------------------ Unmark as Read Only
                   12296: 
                   12297: sub unmark_as_readonly {
1.629     banghart 12298:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   12299:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  12300:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 12301:     $file_name = &declutter_portfile($file_name);
1.634     albertel 12302:     my $symb_crs = $what;
                   12303:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  12304:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 12305:     my ($tmp)=keys(%current_permissions);
                   12306:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  12307:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 12308:     foreach my $file (@readonly_files) {
1.759     albertel 12309: 	my $clean_file = &declutter_portfile($file);
                   12310: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 12311: 	my $current_locks = $current_permissions{$file};
1.563     banghart 12312:         my @new_locks;
                   12313:         my @del_keys;
                   12314:         if (ref($current_locks) eq "ARRAY"){
                   12315:             foreach my $locker (@{$current_locks}) {
1.632     albertel 12316:                 my $compare=$locker;
1.749     raeburn  12317:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  12318:                     $compare=join('',@{$locker});
1.746     raeburn  12319:                     if ($compare ne $symb_crs) {
                   12320:                         push(@new_locks, $locker);
                   12321:                     }
1.563     banghart 12322:                 }
                   12323:             }
1.650     albertel 12324:             if (scalar(@new_locks) > 0) {
1.563     banghart 12325:                 $current_permissions{$file} = \@new_locks;
                   12326:             } else {
                   12327:                 push(@del_keys, $file);
1.613     albertel 12328:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 12329:                 delete($current_permissions{$file});
1.563     banghart 12330:             }
                   12331:         }
1.561     banghart 12332:     }
1.613     albertel 12333:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 12334:     return;
                   12335: }
1.512     banghart 12336: 
1.17      www      12337: # ------------------------------------------------------------ Directory lister
                   12338: 
                   12339: sub dirlist {
1.955     raeburn  12340:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      12341:     $uri=~s/^\///;
                   12342:     $uri=~s/\/$//;
1.253     stredwic 12343:     my ($udom, $uname);
1.955     raeburn  12344:     if ($getuserdir) {
1.253     stredwic 12345:         $udom = $userdomain;
                   12346:         $uname = $username;
1.955     raeburn  12347:     } else {
                   12348:         (undef,$udom,$uname)=split(/\//,$uri);
                   12349:         if(defined($userdomain)) {
                   12350:             $udom = $userdomain;
                   12351:         }
                   12352:         if(defined($username)) {
                   12353:             $uname = $username;
                   12354:         }
1.253     stredwic 12355:     }
1.955     raeburn  12356:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 12357: 
1.955     raeburn  12358:     $dirRoot = $perlvar{'lonDocRoot'};
                   12359:     if (defined($getpropath)) {
                   12360:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 12361:         $dirRoot =~ s/\/$//;
1.955     raeburn  12362:     } elsif (defined($getuserdir)) {
                   12363:         my $subdir=$uname.'__';
                   12364:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   12365:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   12366:                    ."/$udom/$subdir/$uname";
                   12367:     } elsif (defined($alternateRoot)) {
                   12368:         $dirRoot = $alternateRoot;
1.751     banghart 12369:     }
1.253     stredwic 12370: 
                   12371:     if($udom) {
                   12372:         if($uname) {
1.1135    raeburn  12373:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  12374:             if ($uhome eq 'no_host') {
                   12375:                 return ([],'no_host');
                   12376:             }
1.955     raeburn  12377:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  12378:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  12379:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  12380:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  12381:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  12382:             } else {
                   12383:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   12384:             }
1.605     matthew  12385:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  12386:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  12387:                 @listing_results = split(/:/,$listing);
                   12388:             } else {
                   12389:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   12390:             }
1.1135    raeburn  12391:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  12392:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   12393:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   12394:                 return ([],$listing);
                   12395:             } else {
                   12396:                 return (\@listing_results);
1.1135    raeburn  12397:             }
1.955     raeburn  12398:         } elsif(!$alternateRoot) {
1.1136    raeburn  12399:             my (%allusers,%listerror);
1.841     albertel 12400: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  12401:  	    foreach my $tryserver (keys(%servers)) {
                   12402:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   12403:                                   &escape($udom),$tryserver);
                   12404:                 if ($listing eq 'unknown_cmd') {
                   12405: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   12406: 				      $udom, $tryserver);
                   12407:                 } else {
                   12408:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   12409:                 }
1.841     albertel 12410: 		if ($listing eq 'unknown_cmd') {
                   12411: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   12412: 				      $udom, $tryserver);
                   12413: 		    @listing_results = split(/:/,$listing);
                   12414: 		} else {
                   12415: 		    @listing_results =
                   12416: 			map { &unescape($_); } split(/:/,$listing);
                   12417: 		}
1.1136    raeburn  12418:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   12419:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   12420:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   12421:                     $listerror{$tryserver} = $listing;
                   12422:                 } else {
1.841     albertel 12423: 		    foreach my $line (@listing_results) {
                   12424: 			my ($entry) = split(/&/,$line,2);
                   12425: 			$allusers{$entry} = 1;
                   12426: 		    }
                   12427: 		}
1.253     stredwic 12428:             }
1.1136    raeburn  12429:             my @alluserslist=();
1.800     albertel 12430:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  12431:                 push(@alluserslist,$user.'&user');
1.253     stredwic 12432:             }
1.1318    droeschl 12433: 
                   12434:             if (!%listerror) {
                   12435:                 # no errors
                   12436:                 return (\@alluserslist);
                   12437:             } elsif (scalar(keys(%servers)) == 1) {
                   12438:                 # one library server, one error 
                   12439:                 my ($key) = keys(%listerror);
                   12440:                 return (\@alluserslist, $listerror{$key});
                   12441:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   12442:                 # con_lost indicates that we might miss data from at least one
                   12443:                 # library server
                   12444:                 return (\@alluserslist, 'con_lost');
                   12445:             } else {
                   12446:                 # multiple library servers and no con_lost -> data should be
                   12447:                 # complete. 
                   12448:                 return (\@alluserslist);
                   12449:             }
                   12450: 
1.253     stredwic 12451:         } else {
1.1136    raeburn  12452:             return ([],'missing username');
1.253     stredwic 12453:         }
1.955     raeburn  12454:     } elsif(!defined($getpropath)) {
1.1136    raeburn  12455:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   12456:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   12457:         return (\@all_domains);
1.955     raeburn  12458:     } else {
1.1136    raeburn  12459:         return ([],'missing domain');
1.275     stredwic 12460:     }
                   12461: }
                   12462: 
                   12463: # --------------------------------------------- GetFileTimestamp
                   12464: # This function utilizes dirlist and returns the date stamp for
                   12465: # when it was last modified.  It will also return an error of -1
                   12466: # if an error occurs
                   12467: 
                   12468: sub GetFileTimestamp {
1.955     raeburn  12469:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 12470:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   12471:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  12472:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   12473:                                     undef,$getuserdir);
                   12474:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   12475:         return -1;
                   12476:     }
                   12477:     if (ref($fileref) eq 'ARRAY') {
                   12478:         my @stats = split('&',$fileref->[0]);
1.375     matthew  12479:         # @stats contains first the filename, then the stat output
                   12480:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 12481:     } else {
                   12482:         return -1;
1.253     stredwic 12483:     }
1.26      www      12484: }
                   12485: 
1.712     albertel 12486: sub stat_file {
                   12487:     my ($uri) = @_;
1.787     albertel 12488:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 12489: 
1.955     raeburn  12490:     my ($udom,$uname,$file);
1.712     albertel 12491:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   12492: 	($udom,$uname,$file) =
1.811     albertel 12493: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 12494: 	$file = 'userfiles/'.$file;
                   12495:     }
                   12496:     if ($uri =~ m-^/res/-) {
                   12497: 	($udom,$uname) = 
1.807     albertel 12498: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 12499: 	$file = $uri;
                   12500:     }
                   12501: 
                   12502:     if (!$udom || !$uname || !$file) {
                   12503: 	# unable to handle the uri
                   12504: 	return ();
                   12505:     }
1.956     raeburn  12506:     my $getpropath;
                   12507:     if ($file =~ /^userfiles\//) {
                   12508:         $getpropath = 1;
                   12509:     }
1.1136    raeburn  12510:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   12511:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   12512:         return ();
                   12513:     } else {
                   12514:         if (ref($listref) eq 'ARRAY') {
                   12515:             my @stats = split('&',$listref->[0]);
                   12516: 	    shift(@stats); #filename is first
                   12517: 	    return @stats;
                   12518:         }
1.712     albertel 12519:     }
                   12520:     return ();
                   12521: }
                   12522: 
1.1313    raeburn  12523: # --------------------------------------------------------- recursedirs
                   12524: # Recursive function to traverse either a specific user's Authoring Space
                   12525: # or corresponding Published Resource Space, and populate the hash ref:
                   12526: # $dirhashref with URLs of all directories, and if $filehashref hash
                   12527: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
1.1503    raeburn  12528: # or .rights files in resource space, and .meta, .save, .log, .bak and
                   12529: # .rights files in Authoring Space.
1.1313    raeburn  12530: #
                   12531: # Inputs:
                   12532: #
                   12533: # $is_home - true if current server is home server for user's space
1.1503    raeburn  12534: # $recurse - if true will also traverse subdirectories recursively
                   12535: # $include - reference to hash containing allowed file extensions.  If provided,
                   12536: #             files which do not have a matching extension will be ignored.
                   12537: # $exclude - reference to hash containing excluded file extensions.  If provided,
                   12538: #             files which have a matching extension will be ignored.
                   12539: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
                   12540: #             directory with first file found (with acceptable extension).
1.1505    raeburn  12541: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
1.1313    raeburn  12542: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   12543: # $relpath - Current path (relative to top level).
                   12544: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   12545: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   12546: #
                   12547: # Returns: nothing
                   12548: #
                   12549: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   12550: #
                   12551: # Currently used by interface/londocs.pm to create linked select boxes for
                   12552: # directory and filename to import a Course "Author" resource into a course, and
                   12553: # also to create linked select boxes for Authoring Space and Directory to choose
                   12554: # save location for creation of a new "standard" problem from the Course Editor.
                   12555: #
                   12556: 
                   12557: sub recursedirs {
1.1505    raeburn  12558:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
1.1313    raeburn  12559:     return unless (ref($dirhashref) eq 'HASH');
1.1503    raeburn  12560:     my $docroot = $perlvar{'lonDocRoot'};
1.1313    raeburn  12561:     my $currpath = $docroot.$toppath;
1.1503    raeburn  12562:     if ($relpath ne '') {
1.1313    raeburn  12563:         $currpath .= "/$relpath";
                   12564:     }
1.1503    raeburn  12565:     my ($savefile,$checkinc,$checkexc);
1.1313    raeburn  12566:     if (ref($filehashref)) {
                   12567:         $savefile = 1;
                   12568:     }
1.1503    raeburn  12569:     if (ref($include) eq 'HASH') {
                   12570:         $checkinc = 1;
                   12571:     }
                   12572:     if (ref($exclude) eq 'HASH') {
                   12573:         $checkexc = 1;
                   12574:     }
1.1313    raeburn  12575:     if ($is_home) {
1.1505    raeburn  12576:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
1.1503    raeburn  12577:             my $filecount = 0;
1.1313    raeburn  12578:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   12579:                 next if ($item eq '');
                   12580:                 if (-d "$currpath/$item") {
                   12581:                     my $newpath;
1.1503    raeburn  12582:                     if ($relpath ne '') {
1.1313    raeburn  12583:                         $newpath = "$relpath/$item";
                   12584:                     } else {
                   12585:                         $newpath = $item;
                   12586:                     }
                   12587:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503    raeburn  12588:                     if ($recurse) {
1.1505    raeburn  12589:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
1.1503    raeburn  12590:                     }
                   12591:                 } elsif (($savefile) || ($relpath eq '')) {
                   12592:                     next if ($nonemptydir && $filecount);
                   12593:                     if ($checkinc || $checkexc) {
                   12594:                         my ($extension) = ($item =~ /\.(\w+)$/);
                   12595:                         if ($checkinc) {
                   12596:                             next unless ($extension && $include->{$extension});
                   12597:                         }
                   12598:                         if ($checkexc) {
                   12599:                             next if ($extension && $exclude->{$extension});
                   12600:                         }
                   12601:                     }
1.1505    raeburn  12602:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
1.1503    raeburn  12603:                         $dirhashref->{'/'} = 1;
                   12604:                     }
                   12605:                     if ($savefile) {
                   12606:                         if ($relpath eq '') {
                   12607:                             $filehashref->{'/'}{$item} = 1;
                   12608:                         } else {
1.1313    raeburn  12609:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   12610:                         }
                   12611:                     }
1.1503    raeburn  12612:                     $filecount ++;
1.1313    raeburn  12613:                 }
                   12614:             }
                   12615:             closedir($dirh);
                   12616:         }
                   12617:     } else {
                   12618:         my ($dirlistref,$listerror) =
                   12619:             &dirlist($toppath.$relpath);
                   12620:         my @dir_lines;
                   12621:         my $dirptr=16384;
                   12622:         if (ref($dirlistref) eq 'ARRAY') {
1.1503    raeburn  12623:             my $filecount = 0;
1.1313    raeburn  12624:             foreach my $dir_line (sort
                   12625:                               {
                   12626:                                   my ($afile)=split('&',$a,2);
                   12627:                                   my ($bfile)=split('&',$b,2);
                   12628:                                   return (lc($afile) cmp lc($bfile));
                   12629:                               } (@{$dirlistref})) {
                   12630:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   12631:                     split(/\&/,$dir_line,16);
                   12632:                 $item =~ s/\s+$//;
                   12633:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   12634:                 if ($dirptr&$testdir) {
                   12635:                     my $newpath;
                   12636:                     if ($relpath) {
                   12637:                         $newpath = "$relpath/$item";
                   12638:                     } else {
                   12639:                         $newpath = $item;
                   12640:                     }
                   12641:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503    raeburn  12642:                     if ($recurse) {
1.1505    raeburn  12643:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
1.1503    raeburn  12644:                     }
                   12645:                 } elsif (($savefile) || ($relpath eq '')) {
                   12646:                     next if ($nonemptydir && $filecount);
                   12647:                     if ($checkinc || $checkexc) {
                   12648:                         my $extension;
                   12649:                         if ($checkinc) {
                   12650:                             next unless ($extension && $include->{$extension});
                   12651:                         }
                   12652:                         if ($checkexc) {
                   12653:                             next if ($extension && $exclude->{$extension});
                   12654:                         }
                   12655:                     }
                   12656:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
                   12657:                         $dirhashref->{'/'} = 1;
                   12658:                     }
                   12659:                     if ($savefile) {
                   12660:                         if ($relpath eq '') {
                   12661:                             $filehashref->{'/'}{$item} = 1;
                   12662:                         } else {
                   12663:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
1.1313    raeburn  12664:                         }
                   12665:                     }
1.1503    raeburn  12666:                     $filecount ++; 
1.1313    raeburn  12667:                 }
                   12668:             }
                   12669:         }
                   12670:     }
1.1505    raeburn  12671:     if ($addtopdir) {
                   12672:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
                   12673:             $dirhashref->{'/'} = 1;
                   12674:         }
                   12675:     }
1.1313    raeburn  12676:     return;
                   12677: }
                   12678: 
1.1503    raeburn  12679: sub priv_exclude {
                   12680:     return {
                   12681:              meta => 1,
                   12682:              save => 1,
                   12683:              log => 1,
                   12684:              bak => 1,
                   12685:              rights => 1,
                   12686:              DS_Store => 1,
                   12687:            };
                   12688: }
                   12689: 
1.26      www      12690: # -------------------------------------------------------- Value of a Condition
                   12691: 
1.713     albertel 12692: # gets the value of a specific preevaluated condition
                   12693: #    stored in the string  $env{user.state.<cid>}
                   12694: # or looks up a condition reference in the bighash and if if hasn't
                   12695: # already been evaluated recurses into docondval to get the value of
                   12696: # the condition, then memoizing it to 
                   12697: #   $env{user.state.<cid>.<condition>}
1.40      www      12698: sub directcondval {
                   12699:     my $number=shift;
1.620     albertel 12700:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 12701: 	&Apache::lonuserstate::evalstate();
                   12702:     }
1.713     albertel 12703:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   12704: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   12705:     } elsif ($number =~ /^_/) {
                   12706: 	my $sub_condition;
                   12707: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12708: 		&GDBM_READER(),0640)) {
                   12709: 	    $sub_condition=$bighash{'conditions'.$number};
                   12710: 	    untie(%bighash);
                   12711: 	}
                   12712: 	my $value = &docondval($sub_condition);
1.949     raeburn  12713: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 12714: 	return $value;
                   12715:     }
1.620     albertel 12716:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   12717:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      12718:     } else {
                   12719:        return 2;
                   12720:     }
                   12721: }
                   12722: 
1.713     albertel 12723: # get the collection of conditions for this resource
1.26      www      12724: sub condval {
                   12725:     my $condidx=shift;
1.54      www      12726:     my $allpathcond='';
1.713     albertel 12727:     foreach my $cond (split(/\|/,$condidx)) {
                   12728: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   12729: 	    $allpathcond.=
                   12730: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   12731: 	}
1.191     harris41 12732:     }
1.54      www      12733:     $allpathcond=~s/\|$//;
1.713     albertel 12734:     return &docondval($allpathcond);
                   12735: }
                   12736: 
                   12737: #evaluates an expression of conditions
                   12738: sub docondval {
                   12739:     my ($allpathcond) = @_;
                   12740:     my $result=0;
                   12741:     if ($env{'request.course.id'}
                   12742: 	&& defined($allpathcond)) {
                   12743: 	my $operand='|';
                   12744: 	my @stack;
                   12745: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   12746: 	    if ($chunk eq '(') {
                   12747: 		push @stack,($operand,$result);
                   12748: 	    } elsif ($chunk eq ')') {
                   12749: 		my $before=pop @stack;
                   12750: 		if (pop @stack eq '&') {
                   12751: 		    $result=$result>$before?$before:$result;
                   12752: 		} else {
                   12753: 		    $result=$result>$before?$result:$before;
                   12754: 		}
                   12755: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   12756: 		$operand=$chunk;
                   12757: 	    } else {
                   12758: 		my $new=directcondval($chunk);
                   12759: 		if ($operand eq '&') {
                   12760: 		    $result=$result>$new?$new:$result;
                   12761: 		} else {
                   12762: 		    $result=$result>$new?$result:$new;
                   12763: 		}
                   12764: 	    }
                   12765: 	}
1.26      www      12766:     }
                   12767:     return $result;
1.421     albertel 12768: }
                   12769: 
                   12770: # ---------------------------------------------------- Devalidate courseresdata
                   12771: 
                   12772: sub devalidatecourseresdata {
                   12773:     my ($coursenum,$coursedomain)=@_;
                   12774:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12775:     &devalidate_cache_new('courseres',$hashid);
1.28      www      12776: }
                   12777: 
1.763     www      12778: 
1.200     www      12779: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     12780: #
                   12781: #  Parameters:
                   12782: #      $coursenum    - Number of the course.
                   12783: #      $coursedomain - Domain at which the course was created.
                   12784: #  Returns:
                   12785: #     A hash of the course parameters along (I think) with timestamps
                   12786: #     and version info.
1.877     foxr     12787: 
1.624     albertel 12788: sub get_courseresdata {
                   12789:     my ($coursenum,$coursedomain)=@_;
1.200     www      12790:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   12791:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12792:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 12793:     my %dumpreply;
1.417     albertel 12794:     unless (defined($cached)) {
1.624     albertel 12795: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 12796: 	$result=\%dumpreply;
1.251     albertel 12797: 	my ($tmp) = keys(%dumpreply);
                   12798: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 12799: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 12800: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   12801: 	    return $tmp;
1.416     albertel 12802: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 12803: 	    $result=undef;
1.599     albertel 12804: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 12805: 	}
                   12806:     }
1.624     albertel 12807:     return $result;
                   12808: }
                   12809: 
1.633     albertel 12810: sub devalidateuserresdata {
                   12811:     my ($uname,$udom)=@_;
                   12812:     my $hashid="$udom:$uname";
                   12813:     &devalidate_cache_new('userres',$hashid);
                   12814: }
                   12815: 
1.624     albertel 12816: sub get_userresdata {
                   12817:     my ($uname,$udom)=@_;
                   12818:     #most student don\'t have any data set, check if there is some data
                   12819:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   12820: 
                   12821:     my $hashid="$udom:$uname";
                   12822:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   12823:     if (!defined($cached)) {
                   12824: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   12825: 	$result=\%resourcedata;
                   12826: 	&do_cache_new('userres',$hashid,$result,600);
                   12827:     }
                   12828:     my ($tmp)=keys(%$result);
                   12829:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   12830: 	return $result;
                   12831:     }
                   12832:     #error 2 occurs when the .db doesn't exist
                   12833:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  12834:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   12835: 	    &logthis("<font color=\"blue\">WARNING:".
                   12836: 		     " Trying to get resource data for ".
                   12837: 		     $uname." at ".$udom.": ".
                   12838: 		     $tmp."</font>");
                   12839:         }
1.624     albertel 12840:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 12841: 	#&EXT_cache_set($udom,$uname);
                   12842: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 12843: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 12844:     }
                   12845:     return $tmp;
                   12846: }
1.879     foxr     12847: #----------------------------------------------- resdata - return resource data
                   12848: #  Purpose:
                   12849: #    Return resource data for either users or for a course.
                   12850: #  Parameters:
                   12851: #     $name      - Course/user name.
                   12852: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  12853: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  12854: #     $mapp      - decluttered URL of enclosing map  
                   12855: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   12856: #     $recurseup - Ref to array of map URLs, starting with map containing
                   12857: #                  $mapp up through hierarchy of nested maps to top level map.  
                   12858: #     $courseid  - CourseID (first part of param identifier).
                   12859: #     $modifier  - Middle part of param identifier.
                   12860: #     $what      - Last part of param identifier.
1.879     foxr     12861: #     @which     - Array of names of resources desired.
                   12862: #  Returns:
                   12863: #     The value of the first reasource in @which that is found in the
                   12864: #     resource hash.
                   12865: #  Exceptional Conditions:
                   12866: #     If the $type passed in is not valid (not the string 'course' or 
                   12867: #     'user', an undefined  reference is returned.
                   12868: #     If none of the resources are found, an undef is returned
1.624     albertel 12869: sub resdata {
1.1301    raeburn  12870:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   12871:         $modifier,$what,@which)=@_;
1.624     albertel 12872:     my $result;
                   12873:     if ($type eq 'course') {
                   12874: 	$result=&get_courseresdata($name,$domain);
                   12875:     } elsif ($type eq 'user') {
                   12876: 	$result=&get_userresdata($name,$domain);
                   12877:     }
                   12878:     if (!ref($result)) { return $result; }    
1.251     albertel 12879:     foreach my $item (@which) {
1.1301    raeburn  12880:         if ($item->[1] eq 'course') {
                   12881:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   12882:                 unless ($$recursed) {
1.1302    raeburn  12883:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  12884:                     $$recursed = 1;
                   12885:                 }
                   12886:                 foreach my $item (@${recurseup}) {
                   12887:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   12888:                     last if (defined($result->{$norecursechk}));
                   12889:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   12890:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   12891:                 }
                   12892:             }
                   12893:         }
                   12894:         if (defined($result->{$item->[0]})) {
1.927     albertel 12895: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12896: 	}
1.250     albertel 12897:     }
1.291     albertel 12898:     return undef;
1.200     www      12899: }
                   12900: 
1.1360    raeburn  12901: sub get_domain_lti {
                   12902:     my ($cdom,$context) = @_;
1.1483    raeburn  12903:     my ($name,$cachename,%lti);
1.1360    raeburn  12904:     if ($context eq 'consumer') {
                   12905:         $name = 'ltitools';
                   12906:     } elsif ($context eq 'provider') {
                   12907:         $name = 'lti';
1.1483    raeburn  12908:     } elsif ($context eq 'linkprot') {
                   12909:         $name = 'ltisec';
1.1360    raeburn  12910:     } else {
                   12911:         return %lti;
                   12912:     }
1.1483    raeburn  12913:     if ($context eq 'linkprot') {
                   12914:         $cachename = $context;
                   12915:     } else {
                   12916:         $cachename = $name;
                   12917:     }
                   12918:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298    raeburn  12919:     if (defined($cached)) {
                   12920:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12921:             %lti = %{$result};
1.1298    raeburn  12922:         }
                   12923:     } else {
1.1360    raeburn  12924:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12925:         if (ref($domconfig{$name}) eq 'HASH') {
1.1483    raeburn  12926:             if ($context eq 'linkprot') {
                   12927:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12928:                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12929:                 }
                   12930:             } else {
                   12931:                 %lti = %{$domconfig{$name}};
                   12932:             }
1.1298    raeburn  12933:         }
                   12934:         my $cachetime = 24*60*60;
1.1483    raeburn  12935:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298    raeburn  12936:     }
1.1360    raeburn  12937:     return %lti;
1.1298    raeburn  12938: }
                   12939: 
1.1463    raeburn  12940: sub get_course_lti {
1.1510    raeburn  12941:     my ($cnum,$cdom,$context) = @_;
                   12942:     my ($name,$cachename,%lti);
                   12943:     if ($context eq 'consumer') {
                   12944:         $name = 'ltitools';
                   12945:         $cachename = 'courseltitools';
                   12946:     } elsif ($context eq 'provider') {
                   12947:         $name = 'lti';
                   12948:         $cachename = 'courselti';
                   12949:     } else {
                   12950:         return %lti;
                   12951:     }
1.1463    raeburn  12952:     my $hashid=$cdom.'_'.$cnum;
1.1510    raeburn  12953:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
1.1463    raeburn  12954:     if (defined($cached)) {
                   12955:         if (ref($result) eq 'HASH') {
1.1510    raeburn  12956:             %lti = %{$result};
1.1463    raeburn  12957:         }
                   12958:     } else {
1.1510    raeburn  12959:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
1.1463    raeburn  12960:         my $cachetime = 24*60*60;
1.1510    raeburn  12961:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
1.1463    raeburn  12962:     }
1.1510    raeburn  12963:     return %lti;
1.1463    raeburn  12964: }
                   12965: 
1.1479    raeburn  12966: sub courselti_itemid {
                   12967:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12968:     my ($chome,$itemid);
                   12969:     $chome = &homeserver($cnum,$cdom);
                   12970:     return if ($chome eq 'no_host');
                   12971:     if (ref($params) eq 'HASH') {
                   12972:         my $rep;
                   12973:         if (grep { $_ eq $chome } current_machine_ids()) {
                   12974:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12975:         } else {
                   12976:             my $escurl = &escape($url);
                   12977:             my $escmethod = &escape($method);
                   12978:             my $items = &freeze_escape($params);
                   12979:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12980:         }
                   12981:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12982:                 ($rep eq 'unknown_cmd')) {
                   12983:             $itemid = $rep;
                   12984:         }
                   12985:     }
                   12986:     return $itemid;
                   12987: }
                   12988: 
                   12989: sub domainlti_itemid {
                   12990:     my ($cdom,$url,$method,$params,$context) = @_;
                   12991:     my ($primary_id,$itemid);
                   12992:     $primary_id = &domain($cdom,'primary');
                   12993:     return if ($primary_id eq '');
                   12994:     if (ref($params) eq 'HASH') {
                   12995:         my $rep;
                   12996:         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12997:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12998:         } else {
                   12999:             my $cnum = '';
                   13000:             my $escurl = &escape($url);
                   13001:             my $escmethod = &escape($method);
                   13002:             my $items = &freeze_escape($params);
                   13003:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   13004:         }
                   13005:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   13006:                 ($rep eq 'unknown_cmd')) {
                   13007:             $itemid = $rep;
                   13008:         }
                   13009:     }
                   13010:     return $itemid;
                   13011: }
                   13012: 
1.1513    raeburn  13013: sub get_ltitools_id {
                   13014:     my ($context,$cdom,$cnum,$title) = @_;
                   13015:     my ($lockhash,$tries,$gotlock,$id,$error);
                   13016: 
                   13017:     # get lock on ltitools db
                   13018:     $lockhash = {
                   13019:                    lock => $env{'user.name'}.
                   13020:                            ':'.$env{'user.domain'},
                   13021:                 };
                   13022:     $tries = 0;
                   13023:     if ($context eq 'domain') {
                   13024:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   13025:     } else {
                   13026:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   13027:     }
                   13028:     while (($gotlock ne 'ok') && ($tries<10)) {
                   13029:         $tries ++;
                   13030:         sleep (0.1);
                   13031:         if ($context eq 'domain') {
                   13032:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   13033:         } else {
                   13034:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   13035:         }
                   13036:     }
                   13037:     if ($gotlock eq 'ok') {
                   13038:         my %currids;
                   13039:         if ($context eq 'domain') {
                   13040:             %currids = &dump_dom('ltitools',$cdom);
                   13041:         } else {
                   13042:             %currids = &dump('ltitools',$cdom,$cnum);
                   13043:         }
                   13044:         if ($currids{'lock'}) {
                   13045:             delete($currids{'lock'});
                   13046:             if (keys(%currids)) {
                   13047:                 my @curr = sort { $a <=> $b } keys(%currids);
                   13048:                 if ($curr[-1] =~ /^\d+$/) {
                   13049:                     $id = 1 + $curr[-1];
                   13050:                 }
                   13051:             } else {
                   13052:                 $id = 1;
                   13053:             }
                   13054:             if ($id) {
                   13055:                 if ($context eq 'domain') {
                   13056:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
                   13057:                         $error = 'nostore';
                   13058:                     }
                   13059:                 } else {
                   13060:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
                   13061:                         $error = 'nostore';
                   13062:                     }
                   13063:                 }
                   13064:             } else {
                   13065:                 $error = 'nonumber';
                   13066:             }
                   13067:         }
                   13068:         my $dellockoutcome;
                   13069:         if ($context eq 'domain') {
                   13070:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
                   13071:         } else {
                   13072:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
                   13073:         }
                   13074:     } else {
                   13075:         $error = 'nolock';
                   13076:     }
                   13077:     return ($id,$error);
                   13078: }
                   13079: 
1.1496    raeburn  13080: sub count_supptools {
                   13081:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
                   13082:     my $hashid=$cnum.':'.$cdom;
                   13083:     my ($numexttools,$cached);
                   13084:     unless ($ignorecache) {
                   13085:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
                   13086:     }
                   13087:     unless (defined($cached)) {
                   13088:         my $chome=&homeserver($cnum,$cdom);
                   13089:         $numexttools = 0;
                   13090:         unless ($chome eq 'no_host') {
1.1500    raeburn  13091:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
1.1496    raeburn  13092:             if (ref($supplemental) eq 'HASH') {
                   13093:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   13094:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   13095:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   13096:                             $numexttools ++;
                   13097:                         }
                   13098:                     }
                   13099:                 }
                   13100:             }
                   13101:         }
                   13102:         &do_cache_new('supptools',$hashid,$numexttools,600);
                   13103:     }
                   13104:     return $numexttools;
                   13105: }
                   13106: 
                   13107: sub has_unhidden_suppfiles {
1.1498    raeburn  13108:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
1.1236    raeburn  13109:     my $hashid=$cnum.':'.$cdom;
1.1496    raeburn  13110:     my ($showsupp,$cached);
1.1236    raeburn  13111:     unless ($ignorecache) {
1.1496    raeburn  13112:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
1.1236    raeburn  13113:     }
                   13114:     unless (defined($cached)) {
                   13115:         my $chome=&homeserver($cnum,$cdom);
                   13116:         unless ($chome eq 'no_host') {
1.1500    raeburn  13117:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
1.1496    raeburn  13118:             if (ref($supplemental) eq 'HASH') {
                   13119:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   13120:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   13121:                         next if ($key =~ /\.sequence$/);
                   13122:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   13123:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   13124:                                 unless ($supplemental->{'hidden'}->{$id}) {
                   13125:                                     $showsupp = 1;
                   13126:                                     last;
                   13127:                                 }
                   13128:                             }
                   13129:                         }
                   13130:                         last if ($showsupp);
                   13131:                     }
                   13132:                 }
                   13133:             }
1.1236    raeburn  13134:         }
1.1496    raeburn  13135:         &do_cache_new('showsupp',$hashid,$showsupp,600);
1.1236    raeburn  13136:     }
1.1496    raeburn  13137:     return $showsupp;
                   13138: }
                   13139: 
1.379     matthew  13140: #
                   13141: # EXT resource caching routines
                   13142: #
                   13143: 
1.1302    raeburn  13144: {
                   13145: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   13146: #
                   13147: # The course for which we cache
                   13148: my $cachedmapkey='';
                   13149: # The cached recursive maps for this course
                   13150: my %cachedmaps=();
                   13151: # When this was last done
                   13152: my $cachedmaptime='';
                   13153: 
1.379     matthew  13154: sub clear_EXT_cache_status {
1.383     albertel 13155:     &delenv('cache.EXT.');
1.379     matthew  13156: }
                   13157: 
                   13158: sub EXT_cache_status {
                   13159:     my ($target_domain,$target_user) = @_;
1.383     albertel 13160:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 13161:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  13162:         # We know already the user has no data
                   13163:         return 1;
                   13164:     } else {
                   13165:         return 0;
                   13166:     }
                   13167: }
                   13168: 
                   13169: sub EXT_cache_set {
                   13170:     my ($target_domain,$target_user) = @_;
1.383     albertel 13171:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  13172:     #&appenv({$cachename => time});
1.379     matthew  13173: }
                   13174: 
1.28      www      13175: # --------------------------------------------------------- Value of a Variable
1.58      www      13176: sub EXT {
1.715     albertel 13177: 
1.1461    raeburn  13178:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68      www      13179:     unless ($varname) { return ''; }
1.218     albertel 13180:     #get real user name/domain, courseid and symb
                   13181:     my $courseid;
1.359     albertel 13182:     my $publicuser;
1.427     www      13183:     if ($symbparm) {
                   13184: 	$symbparm=&get_symb_from_alias($symbparm);
                   13185:     }
1.218     albertel 13186:     if (!($uname && $udom)) {
1.790     albertel 13187:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 13188:       if (!$symbparm) {	$symbparm=$cursymb; }
                   13189:     } else {
1.620     albertel 13190: 	$courseid=$env{'request.course.id'};
1.218     albertel 13191:     }
1.48      www      13192:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   13193:     my $rest;
1.320     albertel 13194:     if (defined($therest[0])) {
1.48      www      13195:        $rest=join('.',@therest);
                   13196:     } else {
                   13197:        $rest='';
                   13198:     }
1.320     albertel 13199: 
1.57      www      13200:     my $qualifierrest=$qualifier;
                   13201:     if ($rest) { $qualifierrest.='.'.$rest; }
                   13202:     my $spacequalifierrest=$space;
                   13203:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      13204:     if ($realm eq 'user') {
1.48      www      13205: # --------------------------------------------------------------- user.resource
                   13206: 	if ($space eq 'resource') {
1.651     albertel 13207: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   13208: 		  || defined($Apache::lonhomework::parsing_a_task))
                   13209: 		 &&
1.1469    raeburn  13210: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 13211: 		# if we are in the middle of processing the resource the
                   13212: 		# get the value we are planning on committing
                   13213:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   13214:                     return $Apache::lonhomework::results{$qualifierrest};
                   13215:                 } else {
                   13216:                     return $Apache::lonhomework::history{$qualifierrest};
                   13217:                 }
1.335     albertel 13218: 	    } else {
1.359     albertel 13219: 		my %restored;
1.620     albertel 13220: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 13221: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   13222: 		} else {
                   13223: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   13224: 		}
1.335     albertel 13225: 		return $restored{$qualifierrest};
                   13226: 	    }
1.48      www      13227: # ----------------------------------------------------------------- user.access
                   13228:         } elsif ($space eq 'access') {
1.218     albertel 13229: 	    # FIXME - not supporting calls for a specific user
1.48      www      13230:             return &allowed($qualifier,$rest);
                   13231: # ------------------------------------------ user.preferences, user.environment
                   13232:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 13233: 	    if (($uname eq $env{'user.name'}) &&
                   13234: 		($udom eq $env{'user.domain'})) {
                   13235: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 13236: 	    } else {
1.359     albertel 13237: 		my %returnhash;
                   13238: 		if (!$publicuser) {
                   13239: 		    %returnhash=&userenvironment($udom,$uname,
                   13240: 						 $qualifierrest);
                   13241: 		}
1.218     albertel 13242: 		return $returnhash{$qualifierrest};
                   13243: 	    }
1.48      www      13244: # ----------------------------------------------------------------- user.course
                   13245:         } elsif ($space eq 'course') {
1.218     albertel 13246: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 13247:             return $env{join('.',('request.course',$qualifier))};
1.48      www      13248: # ------------------------------------------------------------------- user.role
                   13249:         } elsif ($space eq 'role') {
1.218     albertel 13250: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 13251:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      13252:             if ($qualifier eq 'value') {
                   13253: 		return $role;
                   13254:             } elsif ($qualifier eq 'extent') {
                   13255:                 return $where;
                   13256:             }
                   13257: # ----------------------------------------------------------------- user.domain
                   13258:         } elsif ($space eq 'domain') {
1.218     albertel 13259:             return $udom;
1.48      www      13260: # ------------------------------------------------------------------- user.name
                   13261:         } elsif ($space eq 'name') {
1.218     albertel 13262:             return $uname;
1.48      www      13263: # ---------------------------------------------------- Any other user namespace
1.29      www      13264:         } else {
1.359     albertel 13265: 	    my %reply;
                   13266: 	    if (!$publicuser) {
                   13267: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   13268: 	    }
                   13269: 	    return $reply{$qualifierrest};
1.48      www      13270:         }
1.236     www      13271:     } elsif ($realm eq 'query') {
                   13272: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 13273:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   13274: 						[$spacequalifierrest]);
1.620     albertel 13275: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      13276:    } elsif ($realm eq 'request') {
1.48      www      13277: # ------------------------------------------------------------- request.browser
                   13278:         if ($space eq 'browser') {
1.1145    bisitz   13279:             return $env{'browser.'.$qualifier};
1.57      www      13280: # ------------------------------------------------------------ request.filename
                   13281:         } else {
1.620     albertel 13282:             return $env{'request.'.$spacequalifierrest};
1.29      www      13283:         }
1.28      www      13284:     } elsif ($realm eq 'course') {
1.48      www      13285: # ---------------------------------------------------------- course.description
1.620     albertel 13286:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      13287:     } elsif ($realm eq 'resource') {
1.165     www      13288: 
1.620     albertel 13289: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 13290: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   13291: 	}
1.693     albertel 13292: 
1.1232    raeburn  13293:         if ($qualifier eq '') {
                   13294: 	    if ($space eq 'title') {
                   13295: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   13296: 	        return &gettitle($symbparm);
                   13297: 	    }
1.693     albertel 13298: 	
1.1232    raeburn  13299: 	    if ($space eq 'map') {
                   13300: 	        my ($map) = &decode_symb($symbparm);
                   13301: 	        return &symbread($map);
                   13302: 	    }
                   13303:             if ($space eq 'maptitle') {
                   13304:                 my ($map) = &decode_symb($symbparm);
                   13305:                 return &gettitle($map);
                   13306:             }
                   13307: 	    if ($space eq 'filename') {
                   13308: 	        if ($symbparm) {
                   13309: 		    return &clutter((&decode_symb($symbparm))[2]);
                   13310: 	        }
                   13311: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 13312: 	    }
1.1232    raeburn  13313: 
1.1233    raeburn  13314:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   13315:                 if ($space eq 'visibleparts') {
                   13316:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   13317:                     my $item;
                   13318:                     if (ref($navmap)) {
                   13319:                         my $res = $navmap->getBySymb($symbparm);
                   13320:                         my $parts = $res->parts();
                   13321:                         if (ref($parts) eq 'ARRAY') {
                   13322:                             $item = join(',',@{$parts});
                   13323:                         }
                   13324:                         undef($navmap);
1.1232    raeburn  13325:                     }
1.1233    raeburn  13326:                     return $item;
1.1232    raeburn  13327:                 }
                   13328:             }
                   13329:         }
1.693     albertel 13330: 
1.1301    raeburn  13331: 	my ($section, $group, @groups, @recurseup, $recursed);
1.1461    raeburn  13332:         if (ref($recurseupref) eq 'ARRAY') {
                   13333:             @recurseup = @{$recurseupref};
                   13334:             $recursed = 1;
                   13335:         }
1.1301    raeburn  13336: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  13337:         if (($courseid eq '') && ($cid)) {
                   13338:             $courseid = $cid;
                   13339:         }
                   13340: 	if (($symbparm && $courseid) && 
                   13341: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      13342: 
1.218     albertel 13343: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      13344: 
1.60      www      13345: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 13346: 	    my $symbp=$symbparm;
1.1301    raeburn  13347: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 13348: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  13349:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 13350: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 13351: 	    if (($env{'user.name'} eq $uname) &&
                   13352: 		($env{'user.domain'} eq $udom)) {
                   13353: 		$section=$env{'request.course.sec'};
1.733     raeburn  13354:                 @groups = split(/:/,$env{'request.course.groups'});  
                   13355:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 13356: 	    } else {
1.539     albertel 13357: 		if (! defined($usection)) {
1.551     albertel 13358: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 13359: 		} else {
                   13360: 		    $section = $usection;
                   13361: 		}
1.733     raeburn  13362:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 13363: 	    }
                   13364: 
                   13365: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   13366: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  13367:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 13368: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   13369: 
1.593     albertel 13370: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 13371: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  13372:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 13373: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      13374: 
1.60      www      13375: # ----------------------------------------------------------- first, check user
1.624     albertel 13376: 
1.1301    raeburn  13377: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   13378:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 13379: 				       ([$courselevelr,'resource'],
                   13380: 					[$courselevelm,'map'     ],
1.1301    raeburn  13381:                                         [$courseleveli,'map'     ],
1.927     albertel 13382: 					[$courselevel, 'course'  ]));
1.931     albertel 13383: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      13384: 
1.594     albertel 13385: # ------------------------------------------------ second, check some of course
1.684     raeburn  13386:             my $coursereply;
1.691     raeburn  13387:             if (@groups > 0) {
                   13388:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  13389:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   13390:                                        $mapp,\$recursed,\@recurseup);
                   13391:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  13392:             }
1.96      www      13393: 
1.684     raeburn  13394: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 13395: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  13396: 				  'course',$mapp,\$recursed,\@recurseup,
                   13397:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 13398: 				  ([$seclevelr,   'resource'],
                   13399: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  13400:                                    [$secleveli,   'map'     ],
1.927     albertel 13401: 				   [$seclevel,    'course'  ],
                   13402: 				   [$courselevelr,'resource']));
                   13403: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      13404: 
1.60      www      13405: # ------------------------------------------------------ third, check map parms
1.218     albertel 13406: 	    my %parmhash=();
                   13407: 	    my $thisparm='';
                   13408: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 13409: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 13410: 		    &GDBM_READER(),0640)) {
1.218     albertel 13411: 		$thisparm=$parmhash{$symbparm};
                   13412: 		untie(%parmhash);
                   13413: 	    }
1.927     albertel 13414: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 13415: 	}
1.594     albertel 13416: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  13417:  
                   13418:         my $what = $spacequalifierrest;
                   13419: 	$what=~s/\./\_/;
1.282     albertel 13420: 	my $filename;
                   13421: 	if (!$symbparm) { $symbparm=&symbread(); }
                   13422: 	if ($symbparm) {
1.409     www      13423: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 13424: 	} else {
1.620     albertel 13425: 	    $filename=$env{'request.filename'};
1.282     albertel 13426: 	}
1.1362    raeburn  13427:         my $toolsymb;
                   13428:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   13429:             $toolsymb = $symbparm;
                   13430:         }
                   13431: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 13432: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  13433: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 13434: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      13435: 
1.1301    raeburn  13436: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 13437: 	if ($symbparm && defined($courseid) && 
1.620     albertel 13438: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 13439: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   13440: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  13441: 				     'course',$mapp,\$recursed,\@recurseup,
                   13442:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 13443: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  13444:                                       [$courseleveli,'map'   ],
1.927     albertel 13445: 				      [$courselevel, 'course']));
                   13446: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 13447: 	}
1.145     www      13448: # ------------------------------------------------------------------ Cascade up
1.218     albertel 13449: 	unless ($space eq '0') {
1.336     albertel 13450: 	    my @parts=split(/_/,$space);
                   13451: 	    my $id=pop(@parts);
                   13452: 	    my $part=join('_',@parts);
                   13453: 	    if ($part eq '') { $part='0'; }
1.927     albertel 13454: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 13455: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  13456: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 13457: 	}
1.395     albertel 13458: 	if ($recurse) { return undef; }
1.1362    raeburn  13459: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 13460: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      13461: # ---------------------------------------------------- Any other user namespace
                   13462:     } elsif ($realm eq 'environment') {
                   13463: # ----------------------------------------------------------------- environment
1.620     albertel 13464: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   13465: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 13466: 	} else {
1.770     albertel 13467: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   13468: 		return '';
                   13469: 	    }
1.219     albertel 13470: 	    my %returnhash=&userenvironment($udom,$uname,
                   13471: 					    $spacequalifierrest);
                   13472: 	    return $returnhash{$spacequalifierrest};
                   13473: 	}
1.28      www      13474:     } elsif ($realm eq 'system') {
1.48      www      13475: # ----------------------------------------------------------------- system.time
                   13476: 	if ($space eq 'time') {
                   13477: 	    return time;
                   13478:         }
1.696     albertel 13479:     } elsif ($realm eq 'server') {
                   13480: # ----------------------------------------------------------------- system.time
                   13481: 	if ($space eq 'name') {
                   13482: 	    return $ENV{'SERVER_NAME'};
                   13483:         }
1.1415    raeburn  13484:     } elsif ($realm eq 'client') {
                   13485:         if ($space eq 'remote_addr') {
1.1441    raeburn  13486:             return &get_requestor_ip();
1.1415    raeburn  13487:         }
1.28      www      13488:     }
1.48      www      13489:     return '';
1.61      www      13490: }
                   13491: 
1.927     albertel 13492: sub get_reply {
                   13493:     my ($reply_value) = @_;
1.940     raeburn  13494:     if (ref($reply_value) eq 'ARRAY') {
                   13495:         if (wantarray) {
                   13496: 	    return @$reply_value;
                   13497:         }
                   13498:         return $reply_value->[0];
                   13499:     } else {
                   13500:         return $reply_value;
1.927     albertel 13501:     }
                   13502: }
                   13503: 
1.691     raeburn  13504: sub check_group_parms {
1.1301    raeburn  13505:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   13506:         $recursed,$recurseupref) = @_;
                   13507:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   13508:                   [$what,'course']);
                   13509:     my $coursereply;
1.691     raeburn  13510:     foreach my $group (@{$groups}) {
1.1301    raeburn  13511:         my @groupitems = ();
1.691     raeburn  13512:         foreach my $level (@levels) {
1.927     albertel 13513:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   13514:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  13515:         }
1.1301    raeburn  13516:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   13517:                                    $env{'course.'.$courseid.'.domain'},
                   13518:                                    'course',$mapp,$recursed,$recurseupref,
                   13519:                                    $courseid,'.['.$group.'].',$what,
                   13520:                                    @groupitems);
                   13521:         last if (defined($coursereply));
1.691     raeburn  13522:     }
                   13523:     return $coursereply;
                   13524: }
                   13525: 
1.1301    raeburn  13526: sub get_map_hierarchy {
1.1302    raeburn  13527:     my ($mapname,$courseid) = @_;
                   13528:     my @recurseup = ();
1.1301    raeburn  13529:     if ($mapname) {
1.1302    raeburn  13530:         if (($cachedmapkey eq $courseid) &&
                   13531:             (abs($cachedmaptime-time)<5)) {
                   13532:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   13533:                 return @{$cachedmaps{$mapname}};
                   13534:             }
                   13535:         }
1.1301    raeburn  13536:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13537:         if (ref($navmap)) {
                   13538:             @recurseup = $navmap->recurseup_maps($mapname);
                   13539:             undef($navmap);
1.1302    raeburn  13540:             $cachedmaps{$mapname} = \@recurseup;
                   13541:             $cachedmaptime=time;
                   13542:             $cachedmapkey=$courseid;
1.1301    raeburn  13543:         }
                   13544:     }
                   13545:     return @recurseup;
                   13546: }
                   13547: 
1.1302    raeburn  13548: }
                   13549: 
1.691     raeburn  13550: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  13551:     my ($courseid,@groups) = @_;
                   13552:     @groups = sort(@groups);
1.691     raeburn  13553:     return @groups;
                   13554: }
                   13555: 
1.395     albertel 13556: sub packages_tab_default {
1.1362    raeburn  13557:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 13558:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 13559: 
                   13560:     my (@extension,@specifics,$do_default);
1.1362    raeburn  13561:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 13562: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 13563: 	if ($pack_type eq 'default') {
                   13564: 	    $do_default=1;
                   13565: 	} elsif ($pack_type eq 'extension') {
                   13566: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 13567: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 13568: 	    # only look at packages defaults for packages that this id is
1.738     albertel 13569: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   13570: 	}
                   13571:     }
                   13572:     # first look for a package that matches the requested part id
                   13573:     foreach my $package (@specifics) {
                   13574: 	my (undef,$pack_type,$pack_part)=@{$package};
                   13575: 	next if ($pack_part ne $part);
                   13576: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   13577: 	    return $packagetab{"$pack_type&$name&default"};
                   13578: 	}
                   13579:     }
                   13580:     # look for any possible matching non extension_ package
                   13581:     foreach my $package (@specifics) {
                   13582: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 13583: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   13584: 	    return $packagetab{"$pack_type&$name&default"};
                   13585: 	}
1.585     albertel 13586: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 13587: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   13588: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 13589: 	}
                   13590:     }
1.738     albertel 13591:     # look for any posible extension_ match
                   13592:     foreach my $package (@extension) {
                   13593: 	my ($package,$pack_type)=@{$package};
                   13594: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   13595: 	    return $packagetab{"$pack_type&$name&default"};
                   13596: 	}
                   13597: 	if (defined($packagetab{$package."&$name&default"})) {
                   13598: 	    return $packagetab{$package."&$name&default"};
                   13599: 	}
                   13600:     }
                   13601:     # look for a global default setting
                   13602:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   13603: 	return $packagetab{"default&$name&default"};
                   13604:     }
1.395     albertel 13605:     return undef;
                   13606: }
                   13607: 
1.334     albertel 13608: sub add_prefix_and_part {
                   13609:     my ($prefix,$part)=@_;
                   13610:     my $keyroot;
                   13611:     if (defined($prefix) && $prefix !~ /^__/) {
                   13612: 	# prefix that has a part already
                   13613: 	$keyroot=$prefix;
                   13614:     } elsif (defined($prefix)) {
                   13615: 	# prefix that is missing a part
                   13616: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   13617:     } else {
                   13618: 	# no prefix at all
                   13619: 	if (defined($part)) { $keyroot='_'.$part; }
                   13620:     }
                   13621:     return $keyroot;
                   13622: }
                   13623: 
1.71      www      13624: # ---------------------------------------------------------------- Get metadata
                   13625: 
1.599     albertel 13626: my %metaentry;
1.1070    www      13627: my %importedpartids;
1.1369    raeburn  13628: my %importedrespids;
1.71      www      13629: sub metadata {
1.1362    raeburn  13630:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      13631:     $uri=&declutter($uri);
1.288     albertel 13632:     # if it is a non metadata possible uri return quickly
1.529     albertel 13633:     if (($uri eq '') || 
                   13634: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  13635: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  13636:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 13637: 	return undef;
                   13638:     }
1.1261    raeburn  13639:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 13640: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 13641: 	return undef;
1.288     albertel 13642:     }
1.73      www      13643:     my $filename=$uri;
                   13644:     $uri=~s/\.meta$//;
1.172     www      13645: #
                   13646: # Is the metadata already cached?
1.177     www      13647: # Look at timestamp of caching
1.172     www      13648: # Everything is cached by the main uri, libraries are never directly cached
                   13649: #
1.428     albertel 13650:     if (!defined($liburi)) {
1.599     albertel 13651: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 13652: 	if (defined($cached)) { return $result->{':'.$what}; }
                   13653:     }
1.1362    raeburn  13654: 
                   13655: #
                   13656: # If the uri is for an external tool the file from
                   13657: # which metadata should be retrieved depends on whether
                   13658: # the tool had been configured to be gradable (set in the Course
                   13659: # Editor or Resource Editor).
                   13660: #
                   13661: # If a valid symb has been included as the third arg in the call
                   13662: # to &metadata() that can be used to retrieve the value of
                   13663: # parameter_0_gradable set for the resource, and included in the
                   13664: # uploaded map containing the tool. The value is retrieved via
                   13665: # &EXT(), if a valid symb is available.  Otherwise the value of
                   13666: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  13667: # is retrieved via &get().
                   13668: #
                   13669: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   13670: # hiddenresource and encrypturl (during course initialization)
                   13671: # the map-level parameter for resource.0.gradable included in the 
                   13672: # uploaded map containing the tool will not yet have been stored
                   13673: # in the user_course_parms.db file for the user's session, so in 
                   13674: # this case fall back to retrieving gradable status from the
                   13675: # exttool_$marker.db file.
1.1362    raeburn  13676: #
                   13677: # In order to avoid an infinite loop, &metadata() will return
                   13678: # before a call to &EXT(), if the uri is for an external tool
                   13679: # and the $what for which metadata is being requested is
                   13680: # parameter_0_gradable or 0_gradable.
                   13681: #
                   13682: 
                   13683:     if ($uri =~ /ext\.tool$/) {
                   13684:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   13685:             return;
                   13686:         } else {
                   13687:             my ($checked,$use_passback);
                   13688:             if ($toolsymb ne '') {
                   13689:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  13690:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  13691:                     $checked = 1;
                   13692:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   13693:                         $use_passback = 1;
                   13694:                     }
                   13695:                 }
                   13696:             }
                   13697:             unless ($checked) {
                   13698:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   13699:                 $marker=~s/\D//g;
1.1363    raeburn  13700:                 if ($marker) {
1.1362    raeburn  13701:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   13702:                     $use_passback = $toolsettings{'gradable'};
                   13703:                 }
                   13704:             }
                   13705:             if ($use_passback) {
                   13706:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   13707:             } else {
                   13708:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   13709:             }
                   13710:         }
                   13711:     }
                   13712: 
1.428     albertel 13713:     {
1.1069    www      13714: # Imported parts would go here
1.1369    raeburn  13715:         my @origfiletagids=();
1.1069    www      13716:         my $importedparts=0;
1.1369    raeburn  13717: 
                   13718: # Imported responseids would go here
                   13719:         my $importedresponses=0;
1.172     www      13720: #
                   13721: # Is this a recursive call for a library?
                   13722: #
1.599     albertel 13723: #	if (! exists($metacache{$uri})) {
                   13724: #	    $metacache{$uri}={};
                   13725: #	}
1.924     albertel 13726: 	my $cachetime = 60*60;
1.171     www      13727:         if ($liburi) {
                   13728: 	    $liburi=&declutter($liburi);
                   13729:             $filename=$liburi;
1.401     bowersj2 13730:         } else {
1.599     albertel 13731: 	    &devalidate_cache_new('meta',$uri);
                   13732: 	    undef(%metaentry);
1.401     bowersj2 13733: 	}
1.140     www      13734:         my %metathesekeys=();
1.73      www      13735:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 13736: 	my $metastring;
1.1140    www      13737: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 13738: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 13739: 	    $metastring = 
1.929     albertel 13740: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 13741: 					  ('grade_target' => 'meta'));
                   13742: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  13743: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   13744:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 13745: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 13746: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 13747: 	    $metastring=&getfile($file);
1.489     albertel 13748: 	}
1.208     albertel 13749:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      13750:         my $token;
1.140     www      13751:         undef %metathesekeys;
1.71      www      13752:         while ($token=$parser->get_token) {
1.339     albertel 13753: 	    if ($token->[0] eq 'S') {
                   13754: 		if (defined($token->[2]->{'package'})) {
1.172     www      13755: #
                   13756: # This is a package - get package info
                   13757: #
1.339     albertel 13758: 		    my $package=$token->[2]->{'package'};
                   13759: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13760: 		    if (defined($token->[2]->{'id'})) { 
                   13761: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   13762: 		    }
1.599     albertel 13763: 		    if ($metaentry{':packages'}) {
                   13764: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 13765: 		    } else {
1.599     albertel 13766: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 13767: 		    }
1.736     albertel 13768: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 13769: 			my $part=$keyroot;
                   13770: 			$part=~s/^\_//;
1.736     albertel 13771: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   13772: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   13773: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 13774: 			    # ignore package.tab specified default values
                   13775:                             # here &package_tab_default() will fetch those
                   13776: 			    if ($subp eq 'default') { next; }
1.736     albertel 13777: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 13778: 			    my $unikey;
                   13779: 			    if ($pack =~ /_0$/) {
                   13780: 				$unikey='parameter_0_'.$name;
                   13781: 				$part=0;
                   13782: 			    } else {
                   13783: 				$unikey='parameter'.$keyroot.'_'.$name;
                   13784: 			    }
1.339     albertel 13785: 			    if ($subp eq 'display') {
                   13786: 				$value.=' [Part: '.$part.']';
                   13787: 			    }
1.599     albertel 13788: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 13789: 			    $metathesekeys{$unikey}=1;
1.599     albertel 13790: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13791: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 13792: 			    }
1.599     albertel 13793: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   13794: 				$metaentry{':'.$unikey}=
                   13795: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 13796: 			    }
1.339     albertel 13797: 			}
                   13798: 		    }
                   13799: 		} else {
1.172     www      13800: #
                   13801: # This is not a package - some other kind of start tag
1.339     albertel 13802: #
                   13803: 		    my $entry=$token->[1];
1.1068    www      13804: 		    my $unikey='';
1.175     www      13805: 
1.339     albertel 13806: 		    if ($entry eq 'import') {
1.175     www      13807: #
                   13808: # Importing a library here
1.339     albertel 13809: #
1.1067    www      13810:                         my $location=$parser->get_text('/import');
                   13811:                         my $dir=$filename;
                   13812:                         $dir=~s|[^/]*$||;
                   13813:                         $location=&filelocation($dir,$location);
1.1369    raeburn  13814: 
                   13815:                         my $importid=$token->[2]->{'id'};
1.1068    www      13816:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  13817: #
                   13818: # Check metadata for imported file to
                   13819: # see if it contained response items
                   13820: #
1.1372    raeburn  13821:                         my ($origfile,@libfilekeys);
1.1370    raeburn  13822:                         my %currmetaentry = %metaentry;
1.1372    raeburn  13823:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   13824:                                                            $depthcount+1));
                   13825:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   13826:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   13827:                                                              undef,$depthcount+1);
                   13828:                             if ($libresponseorder ne '') {
                   13829:                                 if ($#origfiletagids<0) {
                   13830:                                     undef(%importedrespids);
                   13831:                                     undef(%importedpartids);
                   13832:                                 }
1.1373    raeburn  13833:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   13834:                                 if (@respids) {
                   13835:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   13836:                                 }
                   13837:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  13838:                                     $importedresponses = 1;
1.1369    raeburn  13839: # We need to get the original file and the imported file to get the response order correct
                   13840: # Load and inspect original file
1.1372    raeburn  13841:                                     if ($#origfiletagids<0) {
                   13842:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13843:                                         $origfile=&getfile($origfilelocation);
                   13844:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13845:                                     }
1.1369    raeburn  13846:                                 }
                   13847:                             }
                   13848:                         }
1.1370    raeburn  13849: # Do not overwrite contents of %metaentry hash for resource itself with 
                   13850: # hash populated for imported library file
                   13851:                         %metaentry = %currmetaentry;
                   13852:                         undef(%currmetaentry);
1.1374    raeburn  13853:                         if ($importmode eq 'part') {
1.1068    www      13854: # Import as part(s)
1.1069    www      13855:                            $importedparts=1;
                   13856: # We need to get the original file and the imported file to get the part order correct
                   13857: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  13858: # Load and inspect original file if we didn't do that already
                   13859:                            if ($#origfiletagids<0) {
                   13860:                                undef(%importedrespids);
                   13861:                                undef(%importedpartids);
                   13862:                                if ($origfile eq '') {
                   13863:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13864:                                    $origfile=&getfile($origfilelocation);
                   13865:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13866:                                }
1.1070    www      13867:                            }
1.1372    raeburn  13868:                            my @impfilepartids;
                   13869: # If <partorder> tag is included in metadata for the imported file
                   13870: # get the parts in the imported file from that.
                   13871:                            if (grep(/^partorder$/,@libfilekeys)) {
                   13872:                                %currmetaentry = %metaentry;
                   13873:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13874:                                                             $depthcount+1);
                   13875:                                %metaentry = %currmetaentry;
                   13876:                                undef(%currmetaentry);
                   13877:                                if ($libpartorder ne '') {
                   13878:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   13879:                                }
                   13880:                            } else {
                   13881: # If no <partorder> tag available, load and inspect imported file
                   13882:                                my $impfile=&getfile($location);
                   13883:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13884:                            }
1.1069    www      13885:                            if ($#impfilepartids>=0) {
                   13886: # This problem had parts
1.1070    www      13887:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      13888:                            } else {
                   13889: # Importing by turning a single problem into a problem part
                   13890: # It gets the import-tags ID as part-ID
                   13891:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      13892:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      13893:                            }
1.1068    www      13894:                         } else {
1.1374    raeburn  13895: # Import as problem or as normal import
                   13896:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13897:                             unless ($importmode eq 'problem') {
1.1068    www      13898: # Normal import
1.1374    raeburn  13899:                                 if (defined($token->[2]->{'id'})) {
                   13900:                                     $unikey.='_'.$token->[2]->{'id'};
                   13901:                                 }
                   13902:                             }
                   13903: # Check metadata for imported file to
                   13904: # see if it contained parts
                   13905:                             if (grep(/^partorder$/,@libfilekeys)) {
                   13906:                                 %currmetaentry = %metaentry;
                   13907:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13908:                                                              $depthcount+1);
                   13909:                                 %metaentry = %currmetaentry;
                   13910:                                 undef(%currmetaentry);
                   13911:                                 if ($libpartorder ne '') {
                   13912:                                     $importedparts = 1;
                   13913:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   13914:                                 }
                   13915:                             }
1.1067    www      13916:                         }
1.339     albertel 13917: 			if ($depthcount<20) {
1.736     albertel 13918: 			    my $metadata = 
1.1362    raeburn  13919: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 13920: 					  $depthcount+1);
                   13921: 			    foreach my $meta (split(',',$metadata)) {
                   13922: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   13923: 				$metathesekeys{$meta}=1;
1.339     albertel 13924: 			    }
1.1068    www      13925:                         }
1.1067    www      13926: 		    } else {
                   13927: #
                   13928: # Not importing, some other kind of non-package, non-library start tag
                   13929: # 
                   13930:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13931:                         if (defined($token->[2]->{'id'})) {
                   13932:                             $unikey.='_'.$token->[2]->{'id'};
                   13933:                         }
1.339     albertel 13934: 			if (defined($token->[2]->{'name'})) { 
                   13935: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13936: 			}
                   13937: 			$metathesekeys{$unikey}=1;
1.736     albertel 13938: 			foreach my $param (@{$token->[3]}) {
                   13939: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13940: 				$token->[2]->{$param};
1.339     albertel 13941: 			}
                   13942: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13943: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13944: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13945: 		 # only ws inside the tag, and not in default, so use default
                   13946: 		 # as value
1.599     albertel 13947: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13948: 			} elsif ( $internaltext =~ /\S/ ) {
                   13949: 		  # something interesting inside the tag
                   13950: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13951: 			} else {
1.908     albertel 13952: 		  # no interesting values, don't set a default
1.339     albertel 13953: 			}
1.172     www      13954: # end of not-a-package not-a-library import
1.339     albertel 13955: 		    }
1.172     www      13956: # end of not-a-package start tag
1.339     albertel 13957: 		}
1.172     www      13958: # the next is the end of "start tag"
1.339     albertel 13959: 	    }
                   13960: 	}
1.483     albertel 13961: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13962: 	$extension = lc($extension);
                   13963: 	if ($extension eq 'htm') { $extension='html'; }
                   13964: 
1.737     albertel 13965: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13966: 	    #no specific packages #how's our extension
                   13967: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13968: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13969: 					 \%metathesekeys);
                   13970: 	}
1.883     albertel 13971: 
                   13972: 	if (!exists($metaentry{':packages'})
                   13973: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13974: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13975: 		#no specific packages well let's get default then
                   13976: 		if ($key!~/^default&/) { next; }
1.488     albertel 13977: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13978: 					     \%metathesekeys);
                   13979: 	    }
                   13980: 	}
1.338     www      13981: # are there custom rights to evaluate
1.599     albertel 13982: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13983: 
1.338     www      13984:     #
                   13985:     # Importing a rights file here
1.339     albertel 13986:     #
                   13987: 	    unless ($depthcount) {
1.599     albertel 13988: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13989: 		my $dir=$filename;
                   13990: 		$dir=~s|[^/]*$||;
                   13991: 		$location=&filelocation($dir,$location);
1.736     albertel 13992: 		my $rights_metadata =
1.1362    raeburn  13993: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13994: 			      $depthcount+1);
                   13995: 		foreach my $rights (split(',',$rights_metadata)) {
                   13996: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13997: 		    $metathesekeys{$rights}=1;
1.339     albertel 13998: 		}
                   13999: 	    }
                   14000: 	}
1.737     albertel 14001: 	# uniqifiy package listing
                   14002: 	my %seen;
                   14003: 	my @uniq_packages =
                   14004: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   14005: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   14006: 
1.1369    raeburn  14007:         if (($importedresponses) || ($importedparts)) {
                   14008:             if ($importedparts) {
1.1070    www      14009: # We had imported parts and need to rebuild partorder
1.1369    raeburn  14010:                 $metaentry{':partorder'}='';
                   14011:                 $metathesekeys{'partorder'}=1;
                   14012:             }
                   14013:             if ($importedresponses) {
                   14014: # We had imported responses and need to rebuil responseorder
                   14015:                 $metaentry{':responseorder'}='';
                   14016:                 $metathesekeys{'responseorder'}=1;
                   14017:             }
                   14018:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   14019:                 my $origid = $origfiletagids[$index+1];
                   14020:                 if ($origfiletagids[$index] eq 'part') {
                   14021: # Original part, part of the problem
                   14022:                     if ($importedparts) {
                   14023:                         $metaentry{':partorder'}.=','.$origid;
                   14024:                     }
                   14025:                 } elsif ($origfiletagids[$index] eq 'import') {
                   14026:                     if ($importedparts) {
                   14027: # We have imported parts at this position
1.1373    raeburn  14028:                         if ($importedpartids{$origid} ne '') {
                   14029:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   14030:                         }
1.1369    raeburn  14031:                     }
                   14032:                     if ($importedresponses) {
                   14033: # We have imported responses at this position
1.1373    raeburn  14034:                         if ($importedrespids{$origid} ne '') {
                   14035:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  14036:                         }
                   14037:                     }
                   14038:                 } else {
                   14039: # Original response item, part of the problem
                   14040:                     if ($importedresponses) {
                   14041:                         $metaentry{':responseorder'}.=','.$origid;
                   14042:                     }
                   14043:                 }
                   14044:             }
                   14045:             if ($importedparts) {
                   14046:                 $metaentry{':partorder'}=~s/^\,//;
                   14047:             }
                   14048:             if ($importedresponses) {
                   14049:                 $metaentry{':responseorder'}=~s/^\,//;
                   14050:             }
1.1070    www      14051:         }
1.737     albertel 14052: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 14053: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  14054: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  14055:         unless ($liburi) {
                   14056: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   14057:         }
1.177     www      14058: # this is the end of "was not already recently cached
1.71      www      14059:     }
1.599     albertel 14060:     return $metaentry{':'.$what};
1.261     albertel 14061: }
                   14062: 
1.488     albertel 14063: sub metadata_create_package_def {
1.483     albertel 14064:     my ($uri,$key,$package,$metathesekeys)=@_;
                   14065:     my ($pack,$name,$subp)=split(/\&/,$key);
                   14066:     if ($subp eq 'default') { next; }
                   14067:     
1.599     albertel 14068:     if (defined($metaentry{':packages'})) {
                   14069: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 14070:     } else {
1.599     albertel 14071: 	$metaentry{':packages'}=$package;
1.483     albertel 14072:     }
                   14073:     my $value=$packagetab{$key};
                   14074:     my $unikey;
                   14075:     $unikey='parameter_0_'.$name;
1.599     albertel 14076:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 14077:     $$metathesekeys{$unikey}=1;
1.599     albertel 14078:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   14079: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 14080:     }
1.599     albertel 14081:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   14082: 	$metaentry{':'.$unikey}=
                   14083: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 14084:     }
                   14085: }
                   14086: 
1.261     albertel 14087: sub metadata_generate_part0 {
                   14088:     my ($metadata,$metacache,$uri) = @_;
                   14089:     my %allnames;
1.737     albertel 14090:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 14091: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 14092: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   14093: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 14094: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 14095: 	    $allnames{$name}=$part;
                   14096: 	  }
                   14097: 	}
                   14098:     }
                   14099:     foreach my $name (keys(%allnames)) {
                   14100:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 14101:       my $key=":parameter_0_$name";
1.261     albertel 14102:       $$metacache{"$key.part"}='0';
                   14103:       $$metacache{"$key.name"}=$name;
1.428     albertel 14104:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 14105: 					   $allnames{$name}.'_'.$name.
                   14106: 					   '.type'};
1.428     albertel 14107:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 14108: 			     '.display'};
1.644     www      14109:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 14110:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 14111:       $$metacache{"$key.display"}=$olddis;
                   14112:     }
1.71      www      14113: }
                   14114: 
1.764     albertel 14115: # ------------------------------------------------------ Devalidate title cache
                   14116: 
                   14117: sub devalidate_title_cache {
                   14118:     my ($url)=@_;
                   14119:     if (!$env{'request.course.id'}) { return; }
                   14120:     my $symb=&symbread($url);
                   14121:     if (!$symb) { return; }
                   14122:     my $key=$env{'request.course.id'}."\0".$symb;
                   14123:     &devalidate_cache_new('title',$key);
                   14124: }
                   14125: 
1.1014    droeschl 14126: # ------------------------------------------------- Get the title of a course
                   14127: 
                   14128: sub current_course_title {
                   14129:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   14130: }
1.301     www      14131: # ------------------------------------------------- Get the title of a resource
                   14132: 
                   14133: sub gettitle {
                   14134:     my $urlsymb=shift;
                   14135:     my $symb=&symbread($urlsymb);
1.534     albertel 14136:     if ($symb) {
1.620     albertel 14137: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 14138: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 14139: 	if (defined($cached)) { 
                   14140: 	    return $result;
                   14141: 	}
1.534     albertel 14142: 	my ($map,$resid,$url)=&decode_symb($symb);
                   14143: 	my $title='';
1.907     albertel 14144: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   14145: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   14146: 	} else {
                   14147: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   14148: 		    &GDBM_READER(),0640)) {
                   14149: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   14150: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   14151: 		untie(%bighash);
                   14152: 	    }
1.534     albertel 14153: 	}
                   14154: 	$title=~s/\&colon\;/\:/gs;
                   14155: 	if ($title) {
1.1159    www      14156: # Remember both $symb and $title for dynamic metadata
                   14157:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      14158:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      14159: # Cache this title and then return it
1.599     albertel 14160: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 14161: 	}
                   14162: 	$urlsymb=$url;
                   14163:     }
                   14164:     my $title=&metadata($urlsymb,'title');
                   14165:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   14166:     return $title;
1.301     www      14167: }
1.613     albertel 14168: 
1.614     albertel 14169: sub get_slot {
                   14170:     my ($which,$cnum,$cdom)=@_;
                   14171:     if (!$cnum || !$cdom) {
1.790     albertel 14172: 	(undef,my $courseid)=&whichuser();
1.620     albertel 14173: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   14174: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 14175:     }
1.703     albertel 14176:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   14177:     my %slotinfo;
                   14178:     if (exists($remembered{$key})) {
                   14179: 	$slotinfo{$which} = $remembered{$key};
                   14180:     } else {
                   14181: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   14182: 	&Apache::lonhomework::showhash(%slotinfo);
                   14183: 	my ($tmp)=keys(%slotinfo);
                   14184: 	if ($tmp=~/^error:/) { return (); }
                   14185: 	$remembered{$key} = $slotinfo{$which};
                   14186:     }
1.616     albertel 14187:     if (ref($slotinfo{$which}) eq 'HASH') {
                   14188: 	return %{$slotinfo{$which}};
                   14189:     }
                   14190:     return $slotinfo{$which};
1.614     albertel 14191: }
1.1150    raeburn  14192: 
                   14193: sub get_reservable_slots {
                   14194:     my ($cnum,$cdom,$uname,$udom) = @_;
                   14195:     my $now = time;
                   14196:     my $reservable_info;
                   14197:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   14198:     if (exists($remembered{$key})) {
                   14199:         $reservable_info = $remembered{$key};
                   14200:     } else {
                   14201:         my %resv;
                   14202:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   14203:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   14204:         $reservable_info = \%resv;
                   14205:         $remembered{$key} = $reservable_info;
                   14206:     }
                   14207:     return $reservable_info;
                   14208: }
                   14209: 
                   14210: sub get_course_slots {
                   14211:     my ($cnum,$cdom) = @_;
                   14212:     my $hashid=$cnum.':'.$cdom;
1.1494    raeburn  14213:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
1.1150    raeburn  14214:     if (defined($cached)) {
                   14215:         if (ref($result) eq 'HASH') {
                   14216:             return %{$result};
                   14217:         }
                   14218:     } else {
1.1494    raeburn  14219:         my %slots=&dump('slots',$cdom,$cnum);
1.1150    raeburn  14220:         my ($tmp) = keys(%slots);
                   14221:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  14222:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  14223:             return %slots;
                   14224:         }
                   14225:     }
                   14226:     return;
                   14227: }
                   14228: 
                   14229: sub devalidate_slots_cache {
                   14230:     my ($cnum,$cdom)=@_;
                   14231:     my $hashid=$cnum.':'.$cdom;
                   14232:     &devalidate_cache_new('allslots',$hashid);
                   14233: }
                   14234: 
1.1181    raeburn  14235: sub get_coursechange {
                   14236:     my ($cdom,$cnum) = @_;
                   14237:     if ($cdom eq '' || $cnum eq '') {
                   14238:         return unless ($env{'request.course.id'});
                   14239:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   14240:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   14241:     }
                   14242:     my $hashid=$cdom.'_'.$cnum;
                   14243:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   14244:     if ((defined($cached)) && ($change ne '')) {
                   14245:         return $change;
                   14246:     } else {
                   14247:         my %crshash;
                   14248:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   14249:         if ($crshash{'internal.contentchange'} eq '') {
                   14250:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   14251:             if ($change eq '') {
                   14252:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   14253:                 $change = $crshash{'internal.created'};
                   14254:             }
                   14255:         } else {
                   14256:             $change = $crshash{'internal.contentchange'};
                   14257:         }
                   14258:         my $cachetime = 600;
                   14259:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   14260:     }
                   14261:     return $change;
                   14262: }
                   14263: 
                   14264: sub devalidate_coursechange_cache {
1.1496    raeburn  14265:     my ($cdom,$cnum)=@_;
                   14266:     my $hashid=$cdom.'_'.$cnum;
1.1181    raeburn  14267:     &devalidate_cache_new('crschange',$hashid);
                   14268: }
                   14269: 
1.1496    raeburn  14270: sub get_suppchange {
                   14271:     my ($cdom,$cnum) = @_;
                   14272:     if ($cdom eq '' || $cnum eq '') {
                   14273:         return unless ($env{'request.course.id'});
                   14274:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   14275:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   14276:     }
                   14277:     my $hashid=$cdom.'_'.$cnum;
                   14278:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   14279:     if ((defined($cached)) && ($change ne '')) {
                   14280:         return $change;
                   14281:     } else {
                   14282:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   14283:         if ($crshash{'internal.supplementalchange'} eq '') {
                   14284:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   14285:             if ($change eq '') {
                   14286:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   14287:                 $change = $crshash{'internal.created'};
                   14288:             }
                   14289:         } else {
                   14290:             $change = $crshash{'internal.supplementalchange'};
                   14291:         }
                   14292:         my $cachetime = 600;
                   14293:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   14294:     }
                   14295:     return $change;
                   14296: }
                   14297: 
                   14298: sub devalidate_suppchange_cache {
                   14299:     my ($cdom,$cnum)=@_;
                   14300:     my $hashid=$cdom.'_'.$cnum;
                   14301:     &devalidate_cache_new('suppchange',$hashid);
                   14302: }
                   14303: 
1.1497    raeburn  14304: sub update_supp_caches {
                   14305:     my ($cdom,$cnum) = @_;
                   14306:     my %servers = &internet_dom_servers($cdom);
                   14307:     my @ids=&current_machine_ids();
                   14308:     foreach my $server (keys(%servers)) {
                   14309:         next if (grep(/^\Q$server\E$/,@ids));
                   14310:         my $hashid=$cnum.':'.$cdom;
                   14311:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   14312:         &remote_devalidate_cache($server,[$cachekey]);
                   14313:     }
                   14314:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   14315:     &count_supptools($cnum,$cdom,1);
                   14316:     my $now = time;
                   14317:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   14318:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   14319:     }
                   14320:     &put('environment',{'internal.supplementalchange' => $now},
                   14321:          $cdom,$cnum);
                   14322:     &Apache::lonnet::appenv(
                   14323:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   14324:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   14325: }
                   14326: 
1.31      www      14327: # ------------------------------------------------- Update symbolic store links
                   14328: 
                   14329: sub symblist {
                   14330:     my ($mapname,%newhash)=@_;
1.438     www      14331:     $mapname=&deversion(&declutter($mapname));
1.31      www      14332:     my %hash;
1.620     albertel 14333:     if (($env{'request.course.fn'}) && (%newhash)) {
                   14334:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 14335:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  14336: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 14337: 		next if ($url eq 'last_known'
                   14338: 			 && $env{'form.no_update_last_known'});
                   14339: 		$hash{declutter($url)}=&encode_symb($mapname,
                   14340: 						    $newhash{$url}->[1],
                   14341: 						    $newhash{$url}->[0]);
1.191     harris41 14342:             }
1.31      www      14343:             if (untie(%hash)) {
                   14344: 		return 'ok';
                   14345:             }
                   14346:         }
                   14347:     }
                   14348:     return 'error';
1.212     www      14349: }
                   14350: 
                   14351: # --------------------------------------------------------------- Verify a symb
                   14352: 
                   14353: sub symbverify {
1.1190    raeburn  14354:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      14355:     my $thisfn=$thisurl;
1.439     www      14356:     $thisfn=&declutter($thisfn);
1.215     www      14357: # direct jump to resource in page or to a sequence - will construct own symbs
                   14358:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   14359: # check URL part
1.409     www      14360:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      14361: 
1.431     www      14362:     unless ($url eq $thisfn) { return 0; }
1.213     www      14363: 
1.216     www      14364:     $symb=&symbclean($symb);
1.510     www      14365:     $thisurl=&deversion($thisurl);
1.439     www      14366:     $thisfn=&deversion($thisfn);
1.213     www      14367: 
                   14368:     my %bighash;
                   14369:     my $okay=0;
1.431     www      14370: 
1.620     albertel 14371:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 14372:                             &GDBM_READER(),0640)) {
1.1032    raeburn  14373:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   14374:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  14375:             if ($map =~ m{^uploaded/.+\.page$}) {
                   14376:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   14377:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   14378:             }
                   14379:         }
                   14380:         my $ids;
1.1419    raeburn  14381:         if ($map =~ m{^uploaded/.+\.page$}) {
                   14382:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  14383:         } else {
                   14384:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  14385:         }
1.1102    raeburn  14386:         unless ($ids) {
                   14387:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   14388:             $ids=$bighash{$idkey};
1.216     www      14389:         }
                   14390:         if ($ids) {
                   14391: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  14392:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  14393:                 $symb =~ s/\?.+$//;
1.1202    raeburn  14394:             }
1.800     albertel 14395: 	    foreach my $id (split(/\,/,$ids)) {
                   14396: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      14397:                if (
                   14398:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  14399:    eq $symb) {
                   14400:                    if (ref($encstate)) {
                   14401:                        $$encstate = $bighash{'encrypted_'.$id};
                   14402:                    }
1.620     albertel 14403: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  14404: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   14405:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  14406: 		       $okay=1;
1.1202    raeburn  14407:                        last;
1.582     albertel 14408: 		   }
                   14409: 	       }
1.216     www      14410: 	   }
                   14411:         }
1.213     www      14412: 	untie(%bighash);
                   14413:     }
                   14414:     return $okay;
1.31      www      14415: }
                   14416: 
1.210     www      14417: # --------------------------------------------------------------- Clean-up symb
                   14418: 
                   14419: sub symbclean {
                   14420:     my $symb=shift;
1.568     albertel 14421:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      14422: # remove version from map
                   14423:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      14424: 
1.210     www      14425: # remove version from URL
                   14426:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      14427: 
1.507     www      14428: # remove wrapper
                   14429: 
1.510     www      14430:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 14431:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      14432:     return $symb;
1.409     www      14433: }
                   14434: 
                   14435: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 14436: 
                   14437: sub encode_symb {
                   14438:     my ($map,$resid,$url)=@_;
                   14439:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   14440: }
1.409     www      14441: 
                   14442: sub decode_symb {
1.568     albertel 14443:     my $symb=shift;
                   14444:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   14445:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      14446:     return (&fixversion($map),$resid,&fixversion($url));
                   14447: }
                   14448: 
                   14449: sub fixversion {
                   14450:     my $fn=shift;
1.609     banghart 14451:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      14452:     my %bighash;
                   14453:     my $uri=&clutter($fn);
1.620     albertel 14454:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      14455: # is this cached?
1.599     albertel 14456:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      14457:     if (defined($cached)) { return $result; }
                   14458: # unfortunately not cached, or expired
1.620     albertel 14459:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      14460: 	    &GDBM_READER(),0640)) {
                   14461:  	if ($bighash{'version_'.$uri}) {
                   14462:  	    my $version=$bighash{'version_'.$uri};
1.444     www      14463:  	    unless (($version eq 'mostrecent') || 
                   14464: 		    ($version==&getversion($uri))) {
1.440     www      14465:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   14466:  	    }
                   14467:  	}
                   14468:  	untie %bighash;
1.413     www      14469:     }
1.599     albertel 14470:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      14471: }
                   14472: 
                   14473: sub deversion {
                   14474:     my $url=shift;
                   14475:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   14476:     return $url;
1.210     www      14477: }
                   14478: 
1.31      www      14479: # ------------------------------------------------------ Return symb list entry
                   14480: 
                   14481: sub symbread {
1.1424    raeburn  14482:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  14483:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  14484:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  14485:     if (defined($env{$cache_str})) {
1.1424    raeburn  14486:         unless (ref($possibles) eq 'HASH') {
                   14487:             if ($ignorecachednull) {
                   14488:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   14489:             } else {
                   14490:                 return $env{$cache_str};
                   14491:             }
1.1282    raeburn  14492:         }
                   14493:     }
1.242     www      14494: # no filename provided? try from environment
1.1265    raeburn  14495:     unless ($thisfn) {
1.620     albertel 14496:         if ($env{'request.symb'}) {
1.1427    raeburn  14497:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 14498: 	}
1.620     albertel 14499: 	$thisfn=$env{'request.filename'};
1.44      www      14500:     }
1.569     albertel 14501:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      14502: # is that filename actually a symb? Verify, clean, and return
                   14503:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 14504: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  14505: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 14506: 	}
1.242     www      14507:     }
1.44      www      14508:     $thisfn=declutter($thisfn);
1.31      www      14509:     my %hash;
1.37      www      14510:     my %bighash;
                   14511:     my $syval='';
1.620     albertel 14512:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427    raeburn  14513:         unless ($ignoresymbdb) {
1.1424    raeburn  14514:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   14515:                           &GDBM_READER(),0640)) {
1.1487    raeburn  14516: 	        $syval=$hash{$thisfn};
1.1424    raeburn  14517:                 untie(%hash);
                   14518:             }
1.1427    raeburn  14519:             if ($syval && $checkforblock) {
                   14520:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  14521:                 if (@blockers) {
                   14522:                     $syval='';
                   14523:                 }
                   14524:             }
1.37      www      14525:         }
                   14526: # ---------------------------------------------------------- There was an entry
                   14527:         if ($syval) {
1.601     albertel 14528: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 14529: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  14530: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 14531: 		    #return $env{$cache_str}='';
1.601     albertel 14532: 		#}    
                   14533: 		#$syval.=$1;
                   14534: 	    #}
1.37      www      14535:         } else {
                   14536: # ------------------------------------------------------- Was not in symb table
1.620     albertel 14537:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 14538:                             &GDBM_READER(),0640)) {
1.37      www      14539: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      14540:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      14541:               unless ($ids) { 
                   14542:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      14543:               }
                   14544:               unless ($ids) {
                   14545: # alias?
                   14546: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      14547:               }
1.37      www      14548:               if ($ids) {
                   14549: # ------------------------------------------------------------------- Has ID(s)
                   14550:                  my @possibilities=split(/\,/,$ids);
1.39      www      14551:                  if ($#possibilities==0) {
                   14552: # ----------------------------------------------- There is only one possibility
1.37      www      14553: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 14554: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   14555: 						    $resid,$thisfn);
1.1282    raeburn  14556:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  14557:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   14558:                              $possibles->{$syval} = 1;
                   14559:                          }
1.1282    raeburn  14560:                      }
                   14561:                      if ($checkforblock) {
1.1424    raeburn  14562:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  14563:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  14564:                              if (@blockers) {
                   14565:                                  $syval = '';
1.1425    raeburn  14566:                                  untie(%bighash);
                   14567:                                  return $env{$cache_str}='';
1.1424    raeburn  14568:                              }
1.1282    raeburn  14569:                          }
                   14570:                      }
                   14571:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      14572: # ------------------------------------------ There is more than one possibility
                   14573:                      my $realpossible=0;
1.800     albertel 14574:                      foreach my $id (@possibilities) {
                   14575: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  14576:                          my $canaccess;
                   14577:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   14578:                              $canaccess = 1;
                   14579:                          } else { 
                   14580:                              $canaccess = &allowed('bre',$file);
                   14581:                          }
                   14582:                          if ($canaccess) {
                   14583:          		     my ($mapid,$resid)=split(/\./,$id);
                   14584:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   14585:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   14586: 						             $resid,$thisfn);
1.1424    raeburn  14587:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  14588:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  14589:                                  if ($checkforblock) {
1.1426    raeburn  14590:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  14591:                                      if (@blockers > 0) {
                   14592:                                          $syval = '';
                   14593:                                      } else {
1.1282    raeburn  14594:                                          $syval = $poss_syval;
                   14595:                                          $realpossible++;
                   14596:                                      }
                   14597:                                  } else {
                   14598:                                      $syval = $poss_syval;
                   14599:                                      $realpossible++;
                   14600:                                  }
1.1424    raeburn  14601:                                  if ($syval) {
                   14602:                                      if (ref($possibles) eq 'HASH') {
                   14603:                                          $possibles->{$syval} = 1;
                   14604:                                      }
                   14605:                                  }
1.1282    raeburn  14606:                              }
1.39      www      14607: 			 }
1.191     harris41 14608:                      }
1.39      www      14609: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      14610:                  } else {
                   14611:                      $syval='';
1.37      www      14612:                  }
                   14613: 	      }
1.1282    raeburn  14614:               untie(%bighash);
1.481     raeburn  14615:            }
1.31      www      14616:         }
1.62      www      14617:         if ($syval) {
1.1427    raeburn  14618: 	    return $env{$cache_str}=$syval;
1.62      www      14619:         }
1.31      www      14620:     }
1.949     raeburn  14621:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 14622:     return $env{$cache_str}='';
1.31      www      14623: }
                   14624: 
                   14625: # ---------------------------------------------------------- Return random seed
                   14626: 
1.32      www      14627: sub numval {
                   14628:     my $txt=shift;
                   14629:     $txt=~tr/A-J/0-9/;
                   14630:     $txt=~tr/a-j/0-9/;
                   14631:     $txt=~tr/K-T/0-9/;
                   14632:     $txt=~tr/k-t/0-9/;
                   14633:     $txt=~tr/U-Z/0-5/;
                   14634:     $txt=~tr/u-z/0-5/;
                   14635:     $txt=~s/\D//g;
1.564     albertel 14636:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      14637:     return int($txt);
1.368     albertel 14638: }
                   14639: 
1.484     albertel 14640: sub numval2 {
                   14641:     my $txt=shift;
                   14642:     $txt=~tr/A-J/0-9/;
                   14643:     $txt=~tr/a-j/0-9/;
                   14644:     $txt=~tr/K-T/0-9/;
                   14645:     $txt=~tr/k-t/0-9/;
                   14646:     $txt=~tr/U-Z/0-5/;
                   14647:     $txt=~tr/u-z/0-5/;
                   14648:     $txt=~s/\D//g;
                   14649:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   14650:     my $total;
                   14651:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 14652:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 14653:     return int($total);
                   14654: }
                   14655: 
1.575     albertel 14656: sub numval3 {
                   14657:     use integer;
                   14658:     my $txt=shift;
                   14659:     $txt=~tr/A-J/0-9/;
                   14660:     $txt=~tr/a-j/0-9/;
                   14661:     $txt=~tr/K-T/0-9/;
                   14662:     $txt=~tr/k-t/0-9/;
                   14663:     $txt=~tr/U-Z/0-5/;
                   14664:     $txt=~tr/u-z/0-5/;
                   14665:     $txt=~s/\D//g;
                   14666:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   14667:     my $total;
                   14668:     foreach my $val (@txts) { $total+=$val; }
                   14669:     if ($_64bit) { $total=(($total<<32)>>32); }
                   14670:     return $total;
                   14671: }
                   14672: 
1.675     albertel 14673: sub digest {
                   14674:     my ($data)=@_;
                   14675:     my $digest=&Digest::MD5::md5($data);
                   14676:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   14677:     my ($e,$f);
                   14678:     {
                   14679:         use integer;
                   14680:         $e=($a+$b);
                   14681:         $f=($c+$d);
                   14682:         if ($_64bit) {
                   14683:             $e=(($e<<32)>>32);
                   14684:             $f=(($f<<32)>>32);
                   14685:         }
                   14686:     }
                   14687:     if (wantarray) {
                   14688: 	return ($e,$f);
                   14689:     } else {
                   14690: 	my $g;
                   14691: 	{
                   14692: 	    use integer;
                   14693: 	    $g=($e+$f);
                   14694: 	    if ($_64bit) {
                   14695: 		$g=(($g<<32)>>32);
                   14696: 	    }
                   14697: 	}
                   14698: 	return $g;
                   14699:     }
                   14700: }
                   14701: 
1.368     albertel 14702: sub latest_rnd_algorithm_id {
1.675     albertel 14703:     return '64bit5';
1.366     albertel 14704: }
1.32      www      14705: 
1.503     albertel 14706: sub get_rand_alg {
                   14707:     my ($courseid)=@_;
1.790     albertel 14708:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 14709:     if ($courseid) {
1.620     albertel 14710: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 14711:     }
                   14712:     return &latest_rnd_algorithm_id();
                   14713: }
                   14714: 
1.562     albertel 14715: sub validCODE {
                   14716:     my ($CODE)=@_;
                   14717:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   14718:     return 0;
                   14719: }
                   14720: 
1.491     albertel 14721: sub getCODE {
1.620     albertel 14722:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 14723:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   14724: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   14725: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 14726: 	return $Apache::lonhomework::history{'resource.CODE'};
                   14727:     }
                   14728:     return undef;
                   14729: }
1.1133    foxr     14730: #
                   14731: #  Determines the random seed for a specific context:
                   14732: #
                   14733: # parameters:
                   14734: #   symb      - in course context the symb for the seed.
                   14735: #   course_id - The course id of the form domain_coursenum.
                   14736: #   domain    - Domain for the user.
                   14737: #   course    - Course for the user.
                   14738: #   cenv      - environment of the course.
                   14739: #
                   14740: # NOTE:
                   14741: #   All parameters are picked out of the environment if missing
                   14742: #   or not defined.
                   14743: #   If a symb cannot be determined the current time is used instead.
                   14744: #
                   14745: #  For a given well defined symb, courside, domain, username,
                   14746: #  and course environment, the seed is reproducible.
                   14747: #
1.31      www      14748: sub rndseed {
1.1133    foxr     14749:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 14750:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 14751:     if (!defined($symb)) {
1.366     albertel 14752: 	unless ($symb=$wsymb) { return time; }
                   14753:     }
1.1146    foxr     14754:     if (!defined $courseid) { 
                   14755: 	$courseid=$wcourseid; 
                   14756:     }
                   14757:     if (!defined $domain) { $domain=$wdomain; }
                   14758:     if (!defined $username) { $username=$wusername }
1.1133    foxr     14759: 
                   14760:     my $which;
                   14761:     if (defined($cenv->{'rndseed'})) {
                   14762: 	$which = $cenv->{'rndseed'};
                   14763:     } else {
                   14764: 	$which =&get_rand_alg($courseid);
                   14765:     }
1.491     albertel 14766:     if (defined(&getCODE())) {
1.1133    foxr     14767: 
1.675     albertel 14768: 	if ($which eq '64bit5') {
                   14769: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   14770: 	} elsif ($which eq '64bit4') {
1.575     albertel 14771: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   14772: 	} else {
                   14773: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   14774: 	}
1.675     albertel 14775:     } elsif ($which eq '64bit5') {
                   14776: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 14777:     } elsif ($which eq '64bit4') {
                   14778: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 14779:     } elsif ($which eq '64bit3') {
                   14780: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 14781:     } elsif ($which eq '64bit2') {
                   14782: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 14783:     } elsif ($which eq '64bit') {
                   14784: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   14785:     }
                   14786:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   14787: }
                   14788: 
                   14789: sub rndseed_32bit {
                   14790:     my ($symb,$courseid,$domain,$username)=@_;
                   14791:     {
                   14792: 	use integer;
                   14793: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   14794: 	my $symbseed=numval($symb) << 22;
                   14795: 	my $namechck=unpack("%32C*",$username) << 17;
                   14796: 	my $nameseed=numval($username) << 12;
                   14797: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   14798: 	my $courseseed=unpack("%32C*",$courseid);
                   14799: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 14800: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14801: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14802: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 14803: 	return $num;
                   14804:     }
                   14805: }
                   14806: 
                   14807: sub rndseed_64bit {
                   14808:     my ($symb,$courseid,$domain,$username)=@_;
                   14809:     {
                   14810: 	use integer;
                   14811: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   14812: 	my $symbseed=numval($symb) << 10;
                   14813: 	my $namechck=unpack("%32S*",$username);
                   14814: 	
                   14815: 	my $nameseed=numval($username) << 21;
                   14816: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   14817: 	my $courseseed=unpack("%32S*",$courseid);
                   14818: 	
                   14819: 	my $num1=$symbchck+$symbseed+$namechck;
                   14820: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14821: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14822: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14823: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 14824: 	return "$num1,$num2";
1.155     albertel 14825:     }
1.366     albertel 14826: }
                   14827: 
1.443     albertel 14828: sub rndseed_64bit2 {
                   14829:     my ($symb,$courseid,$domain,$username)=@_;
                   14830:     {
                   14831: 	use integer;
                   14832: 	# strings need to be an even # of cahracters long, it it is odd the
                   14833:         # last characters gets thrown away
                   14834: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14835: 	my $symbseed=numval($symb) << 10;
                   14836: 	my $namechck=unpack("%32S*",$username.' ');
                   14837: 	
                   14838: 	my $nameseed=numval($username) << 21;
1.501     albertel 14839: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14840: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14841: 	
                   14842: 	my $num1=$symbchck+$symbseed+$namechck;
                   14843: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14844: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14845: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 14846: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 14847: 	return "$num1,$num2";
                   14848:     }
                   14849: }
                   14850: 
                   14851: sub rndseed_64bit3 {
                   14852:     my ($symb,$courseid,$domain,$username)=@_;
                   14853:     {
                   14854: 	use integer;
                   14855: 	# strings need to be an even # of cahracters long, it it is odd the
                   14856:         # last characters gets thrown away
                   14857: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14858: 	my $symbseed=numval2($symb) << 10;
                   14859: 	my $namechck=unpack("%32S*",$username.' ');
                   14860: 	
                   14861: 	my $nameseed=numval2($username) << 21;
1.443     albertel 14862: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14863: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14864: 	
                   14865: 	my $num1=$symbchck+$symbseed+$namechck;
                   14866: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14867: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14868: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 14869: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14870: 	
1.503     albertel 14871: 	return "$num1:$num2";
1.443     albertel 14872:     }
                   14873: }
                   14874: 
1.575     albertel 14875: sub rndseed_64bit4 {
                   14876:     my ($symb,$courseid,$domain,$username)=@_;
                   14877:     {
                   14878: 	use integer;
                   14879: 	# strings need to be an even # of cahracters long, it it is odd the
                   14880:         # last characters gets thrown away
                   14881: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14882: 	my $symbseed=numval3($symb) << 10;
                   14883: 	my $namechck=unpack("%32S*",$username.' ');
                   14884: 	
                   14885: 	my $nameseed=numval3($username) << 21;
                   14886: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14887: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14888: 	
                   14889: 	my $num1=$symbchck+$symbseed+$namechck;
                   14890: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14891: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14892: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 14893: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14894: 	
1.575     albertel 14895: 	return "$num1:$num2";
                   14896:     }
                   14897: }
                   14898: 
1.675     albertel 14899: sub rndseed_64bit5 {
                   14900:     my ($symb,$courseid,$domain,$username)=@_;
                   14901:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   14902:     return "$num1:$num2";
                   14903: }
                   14904: 
1.366     albertel 14905: sub rndseed_CODE_64bit {
                   14906:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 14907:     {
1.366     albertel 14908: 	use integer;
1.443     albertel 14909: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 14910: 	my $symbseed=numval2($symb);
1.491     albertel 14911: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14912: 	my $CODEseed=numval(&getCODE());
1.443     albertel 14913: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 14914: 	my $num1=$symbseed+$CODEchck;
                   14915: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14916: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14917: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 14918: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14919: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 14920: 	return "$num1:$num2";
1.366     albertel 14921:     }
                   14922: }
                   14923: 
1.575     albertel 14924: sub rndseed_CODE_64bit4 {
                   14925:     my ($symb,$courseid,$domain,$username)=@_;
                   14926:     {
                   14927: 	use integer;
                   14928: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   14929: 	my $symbseed=numval3($symb);
                   14930: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14931: 	my $CODEseed=numval3(&getCODE());
                   14932: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14933: 	my $num1=$symbseed+$CODEchck;
                   14934: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14935: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14936: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14937: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14938: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14939: 	return "$num1:$num2";
                   14940:     }
                   14941: }
                   14942: 
1.675     albertel 14943: sub rndseed_CODE_64bit5 {
                   14944:     my ($symb,$courseid,$domain,$username)=@_;
                   14945:     my $code = &getCODE();
                   14946:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14947:     return "$num1:$num2";
                   14948: }
                   14949: 
1.366     albertel 14950: sub setup_random_from_rndseed {
                   14951:     my ($rndseed)=@_;
1.503     albertel 14952:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  14953:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14954:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14955:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14956:         } else {
                   14957:             &Math::Random::random_set_seed($num1,$num2);
                   14958:         }
1.366     albertel 14959:     } else {
                   14960: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14961:     }
1.36      albertel 14962: }
                   14963: 
1.474     albertel 14964: sub latest_receipt_algorithm_id {
1.835     albertel 14965:     return 'receipt3';
1.474     albertel 14966: }
                   14967: 
1.480     www      14968: sub recunique {
                   14969:     my $fucourseid=shift;
                   14970:     my $unique;
1.835     albertel 14971:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14972: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14973: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14974:     } else {
                   14975: 	$unique=$perlvar{'lonReceipt'};
                   14976:     }
                   14977:     return unpack("%32C*",$unique);
                   14978: }
                   14979: 
                   14980: sub recprefix {
                   14981:     my $fucourseid=shift;
                   14982:     my $prefix;
1.835     albertel 14983:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14984: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14985: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14986:     } else {
                   14987: 	$prefix=$perlvar{'lonHostID'};
                   14988:     }
                   14989:     return unpack("%32C*",$prefix);
                   14990: }
                   14991: 
1.76      www      14992: sub ireceipt {
1.474     albertel 14993:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14994: 
                   14995:     my $return =&recprefix($fucourseid).'-';
                   14996: 
                   14997:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14998: 	$env{'request.state'} eq 'construct') {
                   14999: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   15000: 	return $return;
                   15001:     }
                   15002: 
1.76      www      15003:     my $cuname=unpack("%32C*",$funame);
                   15004:     my $cudom=unpack("%32C*",$fudom);
                   15005:     my $cucourseid=unpack("%32C*",$fucourseid);
                   15006:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      15007:     my $cunique=&recunique($fucourseid);
1.474     albertel 15008:     my $cpart=unpack("%32S*",$part);
1.835     albertel 15009:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   15010: 
1.790     albertel 15011: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 15012: 			       
                   15013: 	$return.= ($cunique%$cuname+
                   15014: 		   $cunique%$cudom+
                   15015: 		   $cusymb%$cuname+
                   15016: 		   $cusymb%$cudom+
                   15017: 		   $cucourseid%$cuname+
                   15018: 		   $cucourseid%$cudom+
                   15019: 		   $cpart%$cuname+
                   15020: 		   $cpart%$cudom);
                   15021:     } else {
                   15022: 	$return.= ($cunique%$cuname+
                   15023: 		   $cunique%$cudom+
                   15024: 		   $cusymb%$cuname+
                   15025: 		   $cusymb%$cudom+
                   15026: 		   $cucourseid%$cuname+
                   15027: 		   $cucourseid%$cudom);
                   15028:     }
                   15029:     return $return;
1.76      www      15030: }
                   15031: 
                   15032: sub receipt {
1.474     albertel 15033:     my ($part)=@_;
1.790     albertel 15034:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 15035:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      15036: }
1.260     ng       15037: 
1.790     albertel 15038: sub whichuser {
                   15039:     my ($passedsymb)=@_;
                   15040:     my ($symb,$courseid,$domain,$name,$publicuser);
                   15041:     if (defined($env{'form.grade_symb'})) {
                   15042: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   15043: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   15044: 	if (!$allowed &&
                   15045: 	    exists($env{'request.course.sec'}) &&
                   15046: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   15047: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   15048: 			      '/'.$env{'request.course.sec'});
                   15049: 	}
                   15050: 	if ($allowed) {
                   15051: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   15052: 	    $courseid=$tmp_courseid;
                   15053: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   15054: 	    ($name)=&get_env_multiple('form.grade_username');
                   15055: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   15056: 	}
                   15057:     }
                   15058:     if (!$passedsymb) {
                   15059: 	$symb=&symbread();
                   15060:     } else {
                   15061: 	$symb=$passedsymb;
                   15062:     }
                   15063:     $courseid=$env{'request.course.id'};
                   15064:     $domain=$env{'user.domain'};
                   15065:     $name=$env{'user.name'};
                   15066:     if ($name eq 'public' && $domain eq 'public') {
                   15067: 	if (!defined($env{'form.username'})) {
                   15068: 	    $env{'form.username'}.=time.rand(10000000);
                   15069: 	}
                   15070: 	$name.=$env{'form.username'};
                   15071:     }
                   15072:     return ($symb,$courseid,$domain,$name,$publicuser);
                   15073: 
                   15074: }
                   15075: 
1.36      albertel 15076: # ------------------------------------------------------------ Serves up a file
1.472     albertel 15077: # returns either the contents of the file or 
                   15078: # -1 if the file doesn't exist
1.481     raeburn  15079: #
                   15080: # if the target is a file that was uploaded via DOCS, 
                   15081: # a check will be made to see if a current copy exists on the local server,
                   15082: # if it does this will be served, otherwise a copy will be retrieved from
                   15083: # the home server for the course and stored in /home/httpd/html/userfiles on
                   15084: # the local server.   
1.472     albertel 15085: 
1.36      albertel 15086: sub getfile {
1.538     albertel 15087:     my ($file) = @_;
1.609     banghart 15088:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 15089:     &repcopy($file);
                   15090:     return &readfile($file);
                   15091: }
                   15092: 
                   15093: sub repcopy_userfile {
                   15094:     my ($file)=@_;
1.1142    raeburn  15095:     my $londocroot = $perlvar{'lonDocRoot'};
                   15096:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  15097:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 15098:     my ($cdom,$cnum,$filename) = 
1.811     albertel 15099: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 15100:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   15101:     if (-e "$file") {
1.828     www      15102: # we already have a local copy, check it out
1.538     albertel 15103: 	my @fileinfo = stat($file);
1.828     www      15104: 	my $rtncode;
                   15105: 	my $info;
1.538     albertel 15106: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 15107: 	if ($lwpresp ne 'ok') {
1.828     www      15108: # there is no such file anymore, even though we had a local copy
1.482     albertel 15109: 	    if ($rtncode eq '404') {
1.538     albertel 15110: 		unlink($file);
1.482     albertel 15111: 	    }
                   15112: 	    return -1;
                   15113: 	}
                   15114: 	if ($info < $fileinfo[9]) {
1.828     www      15115: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  15116: 	    return 'ok';
1.828     www      15117: 	} else {
                   15118: # the file is outdated, get rid of it
                   15119: 	    unlink($file);
1.482     albertel 15120: 	}
1.828     www      15121:     }
                   15122: # one way or the other, at this point, we don't have the file
                   15123: # construct the correct path for the file
                   15124:     my @parts = ($cdom,$cnum); 
                   15125:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   15126: 	push @parts, split(/\//,$1);
                   15127:     }
                   15128:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   15129:     foreach my $part (@parts) {
                   15130: 	$path .= '/'.$part;
                   15131: 	if (!-e $path) {
                   15132: 	    mkdir($path,0770);
1.482     albertel 15133: 	}
                   15134:     }
1.828     www      15135: # now the path exists for sure
                   15136: # get a user agent
                   15137:     my $transferfile=$file.'.in.transfer';
                   15138: # FIXME: this should flock
                   15139:     if (-e $transferfile) { return 'ok'; }
                   15140:     my $request;
                   15141:     $uri=~s/^\///;
1.980     raeburn  15142:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  15143:     my $hostname = &hostname($homeserver);
1.980     raeburn  15144:     my $protocol = $protocol{$homeserver};
                   15145:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  15146:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  15147:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      15148: # did it work?
                   15149:     if ($response->is_error()) {
                   15150: 	unlink($transferfile);
                   15151: 	&logthis("Userfile repcopy failed for $uri");
                   15152: 	return -1;
                   15153:     }
                   15154: # worked, rename the transfer file
                   15155:     rename($transferfile,$file);
1.607     raeburn  15156:     return 'ok';
1.481     raeburn  15157: }
                   15158: 
1.517     albertel 15159: sub tokenwrapper {
                   15160:     my $uri=shift;
1.980     raeburn  15161:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 15162:     $uri=~s|^/||;
1.620     albertel 15163:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 15164:     my $token=$1;
1.552     albertel 15165:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   15166:     if ($udom && $uname && $file) {
                   15167: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  15168:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  15169:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  15170:         my $hostname = &hostname($homeserver);
1.980     raeburn  15171:         my $protocol = $protocol{$homeserver};
                   15172:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  15173:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 15174:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   15175:                                '&tokenissued='.$perlvar{'lonHostID'};
                   15176:     } else {
                   15177:         return '/adm/notfound.html';
                   15178:     }
                   15179: }
                   15180: 
1.828     www      15181: # call with reqtype HEAD: get last modification time
                   15182: # call with reqtype GET: get the file contents
                   15183: # Do not call this with reqtype GET for large files! It loads everything into memory
                   15184: #
1.481     raeburn  15185: sub getuploaded {
                   15186:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   15187:     $uri=~s/^\///;
1.980     raeburn  15188:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  15189:     my $hostname = &hostname($homeserver);
1.980     raeburn  15190:     my $protocol = $protocol{$homeserver};
                   15191:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  15192:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  15193:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  15194:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  15195:     $$rtncode = $response->code;
1.482     albertel 15196:     if (! $response->is_success()) {
                   15197: 	return 'failed';
                   15198:     }      
                   15199:     if ($reqtype eq 'HEAD') {
1.486     www      15200: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 15201:     } elsif ($reqtype eq 'GET') {
                   15202: 	$$info = $response->content;
1.472     albertel 15203:     }
1.482     albertel 15204:     return 'ok';
1.36      albertel 15205: }
                   15206: 
1.481     raeburn  15207: sub readfile {
                   15208:     my $file = shift;
                   15209:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   15210:     my $fh;
1.1359    raeburn  15211:     open($fh,"<",$file);
1.481     raeburn  15212:     my $a='';
1.800     albertel 15213:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  15214:     return $a;
                   15215: }
                   15216: 
1.36      albertel 15217: sub filelocation {
1.590     banghart 15218:     my ($dir,$file) = @_;
                   15219:     my $location;
                   15220:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 15221: 
                   15222:     if ($file =~ m-^/adm/-) {
                   15223: 	$file=~s-^/adm/wrapper/-/-;
                   15224: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   15225:     }
1.882     albertel 15226: 
1.1139    www      15227:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  15228:         $location = $file;
1.609     banghart 15229:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 15230:         my ($udom,$uname,$filename)=
1.811     albertel 15231:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 15232:         my $home=&homeserver($uname,$udom);
                   15233:         my $is_me=0;
                   15234:         my @ids=&current_machine_ids();
                   15235:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   15236:         if ($is_me) {
1.1117    foxr     15237:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 15238:         } else {
                   15239:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   15240:   	      $udom.'/'.$uname.'/'.$filename;
                   15241:         }
1.882     albertel 15242:     } elsif ($file =~ m-^/adm/-) {
                   15243: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 15244:     } else {
                   15245:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      15246:         $file=~s:^/(res|priv)/:/:;
                   15247:         my $space=$1;
1.590     banghart 15248:         if ( !( $file =~ m:^/:) ) {
                   15249:             $location = $dir. '/'.$file;
                   15250:         } else {
1.1142    raeburn  15251:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 15252:         }
1.59      albertel 15253:     }
1.590     banghart 15254:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 15255:     while ($location=~m{/\.\./}) {
                   15256: 	if ($location =~ m{/[^/]+/\.\./}) {
                   15257: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   15258: 	} else {
                   15259: 	    $location=~ s{/\.\./}{/}g;
                   15260: 	}
                   15261:     } #remove dir/..
1.590     banghart 15262:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   15263:     return $location;
1.46      www      15264: }
1.36      albertel 15265: 
1.46      www      15266: sub hreflocation {
                   15267:     my ($dir,$file)=@_;
1.980     raeburn  15268:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 15269: 	$file=filelocation($dir,$file);
1.700     albertel 15270:     } elsif ($file=~m-^/adm/-) {
                   15271: 	$file=~s-^/adm/wrapper/-/-;
                   15272: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 15273:     }
                   15274:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   15275: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   15276:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  15277: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   15278: 	        {/uploaded/$1/$2/}x;
1.46      www      15279:     }
1.913     albertel 15280:     if ($file=~ m{^/userfiles/}) {
                   15281: 	$file =~ s{^/userfiles/}{/uploaded/};
                   15282:     }
1.462     albertel 15283:     return $file;
1.465     albertel 15284: }
                   15285: 
1.1139    www      15286: 
                   15287: 
                   15288: 
                   15289: 
1.465     albertel 15290: sub current_machine_domains {
1.853     albertel 15291:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   15292: }
                   15293: 
                   15294: sub machine_domains {
                   15295:     my ($hostname) = @_;
1.465     albertel 15296:     my @domains;
1.838     albertel 15297:     my %hostname = &all_hostnames();
1.465     albertel 15298:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  15299: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 15300: 	if ($hostname eq $name) {
1.844     albertel 15301: 	    push(@domains,&host_domain($id));
1.465     albertel 15302: 	}
                   15303:     }
                   15304:     return @domains;
                   15305: }
                   15306: 
                   15307: sub current_machine_ids {
1.853     albertel 15308:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   15309: }
                   15310: 
                   15311: sub machine_ids {
                   15312:     my ($hostname) = @_;
                   15313:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 15314:     my @ids;
1.888     albertel 15315:     my %name_to_host = &all_names();
1.889     albertel 15316:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   15317: 	return @{ $name_to_host{$hostname} };
                   15318:     }
                   15319:     return;
1.31      www      15320: }
                   15321: 
1.824     raeburn  15322: sub additional_machine_domains {
                   15323:     my @domains;
1.1466    raeburn  15324:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   15325:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   15326:             while (my $line = <$fh>) {
                   15327:                 chomp($line);           
                   15328:                 $line =~ s/\s//g;
                   15329:                 push(@domains,$line);
                   15330:             }
                   15331:             close($fh);
                   15332:         }
1.824     raeburn  15333:     }
                   15334:     return @domains;
                   15335: }
                   15336: 
                   15337: sub default_login_domain {
                   15338:     my $domain = $perlvar{'lonDefDomain'};
                   15339:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   15340:     foreach my $posdom (&current_machine_domains(),
                   15341:                         &additional_machine_domains()) {
                   15342:         if (lc($posdom) eq lc($testdomain)) {
                   15343:             $domain=$posdom;
                   15344:             last;
                   15345:         }
                   15346:     }
                   15347:     return $domain;
                   15348: }
                   15349: 
1.1414    raeburn  15350: sub shared_institution {
1.1439    raeburn  15351:     my ($dom,$lonhost) = @_;
                   15352:     if ($lonhost eq '') {
                   15353:         $lonhost = $perlvar{'lonHostID'};
                   15354:     }
1.1414    raeburn  15355:     my $same_intdom;
1.1439    raeburn  15356:     my $hostintdom = &internet_dom($lonhost);
1.1414    raeburn  15357:     if ($hostintdom ne '') {
                   15358:         my %iphost = &get_iphost();
                   15359:         my $primary_id = &domain($dom,'primary');
                   15360:         my $primary_ip = &get_host_ip($primary_id);
                   15361:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   15362:             foreach my $id (@{$iphost{$primary_ip}}) {
                   15363:                 my $intdom = &internet_dom($id);
                   15364:                 if ($intdom eq $hostintdom) {
                   15365:                     $same_intdom = 1;
                   15366:                     last;
                   15367:                 }
                   15368:             }
                   15369:         }
                   15370:     }
                   15371:     return $same_intdom;
                   15372: }
                   15373: 
1.1398    raeburn  15374: sub uses_sts {
                   15375:     my ($ignore_cache) = @_;
                   15376:     my $lonhost = $perlvar{'lonHostID'};
                   15377:     my $hostname = &hostname($lonhost);
                   15378:     my $sts_on;
                   15379:     if ($protocol{$lonhost} eq 'https') {
                   15380:         my $cachetime = 12*3600;
                   15381:         if (!$ignore_cache) {
                   15382:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   15383:             if (defined($cached)) {
                   15384:                 return $sts_on;
                   15385:             }
                   15386:         }
                   15387:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   15388:         my $request=new HTTP::Request('HEAD',$url);
                   15389:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   15390:         if ($response->is_success) {
                   15391:             my $has_sts = $response->header('Strict-Transport-Security');
                   15392:             if ($has_sts eq '') {
                   15393:                 $sts_on = 0;
                   15394:             } else {
                   15395:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   15396:                     my $maxage = $1;
                   15397:                     if ($maxage) {
                   15398:                         $sts_on = 1;
                   15399:                     } else {
                   15400:                         $sts_on = 0;
                   15401:                     }
                   15402:                 } else {
                   15403:                     $sts_on = 0;
                   15404:                 }
                   15405:             }
                   15406:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   15407:         }
                   15408:     }
                   15409:     return;
                   15410: }
                   15411: 
1.1449    raeburn  15412: sub waf_allssl {
                   15413:     my ($host_name) = @_;
                   15414:     my $alias = &get_proxy_alias();
                   15415:     if ($host_name eq '') {
                   15416:         $host_name = $ENV{'SERVER_NAME'};
                   15417:     }
                   15418:     if (($host_name ne '') && ($alias eq $host_name)) {
                   15419:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   15420:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   15421:         if ($defdomdefaults{'waf_sslopt'}) {
                   15422:             return $defdomdefaults{'waf_sslopt'};
                   15423:         }
                   15424:     }
                   15425:     return;
                   15426: }
                   15427: 
1.1434    raeburn  15428: sub get_requestor_ip {
                   15429:     my ($r,$nolookup,$noproxy) = @_;
                   15430:     my $from_ip;
                   15431:     if (ref($r)) {
1.1447    raeburn  15432:         if ($r->can('useragent_ip')) {
                   15433:             if ($noproxy && $r->can('client_ip')) {
                   15434:                 $from_ip = $r->client_ip();
                   15435:             } else {
                   15436:                 $from_ip = $r->useragent_ip();
                   15437:             }
                   15438:         } elsif ($r->connection->can('remote_ip')) {
                   15439:             $from_ip = $r->connection->remote_ip();
                   15440:         } else {
                   15441:             $from_ip = $r->get_remote_host($nolookup);
                   15442:         }
1.1434    raeburn  15443:     } else {
                   15444:         $from_ip = $ENV{'REMOTE_ADDR'};
                   15445:     }
                   15446:     return $from_ip if ($noproxy); 
                   15447:     # Who controls proxy settings for server
                   15448:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15449:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   15450:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437    raeburn  15451:         if ($proxyinfo->{'vpnint'}) {
                   15452:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434    raeburn  15453:                 return $from_ip;
                   15454:             }
                   15455:         }
                   15456:         if ($proxyinfo->{'trusted'}) {
                   15457:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   15458:                 my $ipheader = $proxyinfo->{'ipheader'};
                   15459:                 my ($ip,$xfor);
                   15460:                 if (ref($r)) {
                   15461:                     if ($ipheader) {
                   15462:                         $ip = $r->headers_in->{$ipheader};
                   15463:                     }
                   15464:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   15465:                 } else {
                   15466:                     if ($ipheader) {
                   15467:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   15468:                     }
                   15469:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   15470:                 }
                   15471:                 if (($ip eq '') && ($xfor ne '')) {
                   15472:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   15473:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   15474:                             $ip = $poss_ip;
1.1435    raeburn  15475:                             last;
1.1434    raeburn  15476:                         }
                   15477:                     }
                   15478:                 }
                   15479:                 if ($ip ne '') {
                   15480:                     return $ip;
                   15481:                 }
                   15482:             }
                   15483:         }
                   15484:     }
                   15485:     return $from_ip;
                   15486: }
                   15487: 
                   15488: sub get_proxy_settings {
                   15489:     my ($dom_in_use) = @_;
1.1494    raeburn  15490:     my %domdefaults = &get_domain_defaults($dom_in_use);
1.1434    raeburn  15491:     my $proxyinfo = {
                   15492:                        ipheader => $domdefaults{'waf_ipheader'},
                   15493:                        trusted  => $domdefaults{'waf_trusted'},
1.1437    raeburn  15494:                        vpnint   => $domdefaults{'waf_vpnint'},
1.1438    raeburn  15495:                        vpnext   => $domdefaults{'waf_vpnext'},
1.1449    raeburn  15496:                        sslopt   => $domdefaults{'waf_sslopt'},
1.1434    raeburn  15497:                     };
                   15498:     return $proxyinfo;
                   15499: }
                   15500: 
                   15501: sub ip_match {
                   15502:     my ($ip,$pattern_str) = @_;
                   15503:     $ip=Net::CIDR::cidrvalidate($ip);
                   15504:     if ($ip) {
                   15505:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   15506:     }
                   15507:     return;
                   15508: }
                   15509: 
                   15510: sub get_proxy_alias {
1.1450    raeburn  15511:     my ($lonid) = @_;
                   15512:     if ($lonid eq '') {
                   15513:         $lonid = $perlvar{'lonHostID'};
                   15514:     }
                   15515:     if (!defined(&hostname($lonid))) {
                   15516:         return;
                   15517:     }
                   15518:     if ($lonid ne '') {
                   15519:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434    raeburn  15520:         if ($cached) {
                   15521:             return $alias;
                   15522:         }
1.1494    raeburn  15523:         my $dom = &host_domain($lonid);
1.1434    raeburn  15524:         if ($dom ne '') {
                   15525:             my $cachetime = 60*60*24;
                   15526:             my %domconfig =
1.1494    raeburn  15527:                 &get_dom('configuration',['wafproxy'],$dom);
1.1437    raeburn  15528:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   15529:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450    raeburn  15530:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   15531:                 }
                   15532:             }
                   15533:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   15534:         }
                   15535:     }
                   15536:     return;
                   15537: }
                   15538: 
                   15539: sub use_proxy_alias {
                   15540:     my ($r,$lonid) = @_;
                   15541:     my $alias = &get_proxy_alias($lonid);
                   15542:     if ($alias) {
                   15543:         my $dom = &host_domain($lonid);
                   15544:         if ($dom ne '') {
1.1467    raeburn  15545:             my $proxyinfo = &get_proxy_settings($dom);
1.1450    raeburn  15546:             my ($vpnint,$remote_ip);
                   15547:             if (ref($proxyinfo) eq 'HASH') {
                   15548:                 $vpnint = $proxyinfo->{'vpnint'};
                   15549:                 if ($vpnint) {
                   15550:                     $remote_ip = &get_requestor_ip($r,1,1);
1.1434    raeburn  15551:                 }
                   15552:             }
1.1450    raeburn  15553:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   15554:                 return $alias;
                   15555:             }
1.1434    raeburn  15556:         }
                   15557:     }
                   15558:     return;
                   15559: }
                   15560: 
1.1474    raeburn  15561: sub alias_sso {
1.1467    raeburn  15562:     my ($lonid) = @_;
                   15563:     if ($lonid eq '') {
                   15564:         $lonid = $perlvar{'lonHostID'};
                   15565:     }
                   15566:     if (!defined(&hostname($lonid))) {
                   15567:         return;
                   15568:     }
                   15569:     if ($lonid ne '') {
                   15570:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   15571:         if ($cached) {
                   15572:             return $use_alias;
                   15573:         }
1.1494    raeburn  15574:         my $dom = &host_domain($lonid);
1.1467    raeburn  15575:         if ($dom ne '') {
                   15576:             my $cachetime = 60*60*24;
                   15577:             my %domconfig =
1.1494    raeburn  15578:                 &get_dom('configuration',['wafproxy'],$dom);
1.1467    raeburn  15579:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   15580:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   15581:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   15582:                 }
                   15583:             }
                   15584:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   15585:         }
                   15586:     }
                   15587:     return;
                   15588: }
                   15589: 
1.1465    raeburn  15590: sub get_saml_landing {
                   15591:     my ($lonid) = @_;
                   15592:     if ($lonid eq '') {
                   15593:         my $defdom = &default_login_domain();
                   15594:         my @hosts = &current_machine_ids();
                   15595:         if (@hosts > 1) {
                   15596:             foreach my $hostid (@hosts) {
                   15597:                 if (&host_domain($hostid) eq $defdom) {
                   15598:                     $lonid = $hostid;
                   15599:                     last;
                   15600:                 }
                   15601:             }
                   15602:         } else {
                   15603:             $lonid = $perlvar{'lonHostID'};
                   15604:         }
                   15605:         if ($lonid) {
1.1494    raeburn  15606:             unless (&host_domain($lonid) eq $defdom) {
1.1465    raeburn  15607:                 return;
                   15608:             }
                   15609:         } else {
                   15610:             return;
                   15611:         }
                   15612:     } elsif (!defined(&hostname($lonid))) {
                   15613:         return;
                   15614:     }
                   15615:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   15616:     if ($cached) {
                   15617:         return $landing;
                   15618:     }
1.1494    raeburn  15619:     my $dom = &host_domain($lonid);
1.1465    raeburn  15620:     if ($dom ne '') {
                   15621:         my $cachetime = 60*60*24;
                   15622:         my %domconfig =
1.1494    raeburn  15623:             &get_dom('configuration',['login'],$dom);
1.1465    raeburn  15624:         if (ref($domconfig{'login'}) eq 'HASH') {
                   15625:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   15626:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   15627:                     $landing = 1;
                   15628:                 }
                   15629:             }
                   15630:         }
                   15631:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   15632:     }
                   15633:     return;
                   15634: }
                   15635: 
1.31      www      15636: # ------------------------------------------------------------- Declutters URLs
                   15637: 
                   15638: sub declutter {
                   15639:     my $thisfn=shift;
1.569     albertel 15640:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  15641:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   15642:         $thisfn=~s{^/home/httpd/html}{};
                   15643:     }
1.31      www      15644:     $thisfn=~s/^\///;
1.697     albertel 15645:     $thisfn=~s|^adm/wrapper/||;
                   15646:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      15647:     $thisfn=~s/^res\///;
1.1172    bisitz   15648:     $thisfn=~s/^priv\///;
1.1032    raeburn  15649:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   15650:         $thisfn=~s/\?.+$//;
                   15651:     }
1.268     www      15652:     return $thisfn;
                   15653: }
                   15654: 
                   15655: # ------------------------------------------------------------- Clutter up URLs
                   15656: 
                   15657: sub clutter {
                   15658:     my $thisfn='/'.&declutter(shift);
1.887     albertel 15659:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 15660: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      15661:        $thisfn='/res'.$thisfn; 
                   15662:     }
1.1031    raeburn  15663:     if ($thisfn !~m|^/adm|) {
                   15664: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 15665: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 15666: 	} else {
                   15667: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   15668: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 15669: 	    if ($embstyle eq 'ssi'
                   15670: 		|| ($embstyle eq 'hdn')
                   15671: 		|| ($embstyle eq 'rat')
                   15672: 		|| ($embstyle eq 'prv')
                   15673: 		|| ($embstyle eq 'ign')) {
                   15674: 		#do nothing with these
                   15675: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 15676: 		|| ($embstyle eq 'emb')
                   15677: 		|| ($embstyle eq 'wrp')) {
                   15678: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 15679: 	    } elsif ($embstyle eq 'unk'
                   15680: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 15681: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 15682: 	    } else {
1.718     www      15683: #		&logthis("Got a blank emb style");
1.695     albertel 15684: 	    }
1.694     albertel 15685: 	}
1.1343    raeburn  15686:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  15687:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 15688:     }
1.31      www      15689:     return $thisfn;
1.12      www      15690: }
                   15691: 
1.787     albertel 15692: sub clutter_with_no_wrapper {
                   15693:     my $uri = &clutter(shift);
                   15694:     if ($uri =~ m-^/adm/-) {
                   15695: 	$uri =~ s-^/adm/wrapper/-/-;
                   15696: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   15697:     }
                   15698:     return $uri;
                   15699: }
                   15700: 
1.557     albertel 15701: sub freeze_escape {
                   15702:     my ($value)=@_;
                   15703:     if (ref($value)) {
                   15704: 	$value=&nfreeze($value);
                   15705: 	return '__FROZEN__'.&escape($value);
                   15706:     }
                   15707:     return &escape($value);
                   15708: }
                   15709: 
1.11      www      15710: 
1.557     albertel 15711: sub thaw_unescape {
                   15712:     my ($value)=@_;
                   15713:     if ($value =~ /^__FROZEN__/) {
                   15714: 	substr($value,0,10,undef);
                   15715: 	$value=&unescape($value);
                   15716: 	return &thaw($value);
                   15717:     }
                   15718:     return &unescape($value);
                   15719: }
                   15720: 
1.436     albertel 15721: sub correct_line_ends {
                   15722:     my ($result)=@_;
                   15723:     $$result =~s/\r\n/\n/mg;
                   15724:     $$result =~s/\r/\n/mg;
1.415     albertel 15725: }
1.1       albertel 15726: # ================================================================ Main Program
                   15727: 
1.184     www      15728: sub goodbye {
1.204     albertel 15729:    &logthis("Starting Shut down");
1.443     albertel 15730: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 15731:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 15732: #converted
1.599     albertel 15733: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 15734:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   15735: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   15736: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 15737: #1.1 only
1.870     albertel 15738: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   15739: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   15740: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   15741: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   15742:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 15743:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   15744:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      15745:    &flushcourselogs();
                   15746:    &logthis("Shutting down");
                   15747: }
                   15748: 
1.852     albertel 15749: sub get_dns {
1.1210    raeburn  15750:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 15751:     if (!$ignore_cache) {
                   15752: 	my ($content,$cached)=
1.1494    raeburn  15753: 	    &is_cached_new('dns',$url);
1.869     albertel 15754: 	if ($cached) {
1.1210    raeburn  15755: 	    &$func($content,$hashref);
1.869     albertel 15756: 	    return;
                   15757: 	}
                   15758:     }
                   15759: 
                   15760:     my %alldns;
1.1379    raeburn  15761:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   15762:         foreach my $dns (<$config>) {
                   15763: 	    next if ($dns !~ /^\^(\S*)/x);
                   15764:             my $line = $1;
                   15765:             my ($host,$protocol) = split(/:/,$line);
                   15766:             if ($protocol ne 'https') {
                   15767:                 $protocol = 'http';
                   15768:             }
                   15769: 	    $alldns{$host} = $protocol;
1.979     raeburn  15770:         }
1.1379    raeburn  15771:         close($config);
1.869     albertel 15772:     }
                   15773:     while (%alldns) {
1.1263    raeburn  15774: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456    raeburn  15775:         my ($contents,@content);
                   15776:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   15777:             my $command = (split('/',$url))[3];
                   15778:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   15779:             delete($alldns{$dns});
                   15780:             next if (($dir eq '') || ($file eq ''));
                   15781:             if (open(my $config,'<',"$dir/$file")) {
1.1457    raeburn  15782:                 @content = <$config>;
1.1456    raeburn  15783:                 close($config);
                   15784:             }
                   15785:             if ($url eq '/adm/dns/loncapaCRL') {
                   15786:                 $contents = join('',@content);
                   15787:             }
                   15788:         } else {
                   15789: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   15790:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
                   15791:             delete($alldns{$dns});
                   15792: 	    next if ($response->is_error());
                   15793:             if ($url eq '/adm/dns/loncapaCRL') {
                   15794:                 $contents = $response->content;
                   15795:             } else {
                   15796:                 @content = split("\n",$response->content);
                   15797:             }
                   15798:         }
1.1379    raeburn  15799:         if ($url eq '/adm/dns/loncapaCRL') {
1.1456    raeburn  15800:             return &$func($contents);
1.1379    raeburn  15801:         } else {
                   15802: 	    unless ($nocache) {
                   15803: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   15804: 	    }
                   15805: 	    &$func(\@content,$hashref);
                   15806:             return;
                   15807:         }
                   15808:     }
                   15809:     my $which = (split('/',$url,4))[3];
                   15810:     if ($which eq 'loncapaCRL') {
                   15811:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   15812:         if (-e $diskfile) {
                   15813:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   15814:         } else {
                   15815:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   15816:         }
                   15817:     } else {
                   15818:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   15819:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   15820:             my @content = <$config>;
                   15821:             close($config);
                   15822:             &$func(\@content,$hashref);
                   15823:         }
1.852     albertel 15824:     }
1.1210    raeburn  15825:     return;
                   15826: }
                   15827: 
                   15828: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  15829: sub parse_dns_checksums_tab {
1.1210    raeburn  15830:     my ($lines,$hashref) = @_;
1.1264    raeburn  15831:     my $lonhost = $perlvar{'lonHostID'};
1.1494    raeburn  15832:     my $machine_dom = &host_domain($lonhost);
1.1210    raeburn  15833:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  15834:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   15835:     my $webconfdir = '/etc/httpd/conf';
                   15836:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   15837:         $webconfdir = '/etc/apache2';
                   15838:     } elsif ($distro =~ /^sles(\d+)$/) {
                   15839:         if ($1 >= 10) {
                   15840:             $webconfdir = '/etc/apache2';
                   15841:         }
                   15842:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   15843:         if ($1 >= 10.0) {
                   15844:             $webconfdir = '/etc/apache2';
                   15845:         }
                   15846:     }
1.1210    raeburn  15847:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15848:     my (%chksum,%revnum);
                   15849:     if (ref($lines) eq 'ARRAY') {
                   15850:         chomp(@{$lines});
1.1238    raeburn  15851:         my $version = shift(@{$lines});
                   15852:         if ($version eq $release) {  
1.1210    raeburn  15853:             foreach my $line (@{$lines}) {
1.1238    raeburn  15854:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  15855:                 if ($file =~ m{^/etc/httpd/conf}) {
                   15856:                     if ($webconfdir eq '/etc/apache2') {
                   15857:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   15858:                     }
                   15859:                 }
1.1238    raeburn  15860:                 $chksum{$file} = $shasum;
                   15861:                 $revnum{$file} = $version;
1.1210    raeburn  15862:             }
                   15863:             if (ref($hashref) eq 'HASH') {
                   15864:                 %{$hashref} = (
                   15865:                                 sums     => \%chksum,
                   15866:                                 versions => \%revnum,
                   15867:                               );
                   15868:             }
                   15869:         }
                   15870:     }
1.869     albertel 15871:     return;
1.852     albertel 15872: }
1.1210    raeburn  15873: 
                   15874: sub fetch_dns_checksums {
1.1238    raeburn  15875:     my %checksums;
1.1494    raeburn  15876:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
1.1260    raeburn  15877:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  15878:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15879:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  15880:              \%checksums);
1.1210    raeburn  15881:     return \%checksums;
                   15882: }
                   15883: 
1.1379    raeburn  15884: sub fetch_crl_pemfile {
                   15885:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   15886: }
                   15887: 
                   15888: sub save_crl_pem {
1.1456    raeburn  15889:     my ($content) = @_;
1.1380    raeburn  15890:     my ($msg,$hadchanges);
1.1456    raeburn  15891:     if ($content ne '') {
1.1379    raeburn  15892:         my $now = time;
                   15893:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   15894:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   15895:         if (open(my $fh,'>',"$tmpcrl")) {
1.1456    raeburn  15896:             print $fh $content;
1.1379    raeburn  15897:             close($fh);
                   15898:             if (-e $lonca) {
                   15899:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   15900:                     my $check = <PIPE>;
                   15901:                     close(PIPE);
                   15902:                     chomp($check);
                   15903:                     if ($check eq 'verify OK') {
                   15904:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  15905:                         my $backup;
1.1379    raeburn  15906:                         if (-e $dest) {
1.1380    raeburn  15907:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   15908:                                 $backup = 'ok';
                   15909:                             }
1.1379    raeburn  15910:                         }
                   15911:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   15912:                             $msg = 'ok';
1.1380    raeburn  15913:                             if ($backup) {
                   15914:                                 my (%oldnums,%newnums);
                   15915:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   15916:                                     while (<PIPE>) {
                   15917:                                         $oldnums{(split(/:/))[1]} = 1;
                   15918:                                     }
                   15919:                                     close(PIPE);
                   15920:                                 }
                   15921:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   15922:                                     while(<PIPE>) {
                   15923:                                         $newnums{(split(/:/))[1]} = 1;
                   15924:                                     }
                   15925:                                     close(PIPE);
                   15926:                                 }
                   15927:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   15928:                                     unless (exists($oldnums{$key})) {
                   15929:                                         $hadchanges = 1;
                   15930:                                         last;
                   15931:                                     }
                   15932:                                 }
                   15933:                                 unless ($hadchanges) {
                   15934:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   15935:                                         unless (exists($newnums{$key})) {
                   15936:                                             $hadchanges = 1;
                   15937:                                             last;
                   15938:                                         }
                   15939:                                     }
                   15940:                                 }
                   15941:                             }
1.1379    raeburn  15942:                         }
                   15943:                     } else {
                   15944:                         unlink($tmpcrl);
                   15945:                     }
                   15946:                 } else {
                   15947:                     unlink($tmpcrl);
                   15948:                 }
                   15949:             } else {
                   15950:                 unlink($tmpcrl);
                   15951:             }
                   15952:         }
                   15953:     }
1.1380    raeburn  15954:     return ($msg,$hadchanges);
1.1379    raeburn  15955: }
                   15956: 
1.1456    raeburn  15957: sub parse_getdns_url {
                   15958:     my ($command,$url) = @_;
                   15959:     my $dir = $perlvar{'lonTabDir'};
                   15960:     my $file;
                   15961:     if ($command eq 'hosts') {
                   15962:         $file = 'dns_hosts.tab';
                   15963:     } elsif ($command eq 'domain') {
                   15964:         $file = 'dns_domain.tab';
                   15965:     } elsif ($command eq 'checksums') {
                   15966:         my $version = (split('/',$url))[4];
                   15967:         $file = "dns_checksums/$version.tab",
                   15968:     } elsif ($command eq 'loncapaCRL') {
                   15969:         $dir = $perlvar{'lonCertificateDirectory'};
                   15970:         $file = $perlvar{'lonnetCertRevocationList'};
                   15971:     }
                   15972:     return ($dir,$file);
                   15973: }
                   15974: 
1.327     albertel 15975: # ------------------------------------------------------------ Read domain file
                   15976: {
1.852     albertel 15977:     my $loaded;
1.846     albertel 15978:     my %domain;
                   15979: 
1.852     albertel 15980:     sub parse_domain_tab {
                   15981: 	my ($lines) = @_;
                   15982: 	foreach my $line (@$lines) {
                   15983: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      15984: 
1.846     albertel 15985: 	    chomp($line);
1.852     albertel 15986: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 15987: 	    my %this_domain;
                   15988: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   15989: 			       'lang_def', 'city', 'longi', 'lati',
                   15990: 			       'primary') {
                   15991: 		$this_domain{$field} = shift(@elements);
                   15992: 	    }
                   15993: 	    $domain{$name} = \%this_domain;
1.852     albertel 15994: 	}
                   15995:     }
1.864     albertel 15996: 
                   15997:     sub reset_domain_info {
                   15998: 	undef($loaded);
                   15999: 	undef(%domain);
                   16000:     }
                   16001: 
1.852     albertel 16002:     sub load_domain_tab {
1.1293    raeburn  16003: 	my ($ignore_cache,$nocache) = @_;
                   16004: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 16005: 	my $fh;
1.1359    raeburn  16006: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 16007: 	    my @lines = <$fh>;
                   16008: 	    &parse_domain_tab(\@lines);
1.448     albertel 16009: 	}
1.852     albertel 16010: 	close($fh);
                   16011: 	$loaded = 1;
1.327     albertel 16012:     }
1.846     albertel 16013: 
                   16014:     sub domain {
1.852     albertel 16015: 	&load_domain_tab() if (!$loaded);
                   16016: 
1.846     albertel 16017: 	my ($name,$what) = @_;
                   16018: 	return if ( !exists($domain{$name}) );
                   16019: 
                   16020: 	if (!$what) {
                   16021: 	    return $domain{$name}{'description'};
                   16022: 	}
                   16023: 	return $domain{$name}{$what};
                   16024:     }
1.974     raeburn  16025: 
                   16026:     sub domain_info {
                   16027:         &load_domain_tab() if (!$loaded);
                   16028:         return %domain;
                   16029:     }
                   16030: 
1.327     albertel 16031: }
                   16032: 
                   16033: 
1.1       albertel 16034: # ------------------------------------------------------------- Read hosts file
                   16035: {
1.838     albertel 16036:     my %hostname;
1.844     albertel 16037:     my %hostdom;
1.845     albertel 16038:     my %libserv;
1.852     albertel 16039:     my $loaded;
1.888     albertel 16040:     my %name_to_host;
1.1074    raeburn  16041:     my %internetdom;
1.1107    raeburn  16042:     my %LC_dns_serv;
1.852     albertel 16043: 
                   16044:     sub parse_hosts_tab {
                   16045: 	my ($file) = @_;
                   16046: 	foreach my $configline (@$file) {
                   16047: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  16048:             chomp($configline);
                   16049: 	    if ($configline =~ /^\^/) {
                   16050:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   16051:                     $LC_dns_serv{$1} = 1;
                   16052:                 }
                   16053:                 next;
                   16054:             }
1.1074    raeburn  16055: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 16056: 	    $name=~s/\s//g;
                   16057: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  16058:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   16059:                     my $curr = $hostname{$id};
                   16060:                     my $skip;
                   16061:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   16062:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   16063:                             $skip = 1;
                   16064:                         } else {
                   16065:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   16066:                         }
                   16067:                     }
                   16068:                     unless ($skip) {
                   16069:                         push(@{$name_to_host{$name}},$id);
                   16070:                     }
                   16071:                 } else {
                   16072:                     push(@{$name_to_host{$name}},$id);
                   16073:                 }
1.852     albertel 16074: 		$hostname{$id}=$name;
                   16075: 		$hostdom{$id}=$domain;
                   16076: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  16077:                 if (defined($protocol)) {
                   16078:                     if ($protocol eq 'https') {
                   16079:                         $protocol{$id} = $protocol;
                   16080:                     } else {
                   16081:                         $protocol{$id} = 'http'; 
                   16082:                     }
1.968     raeburn  16083:                 } else {
1.969     raeburn  16084:                     $protocol{$id} = 'http';
1.968     raeburn  16085:                 }
1.1074    raeburn  16086:                 if (defined($intdom)) {
                   16087:                     $internetdom{$id} = $intdom;
                   16088:                 }
1.852     albertel 16089: 	    }
                   16090: 	}
                   16091:     }
1.864     albertel 16092:     
                   16093:     sub reset_hosts_info {
1.897     albertel 16094: 	&purge_remembered();
1.864     albertel 16095: 	&reset_domain_info();
                   16096: 	&reset_hosts_ip_info();
1.1339    raeburn  16097:         undef(%internetdom);
1.892     albertel 16098: 	undef(%name_to_host);
1.864     albertel 16099: 	undef(%hostname);
                   16100: 	undef(%hostdom);
                   16101: 	undef(%libserv);
                   16102: 	undef($loaded);
                   16103:     }
1.1       albertel 16104: 
1.852     albertel 16105:     sub load_hosts_tab {
1.1293    raeburn  16106: 	my ($ignore_cache,$nocache) = @_;
                   16107: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  16108: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 16109: 	my @config = <$config>;
                   16110: 	&parse_hosts_tab(\@config);
                   16111: 	close($config);
                   16112: 	$loaded=1;
1.1       albertel 16113:     }
1.852     albertel 16114: 
1.838     albertel 16115:     sub hostname {
1.852     albertel 16116: 	&load_hosts_tab() if (!$loaded);
                   16117: 
1.838     albertel 16118: 	my ($lonid) = @_;
                   16119: 	return $hostname{$lonid};
                   16120:     }
1.845     albertel 16121: 
1.838     albertel 16122:     sub all_hostnames {
1.852     albertel 16123: 	&load_hosts_tab() if (!$loaded);
                   16124: 
1.838     albertel 16125: 	return %hostname;
                   16126:     }
1.845     albertel 16127: 
1.888     albertel 16128:     sub all_names {
1.1293    raeburn  16129:         my ($ignore_cache,$nocache) = @_;
                   16130: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 16131: 
                   16132: 	return %name_to_host;
                   16133:     }
                   16134: 
1.974     raeburn  16135:     sub all_host_domain {
                   16136:         &load_hosts_tab() if (!$loaded);
                   16137:         return %hostdom;
                   16138:     }
                   16139: 
1.1339    raeburn  16140:     sub all_host_intdom {
                   16141:         &load_hosts_tab() if (!$loaded);
                   16142:         return %internetdom;
                   16143:     }
                   16144: 
1.845     albertel 16145:     sub is_library {
1.852     albertel 16146: 	&load_hosts_tab() if (!$loaded);
                   16147: 
1.845     albertel 16148: 	return exists($libserv{$_[0]});
                   16149:     }
                   16150: 
                   16151:     sub all_library {
1.852     albertel 16152: 	&load_hosts_tab() if (!$loaded);
                   16153: 
1.845     albertel 16154: 	return %libserv;
                   16155:     }
                   16156: 
1.1062    droeschl 16157:     sub unique_library {
                   16158: 	#2x reverse removes all hostnames that appear more than once
                   16159:         my %unique = reverse &all_library();
                   16160:         return reverse %unique;
                   16161:     }
                   16162: 
1.841     albertel 16163:     sub get_servers {
1.852     albertel 16164: 	&load_hosts_tab() if (!$loaded);
                   16165: 
1.841     albertel 16166: 	my ($domain,$type) = @_;
                   16167: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   16168: 	                                          : %hostname;
                   16169: 	my %result;
1.842     albertel 16170: 	if (ref($domain) eq 'ARRAY') {
                   16171: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 16172: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 16173: 		    $result{$host} = $hostname;
                   16174: 		}
                   16175: 	    }
                   16176: 	} else {
                   16177: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   16178: 		if ($hostdom{$host} eq $domain) {
                   16179: 		    $result{$host} = $hostname;
                   16180: 		}
1.841     albertel 16181: 	    }
                   16182: 	}
                   16183: 	return %result;
                   16184:     }
1.845     albertel 16185: 
1.1062    droeschl 16186:     sub get_unique_servers {
                   16187:         my %unique = reverse &get_servers(@_);
                   16188: 	return reverse %unique;
                   16189:     }
                   16190: 
1.844     albertel 16191:     sub host_domain {
1.852     albertel 16192: 	&load_hosts_tab() if (!$loaded);
                   16193: 
1.844     albertel 16194: 	my ($lonid) = @_;
                   16195: 	return $hostdom{$lonid};
                   16196:     }
                   16197: 
1.841     albertel 16198:     sub all_domains {
1.852     albertel 16199: 	&load_hosts_tab() if (!$loaded);
                   16200: 
1.841     albertel 16201: 	my %seen;
                   16202: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   16203: 	return @uniq;
                   16204:     }
1.1074    raeburn  16205: 
                   16206:     sub internet_dom {
                   16207:         &load_hosts_tab() if (!$loaded);
                   16208: 
                   16209:         my ($lonid) = @_;
                   16210:         return $internetdom{$lonid};
                   16211:     }
1.1107    raeburn  16212: 
                   16213:     sub is_LC_dns {
                   16214:         &load_hosts_tab() if (!$loaded);
                   16215: 
                   16216:         my ($hostname) = @_;
                   16217:         return exists($LC_dns_serv{$hostname});
                   16218:     }
                   16219: 
1.1       albertel 16220: }
                   16221: 
1.847     albertel 16222: { 
                   16223:     my %iphost;
1.856     albertel 16224:     my %name_to_ip;
                   16225:     my %lonid_to_ip;
1.869     albertel 16226: 
1.847     albertel 16227:     sub get_hosts_from_ip {
                   16228: 	my ($ip) = @_;
                   16229: 	my %iphosts = &get_iphost();
                   16230: 	if (ref($iphosts{$ip})) {
                   16231: 	    return @{$iphosts{$ip}};
                   16232: 	}
                   16233: 	return;
1.839     albertel 16234:     }
1.864     albertel 16235:     
                   16236:     sub reset_hosts_ip_info {
                   16237: 	undef(%iphost);
                   16238: 	undef(%name_to_ip);
                   16239: 	undef(%lonid_to_ip);
                   16240:     }
1.856     albertel 16241: 
                   16242:     sub get_host_ip {
                   16243: 	my ($lonid) = @_;
                   16244: 	if (exists($lonid_to_ip{$lonid})) {
                   16245: 	    return $lonid_to_ip{$lonid};
                   16246: 	}
                   16247: 	my $name=&hostname($lonid);
                   16248:    	my $ip = gethostbyname($name);
                   16249: 	return if (!$ip || length($ip) ne 4);
                   16250: 	$ip=inet_ntoa($ip);
                   16251: 	$name_to_ip{$name}   = $ip;
                   16252: 	$lonid_to_ip{$lonid} = $ip;
                   16253: 	return $ip;
                   16254:     }
1.847     albertel 16255:     
                   16256:     sub get_iphost {
1.1293    raeburn  16257: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 16258: 
1.869     albertel 16259: 	if (!$ignore_cache) {
                   16260: 	    if (%iphost) {
                   16261: 		return %iphost;
                   16262: 	    }
                   16263: 	    my ($ip_info,$cached)=
1.1494    raeburn  16264: 		&is_cached_new('iphost','iphost');
1.869     albertel 16265: 	    if ($cached) {
                   16266: 		%iphost      = %{$ip_info->[0]};
                   16267: 		%name_to_ip  = %{$ip_info->[1]};
                   16268: 		%lonid_to_ip = %{$ip_info->[2]};
                   16269: 		return %iphost;
                   16270: 	    }
                   16271: 	}
1.894     albertel 16272: 
                   16273: 	# get yesterday's info for fallback
                   16274: 	my %old_name_to_ip;
                   16275: 	my ($ip_info,$cached)=
1.1495    raeburn  16276: 	    &is_cached_new('iphost','iphost');
1.894     albertel 16277: 	if ($cached) {
                   16278: 	    %old_name_to_ip = %{$ip_info->[1]};
                   16279: 	}
                   16280: 
1.1293    raeburn  16281: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 16282: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 16283: 	    my $ip;
                   16284: 	    if (!exists($name_to_ip{$name})) {
                   16285: 		$ip = gethostbyname($name);
                   16286: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 16287: 		    if (defined($old_name_to_ip{$name})) {
                   16288: 			$ip = $old_name_to_ip{$name};
                   16289: 			&logthis("Can't find $name defaulting to old $ip");
                   16290: 		    } else {
                   16291: 			&logthis("Name $name no IP found");
                   16292: 			next;
                   16293: 		    }
                   16294: 		} else {
                   16295: 		    $ip=inet_ntoa($ip);
1.847     albertel 16296: 		}
                   16297: 		$name_to_ip{$name} = $ip;
                   16298: 	    } else {
                   16299: 		$ip = $name_to_ip{$name};
1.653     albertel 16300: 	    }
1.888     albertel 16301: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   16302: 		$lonid_to_ip{$id} = $ip;
                   16303: 	    }
                   16304: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 16305: 	}
1.1293    raeburn  16306:         unless ($nocache) {
                   16307: 	    &do_cache_new('iphost','iphost',
                   16308: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   16309: 		          48*60*60);
                   16310:         }
1.869     albertel 16311: 
1.847     albertel 16312: 	return %iphost;
1.598     albertel 16313:     }
                   16314: 
1.992     raeburn  16315:     #
                   16316:     #  Given a DNS returns the loncapa host name for that DNS 
                   16317:     # 
                   16318:     sub host_from_dns {
                   16319:         my ($dns) = @_;
                   16320:         my @hosts;
                   16321:         my $ip;
                   16322: 
1.993     raeburn  16323:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  16324:             $ip = $name_to_ip{$dns};
                   16325:         }
                   16326:         if (!$ip) {
                   16327:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   16328:             if (length($ip) == 4) { 
                   16329: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   16330:             }
                   16331:         }
                   16332:         if ($ip) {
                   16333: 	    @hosts = get_hosts_from_ip($ip);
                   16334: 	    return $hosts[0];
                   16335:         }
                   16336:         return undef;
1.986     foxr     16337:     }
1.992     raeburn  16338: 
1.1074    raeburn  16339:     sub get_internet_names {
                   16340:         my ($lonid) = @_;
                   16341:         return if ($lonid eq '');
                   16342:         my ($idnref,$cached)=
1.1494    raeburn  16343:             &is_cached_new('internetnames',$lonid);
1.1074    raeburn  16344:         if ($cached) {
                   16345:             return $idnref;
                   16346:         }
                   16347:         my $ip = &get_host_ip($lonid);
                   16348:         my @hosts = &get_hosts_from_ip($ip);
                   16349:         my %iphost = &get_iphost();
                   16350:         my (@idns,%seen);
                   16351:         foreach my $id (@hosts) {
                   16352:             my $dom = &host_domain($id);
                   16353:             my $prim_id = &domain($dom,'primary');
                   16354:             my $prim_ip = &get_host_ip($prim_id);
                   16355:             next if ($seen{$prim_ip});
                   16356:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   16357:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   16358:                     my $intdom = &internet_dom($id);
                   16359:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   16360:                         push(@idns,$intdom);
                   16361:                     }
                   16362:                 }
                   16363:             }
                   16364:             $seen{$prim_ip} = 1;
                   16365:         }
1.1219    raeburn  16366:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  16367:     }
                   16368: 
1.986     foxr     16369: }
                   16370: 
1.1079    raeburn  16371: sub all_loncaparevs {
1.1249    raeburn  16372:     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  16373: }
                   16374: 
1.1227    raeburn  16375: # ---------------------------------------------------------- Read loncaparev table
                   16376: {
                   16377:     sub load_loncaparevs { 
                   16378:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  16379:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  16380:                 while (my $configline=<$config>) {
                   16381:                     chomp($configline);
                   16382:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   16383:                     $loncaparevs{$hostid}=$loncaparev;
                   16384:                 }
                   16385:                 close($config);
                   16386:             }
                   16387:         }
                   16388:     }
                   16389: }
                   16390: 
                   16391: # ---------------------------------------------------------- Read serverhostID table
                   16392: {
                   16393:     sub load_serverhomeIDs {
                   16394:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  16395:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  16396:                 while (my $configline=<$config>) {
                   16397:                     chomp($configline);
                   16398:                     my ($name,$id)=split(/:/,$configline);
                   16399:                     $serverhomeIDs{$name}=$id;
                   16400:                 }
                   16401:                 close($config);
                   16402:             }
                   16403:         }
                   16404:     }
                   16405: }
                   16406: 
                   16407: 
1.862     albertel 16408: BEGIN {
                   16409: 
                   16410: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   16411:     unless ($readit) {
                   16412: {
                   16413:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   16414:     %perlvar = (%perlvar,%{$configvars});
                   16415: }
                   16416: 
                   16417: 
1.1       albertel 16418: # ------------------------------------------------------ Read spare server file
                   16419: {
1.1359    raeburn  16420:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 16421: 
                   16422:     while (my $configline=<$config>) {
                   16423:        chomp($configline);
1.284     matthew  16424:        if ($configline) {
1.784     albertel 16425: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 16426: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 16427: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 16428:        }
                   16429:     }
1.448     albertel 16430:     close($config);
1.1       albertel 16431: }
1.11      www      16432: # ------------------------------------------------------------ Read permissions
                   16433: {
1.1359    raeburn  16434:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      16435: 
                   16436:     while (my $configline=<$config>) {
1.448     albertel 16437: 	chomp($configline);
                   16438: 	if ($configline) {
                   16439: 	    my ($role,$perm)=split(/ /,$configline);
                   16440: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   16441: 	}
1.11      www      16442:     }
1.448     albertel 16443:     close($config);
1.11      www      16444: }
                   16445: 
                   16446: # -------------------------------------------- Read plain texts for permissions
                   16447: {
1.1359    raeburn  16448:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      16449: 
                   16450:     while (my $configline=<$config>) {
1.448     albertel 16451: 	chomp($configline);
                   16452: 	if ($configline) {
1.742     raeburn  16453: 	    my ($short,@plain)=split(/:/,$configline);
                   16454:             %{$prp{$short}} = ();
                   16455: 	    if (@plain > 0) {
                   16456:                 $prp{$short}{'std'} = $plain[0];
                   16457:                 for (my $i=1; $i<@plain; $i++) {
                   16458:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   16459:                 }
                   16460:             }
1.448     albertel 16461: 	}
1.135     www      16462:     }
1.448     albertel 16463:     close($config);
1.135     www      16464: }
                   16465: 
                   16466: # ---------------------------------------------------------- Read package table
                   16467: {
1.1359    raeburn  16468:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      16469: 
                   16470:     while (my $configline=<$config>) {
1.483     albertel 16471: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 16472: 	chomp($configline);
                   16473: 	my ($short,$plain)=split(/:/,$configline);
                   16474: 	my ($pack,$name)=split(/\&/,$short);
                   16475: 	if ($plain ne '') {
                   16476: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   16477: 	    $packagetab{$short}=$plain; 
                   16478: 	}
1.11      www      16479:     }
1.448     albertel 16480:     close($config);
1.329     matthew  16481: }
                   16482: 
1.1073    raeburn  16483: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  16484: 
                   16485: &load_loncaparevs();
1.1073    raeburn  16486: 
1.1074    raeburn  16487: # ---------------------------------------------------------- Read serverhostID table
                   16488: 
1.1227    raeburn  16489: &load_serverhomeIDs();
                   16490: 
                   16491: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  16492: {
                   16493:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   16494:     if (-e $file) {
                   16495:         my $parser = HTML::LCParser->new($file);
                   16496:         while (my $token = $parser->get_token()) {
                   16497:             if ($token->[0] eq 'S') {
                   16498:                 my $item = $token->[1];
                   16499:                 my $name = $token->[2]{'name'};
                   16500:                 my $value = $token->[2]{'value'};
1.1285    raeburn  16501:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  16502:                 my $namematch = $token->[2]{'namematch'};
                   16503:                 if ($item eq 'parameter') {
                   16504:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   16505:                         my $release = $parser->get_text();
                   16506:                         $release =~ s/(^\s*|\s*$ )//gx;
                   16507:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   16508:                     }
                   16509:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  16510:                     my $release = $parser->get_text();
                   16511:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  16512:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  16513:                 }
                   16514:             }
                   16515:         }
                   16516:     }
1.1073    raeburn  16517: }
                   16518: 
1.1138    raeburn  16519: # ---------------------------------------------------------- Read managers table
                   16520: {
                   16521:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  16522:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  16523:             while (my $configline=<$config>) {
                   16524:                 chomp($configline);
                   16525:                 next if ($configline =~ /^\#/);
                   16526:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   16527:                     $managerstab{$configline} = 1;
                   16528:                 }
                   16529:             }
                   16530:             close($config);
                   16531:         }
                   16532:     }
                   16533: }
                   16534: 
1.329     matthew  16535: # ------------- set up temporary directory
                   16536: {
1.1117    foxr     16537:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  16538: 
1.11      www      16539: }
                   16540: 
1.1405    raeburn  16541: # ------------- set default texengine (domain default overrides this)
                   16542: {
                   16543:     $deftex = LONCAPA::texengine();
                   16544: }
                   16545: 
1.1416    raeburn  16546: # ------------- set default minimum length for passwords for internal auth users
                   16547: {
                   16548:     $passwdmin = LONCAPA::passwd_min();
                   16549: }
                   16550: 
1.794     albertel 16551: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   16552: 				'compress_threshold'=> 20_000,
                   16553:  			        });
1.185     www      16554: 
1.281     www      16555: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      16556: $dumpcount=0;
1.958     www      16557: $locknum=0;
1.22      www      16558: 
1.163     harris41 16559: &logtouch();
1.672     albertel 16560: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      16561: $readit=1;
1.564     albertel 16562:     {
                   16563: 	use integer;
                   16564: 	my $test=(2**32)+1;
1.568     albertel 16565: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 16566: 	&logthis(" Detected 64bit platform ($_64bit)");
                   16567:     }
1.195     www      16568: }
1.1       albertel 16569: }
1.179     www      16570: 
1.1       albertel 16571: 1;
1.191     harris41 16572: __END__
                   16573: 
1.243     albertel 16574: =pod
                   16575: 
1.191     harris41 16576: =head1 NAME
                   16577: 
1.243     albertel 16578: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 16579: 
                   16580: =head1 SYNOPSIS
                   16581: 
1.243     albertel 16582: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 16583: 
                   16584:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   16585: 
1.243     albertel 16586: Common parameters:
                   16587: 
                   16588: =over 4
                   16589: 
                   16590: =item *
                   16591: 
                   16592: $uname : an internal username (if $cname expecting a course Id specifically)
                   16593: 
                   16594: =item *
                   16595: 
                   16596: $udom : a domain (if $cdom expecting a course's domain specifically)
                   16597: 
                   16598: =item *
                   16599: 
                   16600: $symb : a resource instance identifier
                   16601: 
                   16602: =item *
                   16603: 
                   16604: $namespace : the name of a .db file that contains the data needed or
                   16605: being set.
                   16606: 
                   16607: =back
                   16608: 
1.394     bowersj2 16609: =head1 OVERVIEW
1.191     harris41 16610: 
1.394     bowersj2 16611: lonnet provides subroutines which interact with the
                   16612: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   16613: about classes, users, and resources.
1.243     albertel 16614: 
                   16615: For many of these objects you can also use this to store data about
                   16616: them or modify them in various ways.
1.191     harris41 16617: 
1.394     bowersj2 16618: =head2 Symbs
1.191     harris41 16619: 
1.394     bowersj2 16620: To identify a specific instance of a resource, LON-CAPA uses symbols
                   16621: or "symbs"X<symb>. These identifiers are built from the URL of the
                   16622: map, the resource number of the resource in the map, and the URL of
                   16623: the resource itself. The latter is somewhat redundant, but might help
                   16624: if maps change.
                   16625: 
                   16626: An example is
                   16627: 
                   16628:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   16629: 
                   16630: The respective map entry is
                   16631: 
                   16632:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   16633:   title="Problem 2">
                   16634:  </resource>
                   16635: 
                   16636: Symbs are used by the random number generator, as well as to store and
                   16637: restore data specific to a certain instance of for example a problem.
                   16638: 
                   16639: =head2 Storing And Retrieving Data
                   16640: 
                   16641: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   16642: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   16643: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   16644: is is the non-critical message twin of cstore. These functions are for
                   16645: handlers to store a perl hash to a user's permanent data space in an
                   16646: easy manner, and to retrieve it again on another call. It is expected
                   16647: that a handler would use this once at the beginning to retrieve data,
                   16648: and then again once at the end to send only the new data back.
                   16649: 
                   16650: The data is stored in the user's data directory on the user's
                   16651: homeserver under the ID of the course.
                   16652: 
                   16653: The hash that is returned by restore will have all of the previous
                   16654: value for all of the elements of the hash.
                   16655: 
                   16656: Example:
                   16657: 
                   16658:  #creating a hash
                   16659:  my %hash;
                   16660:  $hash{'foo'}='bar';
                   16661: 
                   16662:  #storing it
                   16663:  &Apache::lonnet::cstore(\%hash);
                   16664: 
                   16665:  #changing a value
                   16666:  $hash{'foo'}='notbar';
                   16667: 
                   16668:  #adding a new value
                   16669:  $hash{'bar'}='foo';
                   16670:  &Apache::lonnet::cstore(\%hash);
                   16671: 
                   16672:  #retrieving the hash
                   16673:  my %history=&Apache::lonnet::restore();
                   16674: 
                   16675:  #print the hash
                   16676:  foreach my $key (sort(keys(%history))) {
                   16677:    print("\%history{$key} = $history{$key}");
                   16678:  }
                   16679: 
                   16680: Will print out:
1.191     harris41 16681: 
1.394     bowersj2 16682:  %history{1:foo} = bar
                   16683:  %history{1:keys} = foo:timestamp
                   16684:  %history{1:timestamp} = 990455579
                   16685:  %history{2:bar} = foo
                   16686:  %history{2:foo} = notbar
                   16687:  %history{2:keys} = foo:bar:timestamp
                   16688:  %history{2:timestamp} = 990455580
                   16689:  %history{bar} = foo
                   16690:  %history{foo} = notbar
                   16691:  %history{timestamp} = 990455580
                   16692:  %history{version} = 2
                   16693: 
                   16694: Note that the special hash entries C<keys>, C<version> and
                   16695: C<timestamp> were added to the hash. C<version> will be equal to the
                   16696: total number of versions of the data that have been stored. The
                   16697: C<timestamp> attribute will be the UNIX time the hash was
                   16698: stored. C<keys> is available in every historical section to list which
                   16699: keys were added or changed at a specific historical revision of a
                   16700: hash.
                   16701: 
                   16702: B<Warning>: do not store the hash that restore returns directly. This
                   16703: will cause a mess since it will restore the historical keys as if the
                   16704: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 16705: 
1.394     bowersj2 16706: Calling convention:
1.191     harris41 16707: 
1.1225    raeburn  16708:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  16709:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 16710: 
1.394     bowersj2 16711: For more detailed information, see lonnet specific documentation.
1.191     harris41 16712: 
1.394     bowersj2 16713: =head1 RETURN MESSAGES
1.191     harris41 16714: 
1.394     bowersj2 16715: =over 4
1.191     harris41 16716: 
1.394     bowersj2 16717: =item * B<con_lost>: unable to contact remote host
1.191     harris41 16718: 
1.394     bowersj2 16719: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   16720: when the connection is brought back up
1.191     harris41 16721: 
1.394     bowersj2 16722: =item * B<con_failed>: unable to contact remote host and unable to save message
                   16723: for later delivery
1.191     harris41 16724: 
1.967     bisitz   16725: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 16726: 
1.394     bowersj2 16727: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 16728: that was requested
1.191     harris41 16729: 
1.243     albertel 16730: =back
1.191     harris41 16731: 
1.243     albertel 16732: =head1 PUBLIC SUBROUTINES
1.191     harris41 16733: 
1.243     albertel 16734: =head2 Session Environment Functions
1.191     harris41 16735: 
1.243     albertel 16736: =over 4
1.191     harris41 16737: 
1.394     bowersj2 16738: =item * 
                   16739: X<appenv()>
1.949     raeburn  16740: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 16741: the user envirnoment file, and will be restored for each access this
1.620     albertel 16742: user makes during this session, also modifies the %env for the current
1.949     raeburn  16743: process. Optional rolesarrayref - if defined contains a reference to an array
                   16744: of roles which are exempt from the restriction on modifying user.role entries 
                   16745: in the user's environment.db and in %env.    
1.191     harris41 16746: 
                   16747: =item *
1.394     bowersj2 16748: X<delenv()>
1.987     raeburn  16749: B<delenv($delthis,$regexp)>: removes all items from the session
                   16750: environment file that begin with $delthis. If the 
                   16751: optional second arg - $regexp - is true, $delthis is treated as a 
                   16752: regular expression, otherwise \Q$delthis\E is used. 
                   16753: The values are also deleted from the current processes %env.
1.191     harris41 16754: 
1.795     albertel 16755: =item * get_env_multiple($name) 
                   16756: 
                   16757: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   16758: values may be defined and end up as an array ref.
                   16759: 
                   16760: returns an array of values
                   16761: 
1.243     albertel 16762: =back
                   16763: 
                   16764: =head2 User Information
1.191     harris41 16765: 
1.243     albertel 16766: =over 4
1.191     harris41 16767: 
                   16768: =item *
1.394     bowersj2 16769: X<queryauthenticate()>
                   16770: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 16771: authentication scheme
                   16772: 
                   16773: =item *
1.394     bowersj2 16774: X<authenticate()>
1.1073    raeburn  16775: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 16776: authenticate user from domain's lib servers (first use the current
                   16777: one). C<$upass> should be the users password.
1.1073    raeburn  16778: $checkdefauth is optional (value is 1 if a check should be made to
                   16779:    authenticate user using default authentication method, and allow
                   16780:    account creation if username does not have account in the domain).
                   16781: $clientcancheckhost is optional (value is 1 if checking whether the
                   16782:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 16783: 
                   16784: =item *
1.394     bowersj2 16785: X<homeserver()>
                   16786: B<homeserver($uname,$udom)>: find the server which has
                   16787: the user's directory and files (there must be only one), this caches
                   16788: the answer, and also caches if there is a borken connection.
1.191     harris41 16789: 
                   16790: =item *
1.394     bowersj2 16791: X<idget()>
1.1300    raeburn  16792: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   16793: a list of student/employee IDs or clicker IDs
                   16794: (student/employee IDs are a unique resource in a domain, there must be 
                   16795: only 1 ID per username, and only 1 username per ID in a specific domain).
                   16796: clickerIDs are not necessarily unique, as students might share clickers.
                   16797: (returns hash: id=>name,id=>name)
1.191     harris41 16798: 
                   16799: =item *
1.394     bowersj2 16800: X<idrget()>
                   16801: B<idrget($udom,@unames)>: find the IDs behind a list of
                   16802: usernames (returns hash: name=>id,name=>id)
1.191     harris41 16803: 
                   16804: =item *
1.394     bowersj2 16805: X<idput()>
1.1300    raeburn  16806: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   16807: names and associated student/employee IDs or clicker IDs.
                   16808: 
                   16809: =item *
                   16810: X<iddel()>
                   16811: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   16812: student/employee ID or clicker ID username look-ups from domain.
                   16813: The homeserver ($uhome) and namespace ($namespace) are optional.
                   16814: If no $uhome is provided, it will be determined usig &homeserver()
                   16815: for each user.  If no $namespace is provided, the default is ids.
                   16816: 
                   16817: =item *
                   16818: X<updateclickers()>
                   16819: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   16820: clicker ID-to-username look-ups in clickers.db on library server.
                   16821: Permitted actions are add or del (i.e., add or delete). The 
                   16822: clickers.db contains clickerID as keys (escaped), and each corresponding
                   16823: value is an escaped comma-separated list of usernames (for whom the
                   16824: library server is the homeserver), who registered that particular ID.
                   16825: If $critical is true, the update will be sent via &critical, otherwise
                   16826: &reply() will be used.
1.191     harris41 16827: 
                   16828: =item *
1.394     bowersj2 16829: X<rolesinit()>
1.1169    droeschl 16830: B<rolesinit($udom,$username)>: get user privileges.
                   16831: returns user role, first access and timer interval hashes
1.243     albertel 16832: 
                   16833: =item *
1.1171    droeschl 16834: X<privileged()>
                   16835: B<privileged($username,$domain)>: returns a true if user has a
                   16836: privileged and active role (i.e. su or dc), false otherwise.
                   16837: 
                   16838: =item *
1.551     albertel 16839: X<getsection()>
                   16840: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 16841: course $cname, return section name/number or '' for "not in course"
                   16842: and '-1' for "no section"
                   16843: 
                   16844: =item *
1.394     bowersj2 16845: X<userenvironment()>
                   16846: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 16847: passed in @what from the requested user's environment, returns a hash
                   16848: 
1.858     raeburn  16849: =item * 
                   16850: X<userlog_query()>
1.859     albertel 16851: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   16852: activity.log file. %filters defines filters applied when parsing the
                   16853: log file. These can be start or end timestamps, or the type of action
                   16854: - log to look for Login or Logout events, check for Checkin or
                   16855: Checkout, role for role selection. The response is in the form
                   16856: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   16857: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  16858: 
1.243     albertel 16859: =back
                   16860: 
                   16861: =head2 User Roles
                   16862: 
                   16863: =over 4
                   16864: 
                   16865: =item *
                   16866: 
1.1284    raeburn  16867: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   16868: returns codes for allowed actions.
                   16869: 
                   16870: The first argument is required, all others are optional.
                   16871: 
                   16872: $priv is the privilege being checked.
                   16873: $uri contains additional information about what is being checked for access (e.g.,
                   16874: URL, course ID etc.). 
                   16875: $symb is the unique resource instance identifier in a course; if needed,
                   16876: but not provided, it will be retrieved via a call to &symbread(). 
                   16877: $role is the role for which a priv is being checked (only used if priv is evb). 
                   16878: $clientip is the user's IP address (only used when checking for access to portfolio 
                   16879: files).
                   16880: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   16881: prevents recursive calls to &allowed.
                   16882: 
1.243     albertel 16883:  F: full access
                   16884:  U,I,K: authentication modes (cxx only)
                   16885:  '': forbidden
                   16886:  1: user needs to choose course
                   16887:  2: browse allowed
1.766     albertel 16888:  A: passphrase authentication needed
1.1284    raeburn  16889:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  16890:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 16891: 
                   16892: =item *
                   16893: 
1.1192    raeburn  16894: constructaccess($url,$setpriv) : check for access to construction space URL
                   16895: 
                   16896: See if the owner domain and name in the URL match those in the
                   16897: expected environment.  If so, return three element list
                   16898: ($ownername,$ownerdomain,$ownerhome).
                   16899: 
                   16900: Otherwise return the null string.
                   16901: 
                   16902: If second argument 'setpriv' is true, it assigns the privileges,
                   16903: and returns the same three element list, unless the owner has
                   16904: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   16905: in which case the null string is returned.
                   16906: 
                   16907: =item *
                   16908: 
1.1326    raeburn  16909: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   16910: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   16911: for system, domain, and course level. $uname and $udom are optional (current
                   16912: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 16913: 
                   16914: =item *
                   16915: 
1.988     raeburn  16916: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   16917: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  16918: $type is Course (default) or Community.
1.988     raeburn  16919: If $forcedefault evaluates to true, text returned will be default 
                   16920: text for $type. Otherwise, if this is a course, the text returned 
                   16921: will be a custom name for the role (if defined in the course's 
                   16922: environment).  If no custom name is defined the default is returned.
                   16923:    
1.832     raeburn  16924: =item *
                   16925: 
1.1219    raeburn  16926: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  16927: All arguments are optional. Returns a hash of a roles, either for
                   16928: co-author/assistant author roles for a user's Construction Space
1.906     albertel 16929: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  16930: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   16931: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   16932: For each key, value is set to colon-separated start and end times for
                   16933: the role.  If no username and domain are specified, will default to
1.934     raeburn  16934: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  16935: of role statuses (active, future or previous), roles 
                   16936: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   16937: to restrict the list of roles reported. If no array ref is 
                   16938: provided for types, will default to return only active roles.
1.834     albertel 16939: 
1.1195    raeburn  16940: =item *
                   16941: 
                   16942: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  16943: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   16944: 
                   16945: Additional optional arguments are: $type (if role checking is to be restricted 
                   16946: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  16947: available roles) or future (roles available in the future), and
                   16948: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  16949: have active Domain Coordinator role in course's domain or in additional
                   16950: domains (specified in 'Domains to check for privileged users' in course
                   16951: environment -- set via:  Course Settings -> Classlists and staff listing).
                   16952: 
                   16953: =item *
                   16954: 
                   16955: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   16956: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   16957: $possdomains and $possroles are optional array refs -- to domains to check and
                   16958: roles to check.  If $possdomains is not specified, a dump will be done of the
                   16959: users' roles.db to check for a dc or su role in any domain. This can be
                   16960: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   16961: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   16962: this then allows &privileged_by_domain() to be used, which caches the identity
                   16963: of privileged users, eliminating the need for repeated calls to &dump().
                   16964: 
                   16965: =item *
                   16966: 
                   16967: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   16968: where the outer hash keys are domains specified in the $possdomains array ref,
                   16969: next inner hash keys are privileged roles specified in the $roles array ref,
                   16970: and the innermost hash contains key = value pairs for username:domain = end:start
                   16971: for active or future "privileged" users with that role in that domain. To avoid
                   16972: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   16973: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  16974: 
1.243     albertel 16975: =back
                   16976: 
                   16977: =head2 User Modification
                   16978: 
                   16979: =over 4
                   16980: 
                   16981: =item *
                   16982: 
1.957     raeburn  16983: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 16984: user for the level given by URL.  Optional start and end dates (leave empty
                   16985: string or zero for "no date")
1.191     harris41 16986: 
                   16987: =item *
                   16988: 
1.243     albertel 16989: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   16990: change a users, password, possible return values are: ok,
                   16991: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   16992: refused
1.191     harris41 16993: 
                   16994: =item *
                   16995: 
1.243     albertel 16996: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 16997: 
                   16998: =item *
                   16999: 
1.1058    raeburn  17000: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   17001:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   17002: 
                   17003: will update user information (firstname,middlename,lastname,generation,
                   17004: permanentemail), and if forceid is true, student/employee ID also.
                   17005: A user's institutional affiliation(s) can also be updated.
                   17006: User information fields will not be overwritten with empty entries 
                   17007: unless the field is included in the $candelete array reference.
                   17008: This array is included when a single user is modified via "Manage Users",
                   17009: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 17010: 
                   17011: =item *
                   17012: 
1.286     matthew  17013: modifystudent
                   17014: 
1.957     raeburn  17015: modify a student's enrollment and identification information.
1.1235    raeburn  17016: The course id is resolved based on the current user's environment.  
                   17017: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  17018: associated with a course.
                   17019: 
1.297     matthew  17020: This call is essentially a wrapper for lonnet::modifyuser and
                   17021: lonnet::modify_student_enrollment
1.286     matthew  17022: 
                   17023: Inputs: 
                   17024: 
                   17025: =over 4
                   17026: 
1.957     raeburn  17027: =item B<$udom> Student's loncapa domain
1.286     matthew  17028: 
1.957     raeburn  17029: =item B<$uname> Student's loncapa login name
1.286     matthew  17030: 
1.964     bisitz   17031: =item B<$uid> Student/Employee ID
1.286     matthew  17032: 
1.957     raeburn  17033: =item B<$umode> Student's authentication mode
1.286     matthew  17034: 
1.957     raeburn  17035: =item B<$upass> Student's password
1.286     matthew  17036: 
1.957     raeburn  17037: =item B<$first> Student's first name
1.286     matthew  17038: 
1.957     raeburn  17039: =item B<$middle> Student's middle name
1.286     matthew  17040: 
1.957     raeburn  17041: =item B<$last> Student's last name
1.286     matthew  17042: 
1.957     raeburn  17043: =item B<$gene> Student's generation
1.286     matthew  17044: 
1.957     raeburn  17045: =item B<$usec> Student's section in course
1.286     matthew  17046: 
                   17047: =item B<$end> Unix time of the roles expiration
                   17048: 
                   17049: =item B<$start> Unix time of the roles start date
                   17050: 
                   17051: =item B<$forceid> If defined, allow $uid to be changed
                   17052: 
                   17053: =item B<$desiredhome> server to use as home server for student
                   17054: 
1.957     raeburn  17055: =item B<$email> Student's permanent e-mail address
                   17056: 
                   17057: =item B<$type> Type of enrollment (auto or manual)
                   17058: 
1.963     raeburn  17059: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   17060: 
                   17061: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  17062: 
1.963     raeburn  17063: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  17064: 
1.963     raeburn  17065: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  17066: 
1.1216    raeburn  17067: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   17068: 
                   17069: =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  17070: 
1.286     matthew  17071: =back
1.297     matthew  17072: 
                   17073: =item *
                   17074: 
                   17075: modify_student_enrollment
                   17076: 
1.1235    raeburn  17077: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  17078: 'role.request.course' must be defined for this function to proceed.
                   17079: 
                   17080: Inputs:
                   17081: 
                   17082: =over 4
                   17083: 
1.1235    raeburn  17084: =item $udom, student's domain
1.297     matthew  17085: 
1.1235    raeburn  17086: =item $uname, student's name
1.297     matthew  17087: 
1.1235    raeburn  17088: =item $uid, student's user id
1.297     matthew  17089: 
1.1235    raeburn  17090: =item $first, student's first name
1.297     matthew  17091: 
                   17092: =item $middle
                   17093: 
                   17094: =item $last
                   17095: 
                   17096: =item $gene
                   17097: 
                   17098: =item $usec
                   17099: 
                   17100: =item $end
                   17101: 
                   17102: =item $start
                   17103: 
1.957     raeburn  17104: =item $type
                   17105: 
                   17106: =item $locktype
                   17107: 
                   17108: =item $cid
                   17109: 
                   17110: =item $selfenroll
                   17111: 
                   17112: =item $context
                   17113: 
1.1216    raeburn  17114: =item $credits, number of credits student will earn from this class
                   17115: 
1.1314    raeburn  17116: =item $instsec, institutional course section code for student
                   17117: 
1.297     matthew  17118: =back
                   17119: 
1.191     harris41 17120: 
                   17121: =item *
                   17122: 
1.243     albertel 17123: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   17124: custom role; give a custom role to a user for the level given by URL.  Specify
                   17125: name and domain of role author, and role name
1.191     harris41 17126: 
                   17127: =item *
                   17128: 
1.243     albertel 17129: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 17130: 
                   17131: =item *
                   17132: 
1.243     albertel 17133: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   17134: 
                   17135: =back
                   17136: 
                   17137: =head2 Course Infomation
                   17138: 
                   17139: =over 4
1.191     harris41 17140: 
                   17141: =item *
                   17142: 
1.1118    foxr     17143: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 17144: specified course id, including all environment settings for the
                   17145: course, the description of the course will be in the hash under the
                   17146: key 'description'
1.191     harris41 17147: 
1.1118    foxr     17148: $options is an optional parameter that if supplied is a hash reference that controls
                   17149: what how this function works.  It has the following key/values:
                   17150: 
                   17151: =over 4
                   17152: 
                   17153: =item freshen_cache
                   17154: 
                   17155: If defined, and the environment cache for the course is valid, it is 
                   17156: returned in the returned hash.
                   17157: 
                   17158: =item one_time
                   17159: 
                   17160: If defined, the last cache time is set to _now_
                   17161: 
                   17162: =item user
                   17163: 
                   17164: If defined, the supplied username is used instead of the current user.
                   17165: 
                   17166: 
                   17167: =back
                   17168: 
1.191     harris41 17169: =item *
                   17170: 
1.624     albertel 17171: resdata($name,$domain,$type,@which) : request for current parameter
                   17172: setting for a specific $type, where $type is either 'course' or 'user',
                   17173: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  17174: answers for 10 minutes.
1.243     albertel 17175: 
1.877     foxr     17176: =item *
                   17177: 
                   17178: get_courseresdata($courseid, $domain) : dump the entire course resource
                   17179: data base, returning a hash that is keyed by the resource name and has
                   17180: values that are the resource value.  I believe that the timestamps and
                   17181: versions are also returned.
                   17182: 
1.243     albertel 17183: =back
                   17184: 
                   17185: =head2 Course Modification
                   17186: 
                   17187: =over 4
1.191     harris41 17188: 
                   17189: =item *
                   17190: 
1.243     albertel 17191: writecoursepref($courseid,%prefs) : write preferences (environment
                   17192: database) for a course
1.191     harris41 17193: 
                   17194: =item *
                   17195: 
1.1011    raeburn  17196: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   17197: 
                   17198: =item *
                   17199: 
1.1038    raeburn  17200: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 17201: 
1.1167    droeschl 17202: =item *
                   17203: 
                   17204: is_course($courseid), is_course($cdom, $cnum)
                   17205: 
                   17206: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   17207: two component version $cdom, $cnum. It checks if the specified course exists.
                   17208: 
                   17209: Returns:
                   17210:     undef if the course doesn't exist, otherwise
                   17211:     in scalar context the combined courseid.
                   17212:     in list context the two components of the course identifier, domain and 
                   17213:     courseid.    
                   17214: 
1.243     albertel 17215: =back
                   17216: 
1.1401    raeburn  17217: =head2 Bubblesheet Configuration
                   17218: 
                   17219: =over 4
                   17220: 
                   17221: =item *
                   17222: 
                   17223: get_scantron_config($which)
                   17224: 
                   17225: $which - the name of the configuration to parse from the file.
                   17226: 
                   17227: Parses and returns the bubblesheet configuration line selected as a
                   17228: hash of configuration file fields.
                   17229: 
                   17230: 
                   17231: Returns:
                   17232:     If the named configuration is not in the file, an empty
                   17233:     hash is returned.
                   17234: 
                   17235:     a hash with the fields
                   17236:       name         - internal name for the this configuration setup
                   17237:       description  - text to display to operator that describes this config
                   17238:       CODElocation - if 0 or the string 'none'
                   17239:                           - no CODE exists for this config
                   17240:                      if -1 || the string 'letter'
                   17241:                           - a CODE exists for this config and is
                   17242:                             a string of letters
                   17243:                      Unsupported value (but planned for future support)
                   17244:                           if a positive integer
                   17245:                                - The CODE exists as the first n items from
                   17246:                                  the question section of the form
                   17247:                           if the string 'number'
                   17248:                                - The CODE exists for this config and is
                   17249:                                  a string of numbers
                   17250:       CODEstart   - (only matter if a CODE exists) column in the line where
                   17251:                      the CODE starts
                   17252:       CODElength  - length of the CODE
                   17253:       IDstart     - column where the student/employee ID starts
                   17254:       IDlength    - length of the student/employee ID info
                   17255:       Qstart      - column where the information from the bubbled
                   17256:                     'questions' start
                   17257:       Qlength     - number of columns comprising a single bubble line from
                   17258:                     the sheet. (usually either 1 or 10)
                   17259:       Qon         - either a single character representing the character used
                   17260:                     to signal a bubble was chosen in the positional setup, or
                   17261:                     the string 'letter' if the letter of the chosen bubble is
                   17262:                     in the final, or 'number' if a number representing the
                   17263:                     chosen bubble is in the file (1->A 0->J)
                   17264:       Qoff        - the character used to represent that a bubble was
                   17265:                     left blank
                   17266:       PaperID     - if the scanning process generates a unique number for each
                   17267:                     sheet scanned the column that this ID number starts in
                   17268:       PaperIDlength - number of columns that comprise the unique ID number
                   17269:                       for the sheet of paper
                   17270:       FirstName   - column that the first name starts in
                   17271:       FirstNameLength - number of columns that the first name spans
                   17272:       LastName    - column that the last name starts in
                   17273:       LastNameLength - number of columns that the last name spans
                   17274:       BubblesPerRow - number of bubbles available in each row used to
                   17275:                       bubble an answer. (If not specified, 10 assumed).
                   17276: 
                   17277: 
                   17278: =item *
                   17279: 
                   17280: get_scantronformat_file($cdom)
                   17281: 
                   17282: $cdom - the course's domain (optional); if not supplied, uses
                   17283: domain for current $env{'request.course.id'}.
                   17284: 
                   17285: Returns an array containing lines from the scantron format file for
                   17286: the domain of the course.
                   17287: 
                   17288: If a url for a custom.tab file is listed in domain's configuration.db,
                   17289: lines are from this file.
                   17290: 
                   17291: Otherwise, if a default.tab has been published in RES space by the
                   17292: domainconfig user, lines are from this file.
                   17293: 
                   17294: Otherwise, fall back to getting lines from the legacy file on the
                   17295: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   17296: 
                   17297: =back
                   17298: 
1.243     albertel 17299: =head2 Resource Subroutines
                   17300: 
                   17301: =over 4
1.191     harris41 17302: 
                   17303: =item *
                   17304: 
1.243     albertel 17305: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 17306: 
                   17307: =item *
                   17308: 
1.243     albertel 17309: repcopy($filename) : subscribes to the requested file, and attempts to
                   17310: replicate from the owning library server, Might return
1.607     raeburn  17311: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   17312: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 17313: resource. Expects the local filesystem pathname
                   17314: (/home/httpd/html/res/....)
                   17315: 
                   17316: =back
                   17317: 
                   17318: =head2 Resource Information
                   17319: 
                   17320: =over 4
1.191     harris41 17321: 
                   17322: =item *
                   17323: 
1.1228    raeburn  17324: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   17325: and returns the value of a variety of different possible values,
                   17326: $varname should be a request string, and the other parameters can be
                   17327: used to specify who and what one is asking about. Ordinarily, $cid 
                   17328: does not need to be specified, as it is retrived from 
                   17329: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   17330: within lonuserstate::loadmap() when initializing a course, before
                   17331: $env{'request.course.id'} has been set, so it needs to be provided
                   17332: in that one case.
1.243     albertel 17333: 
                   17334: Possible values for $varname are environment.lastname (or other item
                   17335: from the envirnment hash), user.name (or someother aspect about the
                   17336: user), resource.0.maxtries (or some other part and parameter of a
                   17337: resource)
1.204     albertel 17338: 
                   17339: =item *
                   17340: 
1.243     albertel 17341: directcondval($number) : get current value of a condition; reads from a state
                   17342: string
1.204     albertel 17343: 
                   17344: =item *
                   17345: 
1.243     albertel 17346: condval($condidx) : value of condition index based on state
1.204     albertel 17347: 
                   17348: =item *
                   17349: 
1.1362    raeburn  17350: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 17351: resource's metadata, $what should be either a specific key, or either
                   17352: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  17353: packages that this resource currently uses, the last 3 arguments are 
                   17354: only used internally for recursive metadata.
                   17355: 
                   17356: the toolsymb is only used where the uri is for an external tool (for which
                   17357: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 17358: 
1.1371    raeburn  17359: this function automatically caches all requests except any made recursively
                   17360: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   17361: defined).
1.191     harris41 17362: 
                   17363: =item *
                   17364: 
1.243     albertel 17365: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   17366: network of library servers; returns file handle of where SQL and regex results
                   17367: will be stored for query
1.191     harris41 17368: 
                   17369: =item *
                   17370: 
1.1282    raeburn  17371: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   17372: return symbolic list entry (all arguments optional). 
                   17373: 
                   17374: Args: filename is the filename (including path) for the file for which a symb 
                   17375: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   17376: to check access status if more than one resource was found in the bighash 
                   17377: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   17378: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   17379: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   17380: cause possible symbs to be checked to determine if they are subject to content
                   17381: blocking, if so they will not be included as possible symbs; possibles is a
                   17382: ref to a hash, which, as a side effect, will be populated with all possible 
                   17383: symbs (content blocking not tested).
                   17384:  
1.243     albertel 17385: returns the data handle
1.191     harris41 17386: 
                   17387: =item *
                   17388: 
1.1190    raeburn  17389: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   17390: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 17391: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  17392: on failure, user must be in a course, as it assumes the existence of
                   17393: the course initial hash, and uses $env('request.course.id'}.  The third
                   17394: arg is an optional reference to a scalar.  If this arg is passed in the 
                   17395: call to symbverify, it will be set to 1 if the symb has been set to be 
                   17396: encrypted; otherwise it will be null.  
1.191     harris41 17397: 
                   17398: =item *
                   17399: 
1.243     albertel 17400: symbclean($symb) : removes versions numbers from a symb, returns the
                   17401: cleaned symb
1.191     harris41 17402: 
                   17403: =item *
                   17404: 
1.243     albertel 17405: is_on_map($uri) : checks if the $uri is somewhere on the current
                   17406: course map, user must be in a course for it to work.
1.191     harris41 17407: 
                   17408: =item *
                   17409: 
1.243     albertel 17410: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 17411: 
                   17412: =item *
                   17413: 
1.243     albertel 17414: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   17415: a random seed, all arguments are optional, if they aren't sent it uses the
                   17416: environment to derive them. Note: if symb isn't sent and it can't get one
                   17417: from &symbread it will use the current time as its return value
1.191     harris41 17418: 
                   17419: =item *
                   17420: 
1.243     albertel 17421: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   17422: unfakeable, receipt
1.191     harris41 17423: 
                   17424: =item *
                   17425: 
1.620     albertel 17426: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 17427: 
                   17428: =item *
                   17429: 
1.243     albertel 17430: countacc($url) : count the number of accesses to a given URL
1.191     harris41 17431: 
                   17432: =item *
                   17433: 
1.243     albertel 17434: 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 17435: 
                   17436: =item *
                   17437: 
1.243     albertel 17438: 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 17439: 
                   17440: =item *
                   17441: 
1.243     albertel 17442: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 17443: 
                   17444: =item *
                   17445: 
1.243     albertel 17446: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   17447: forcing spreadsheet to reevaluate the resource scores next time.
                   17448: 
1.1195    raeburn  17449: =item * 
                   17450: 
1.1196    raeburn  17451: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   17452: when viewing in course context.
1.1195    raeburn  17453: 
1.1196    raeburn  17454:  input: six args -- filename (decluttered), course number, course domain,
                   17455:                     url, symb (if registered) and group (if this is a 
                   17456:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  17457: 
1.1196    raeburn  17458:  output: array of five scalars --
1.1195    raeburn  17459:          $cfile -- url for file editing if editable on current server
                   17460:          $home -- homeserver of resource (i.e., for author if published,
                   17461:                                           or course if uploaded.).
                   17462:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  17463:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   17464:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  17465: 
                   17466: =item *
                   17467: 
                   17468: is_course_upload($file,$cnum,$cdom)
                   17469: 
                   17470: Used in course context to determine if current file was uploaded to 
                   17471: the course (i.e., would be found in /userfiles/docs on the course's 
                   17472: homeserver.
                   17473: 
                   17474:   input: 3 args -- filename (decluttered), course number and course domain.
                   17475:   output: boolean -- 1 if file was uploaded.
                   17476: 
1.243     albertel 17477: =back
                   17478: 
                   17479: =head2 Storing/Retreiving Data
                   17480: 
                   17481: =over 4
1.191     harris41 17482: 
                   17483: =item *
                   17484: 
1.1269    raeburn  17485: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   17486: permanently for this url; hashref needs to be given and should be a \%hashname;
                   17487: the remaining args aren't required and if they aren't passed or are '' they will
                   17488: be derived from the env (with the exception of $laststore, which is an 
                   17489: optional arg used when a user's submission is stored in grading).
                   17490: $laststore is $version=$timestamp, where $version is the most recent version
                   17491: number retrieved for the corresponding $symb in the $namespace db file, and
                   17492: $timestamp is the timestamp for that transaction (UNIX time).
                   17493: $laststore is currently only passed when cstore() is called by 
                   17494: structuretags::finalize_storage().
1.191     harris41 17495: 
                   17496: =item *
                   17497: 
1.1269    raeburn  17498: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   17499: but uses critical subroutine
1.191     harris41 17500: 
                   17501: =item *
                   17502: 
1.243     albertel 17503: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   17504: all args are optional
1.191     harris41 17505: 
                   17506: =item *
                   17507: 
1.717     albertel 17508: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   17509: dumps the complete (or key matching regexp) namespace into a hash
                   17510: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   17511: normally &store()ed into
                   17512: 
                   17513: $range should be either an integer '100' (give me the first 100
                   17514:                                            matching records)
                   17515:               or be  two integers sperated by a - with no spaces
                   17516:                  '30-50' (give me the 30th through the 50th matching
                   17517:                           records)
                   17518: 
                   17519: 
                   17520: =item *
                   17521: 
1.1269    raeburn  17522: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 17523: replaces a &store() version of data with a replacement set of data
                   17524: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  17525: reference. If $tolog is true, the transaction is logged in the courselog
                   17526: with an action=PUTSTORE.
1.717     albertel 17527: 
                   17528: =item *
                   17529: 
1.243     albertel 17530: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   17531: works very similar to store/cstore, but all data is stored in a
                   17532: temporary location and can be reset using tmpreset, $storehash should
                   17533: be a hash reference, returns nothing on success
1.191     harris41 17534: 
                   17535: =item *
                   17536: 
1.243     albertel 17537: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   17538: similar to restore, but all data is stored in a temporary location and
                   17539: can be reset using tmpreset. Returns a hash of values on success,
                   17540: error string otherwise.
1.191     harris41 17541: 
                   17542: =item *
                   17543: 
1.243     albertel 17544: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   17545: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 17546: 
                   17547: =item *
                   17548: 
1.243     albertel 17549: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   17550: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 17551: 
                   17552: =item *
                   17553: 
1.243     albertel 17554: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   17555: namesp ($udom and $uname are optional)
1.191     harris41 17556: 
                   17557: =item *
                   17558: 
1.702     albertel 17559: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 17560: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 17561: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  17562: 
1.702     albertel 17563: $range should be either an integer '100' (give me the first 100
                   17564:                                            matching records)
                   17565:               or be  two integers sperated by a - with no spaces
                   17566:                  '30-50' (give me the 30th through the 50th matching
                   17567:                           records)
1.449     matthew  17568: =item *
                   17569: 
                   17570: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   17571: $store can be a scalar, an array reference, or if the amount to be 
                   17572: incremented is > 1, a hash reference.
                   17573: 
                   17574: ($udom and $uname are optional)
1.191     harris41 17575: 
                   17576: =item *
                   17577: 
1.243     albertel 17578: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   17579: ($udom and $uname are optional)
1.191     harris41 17580: 
                   17581: =item *
                   17582: 
1.243     albertel 17583: cput($namespace,$storehash,$udom,$uname) : critical put
                   17584: ($udom and $uname are optional)
1.191     harris41 17585: 
                   17586: =item *
                   17587: 
1.748     albertel 17588: newput($namespace,$storehash,$udom,$uname) :
                   17589: 
                   17590: Attempts to store the items in the $storehash, but only if they don't
                   17591: currently exist, if this succeeds you can be certain that you have 
                   17592: successfully created a new key value pair in the $namespace db.
                   17593: 
                   17594: 
                   17595: Args:
                   17596:  $namespace: name of database to store values to
                   17597:  $storehash: hashref to store to the db
                   17598:  $udom: (optional) domain of user containing the db
                   17599:  $uname: (optional) name of user caontaining the db
                   17600: 
                   17601: Returns:
                   17602:  'ok' -> succeeded in storing all keys of $storehash
                   17603:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   17604:                         least <key> already existed in the db (other
                   17605:                         requested keys may also already exist)
1.967     bisitz   17606:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 17607:  'con_lost' -> unable to contact request server
                   17608:  'refused' -> action was not allowed by remote machine
                   17609: 
                   17610: 
                   17611: =item *
                   17612: 
1.243     albertel 17613: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   17614: reference filled in from namesp (encrypts the return communication)
                   17615: ($udom and $uname are optional)
1.191     harris41 17616: 
                   17617: =item *
                   17618: 
1.243     albertel 17619: log($udom,$name,$home,$message) : write to permanent log for user; use
                   17620: critical subroutine
                   17621: 
1.806     raeburn  17622: =item *
                   17623: 
1.860     raeburn  17624: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   17625: array reference filled in from namespace found in domain level on either
                   17626: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  17627: 
                   17628: =item *
                   17629: 
1.860     raeburn  17630: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   17631: domain level either on specified domain server ($uhome) or primary domain 
                   17632: server ($udom and $uhome are optional)
1.806     raeburn  17633: 
1.943     raeburn  17634: =item * 
                   17635: 
1.1240    raeburn  17636: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   17637: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   17638: the target domain.
                   17639: 
                   17640: May also include additional key => value pairs for the following groups:
                   17641: 
                   17642: =over
                   17643: 
                   17644: =item
                   17645: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   17646: 
                   17647: =over
                   17648: 
                   17649: =item defaultquota, authorquota
                   17650: 
                   17651: =back
                   17652: 
                   17653: =item
                   17654: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   17655: portfolio for users).
                   17656: 
                   17657: =over
                   17658: 
                   17659: =item
                   17660: aboutme, blog, webdav, portfolio
                   17661: 
                   17662: =back
                   17663: 
                   17664: =item
                   17665: requestcourses: ability to request courses, and how requests are processed.
                   17666: 
                   17667: =over
                   17668: 
                   17669: =item
1.1305    raeburn  17670: official, unofficial, community, textbook, placement
1.1240    raeburn  17671: 
                   17672: =back
                   17673: 
                   17674: =item
                   17675: inststatus: types of institutional affiliation, and order in which they are displayed.
                   17676: 
                   17677: =over
                   17678: 
                   17679: =item
1.1256    raeburn  17680: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  17681: 
                   17682: =back
                   17683: 
                   17684: =item
                   17685: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   17686: for course's uploaded content.
                   17687: 
                   17688: =over
                   17689: 
                   17690: =item
1.1246    raeburn  17691: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  17692: communityquota, textbookquota, placementquota
1.1240    raeburn  17693: 
                   17694: =back
                   17695: 
                   17696: =item
                   17697: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   17698: on your servers.
                   17699: 
                   17700: =over
                   17701: 
                   17702: =item 
                   17703: remotesessions, hostedsessions
                   17704: 
                   17705: =back
                   17706: 
                   17707: =back
                   17708: 
                   17709: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   17710: utility to create a configuration.db file on a domain's primary library server 
                   17711: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   17712: -- corresponding values are authentication type (internal, krb4, krb5,
                   17713: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   17714: will be available. Values are retrieved from cache (if current), unless the
                   17715: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   17716: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   17717: 
                   17718: Typical usage:
1.943     raeburn  17719: 
1.1240    raeburn  17720: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  17721: 
1.243     albertel 17722: =back
                   17723: 
                   17724: =head2 Network Status Functions
                   17725: 
                   17726: =over 4
1.191     harris41 17727: 
                   17728: =item *
                   17729: 
1.1137    raeburn  17730: dirlist() : return directory list based on URI (first arg).
                   17731: 
                   17732: Inputs: 1 required, 5 optional.
                   17733: 
                   17734: =over
                   17735: 
                   17736: =item 
                   17737: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   17738: 
                   17739: =item
                   17740: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   17741: 
                   17742: =item
                   17743: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   17744: 
                   17745: =item
                   17746: $getpropath - boolean: 1 if prepend path using &propath(). 
                   17747: 
                   17748: =item
                   17749: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   17750: 
                   17751: =item 
                   17752: $alternateRoot - path to prepend in place of path from $uri.
                   17753: 
                   17754: =back
                   17755: 
                   17756: Returns: Array of up to two items.
                   17757: 
                   17758: =over
                   17759: 
                   17760: a reference to an array of files/subdirectories
                   17761: 
                   17762: =over
                   17763: 
                   17764: Each element in the array of files/subdirectories is a & separated list of
                   17765: item name and the result of running stat on the item.  If dirlist was requested
                   17766: for a file instead of a directory, the item name will be ''. For a directory 
                   17767: listing, if the item is a metadata file, the element will end &N&M 
                   17768: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   17769: default copyright set (1).  
                   17770: 
                   17771: =back
                   17772: 
                   17773: a scalar containing error condition (if encountered).
                   17774: 
                   17775: =over
                   17776: 
                   17777: =item 
                   17778: no_host (no homeserver identified for $username:$domain).
                   17779: 
                   17780: =item 
                   17781: no_such_host (server contacted for listing not identified as valid host).
                   17782: 
                   17783: =item 
                   17784: con_lost (connection to remote server failed).
                   17785: 
                   17786: =item 
                   17787: refused (invalid $username:$domain received on lond side).
                   17788: 
                   17789: =item 
                   17790: no_such_dir (directory at specified path on lond side does not exist). 
                   17791: 
                   17792: =item 
                   17793: empty (directory at specified path on lond side is empty).
                   17794: 
                   17795: =over
                   17796: 
                   17797: This is currently not encountered because the &ls3, &ls2, 
                   17798: &ls (_handler) routines on the lond side do not filter out
                   17799: . and .. from a directory listing. 
                   17800: 
                   17801: =back
                   17802: 
                   17803: =back
                   17804: 
                   17805: =back
1.191     harris41 17806: 
                   17807: =item *
                   17808: 
1.243     albertel 17809: spareserver() : find server with least workload from spare.tab
                   17810: 
1.986     foxr     17811: 
                   17812: =item *
                   17813: 
                   17814: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   17815: if there is no corresponding loncapa host.
                   17816: 
1.243     albertel 17817: =back
                   17818: 
1.986     foxr     17819: 
1.243     albertel 17820: =head2 Apache Request
                   17821: 
                   17822: =over 4
1.191     harris41 17823: 
                   17824: =item *
                   17825: 
1.243     albertel 17826: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   17827: localhost, posts hash
                   17828: 
                   17829: =back
                   17830: 
                   17831: =head2 Data to String to Data
                   17832: 
                   17833: =over 4
1.191     harris41 17834: 
                   17835: =item *
                   17836: 
1.243     albertel 17837: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   17838: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 17839: 
                   17840: =item *
                   17841: 
1.243     albertel 17842: hashref2str($hashref) : convert a hashref into a string complete with
                   17843: escaping and '=' and '&' separators, supports elements that are
                   17844: arrayrefs and hashrefs
1.191     harris41 17845: 
                   17846: =item *
                   17847: 
1.243     albertel 17848: arrayref2str($arrayref) : convert an arrayref into a string complete
                   17849: with escaping and '&' separators, supports elements that are arrayrefs
                   17850: and hashrefs
1.191     harris41 17851: 
                   17852: =item *
                   17853: 
1.243     albertel 17854: str2hash($string) : convert string to hash using unescaping and
                   17855: splitting on '=' and '&', supports elements that are arrayrefs and
                   17856: hashrefs
1.191     harris41 17857: 
                   17858: =item *
                   17859: 
1.243     albertel 17860: str2array($string) : convert string to hash using unescaping and
                   17861: splitting on '&', supports elements that are arrayrefs and hashrefs
                   17862: 
                   17863: =back
                   17864: 
                   17865: =head2 Logging Routines
                   17866: 
                   17867: 
                   17868: These routines allow one to make log messages in the lonnet.log and
                   17869: lonnet.perm logfiles.
1.191     harris41 17870: 
1.1119    foxr     17871: =over 4
                   17872: 
1.191     harris41 17873: =item *
                   17874: 
1.243     albertel 17875: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 17876: 
                   17877: =item *
                   17878: 
1.243     albertel 17879: logthis() : append message to the normal lonnet.log file, it gets
                   17880: preiodically rolled over and deleted.
1.191     harris41 17881: 
                   17882: =item *
                   17883: 
1.243     albertel 17884: logperm() : append a permanent message to lonnet.perm.log, this log
                   17885: file never gets deleted by any automated portion of the system, only
                   17886: messages of critical importance should go in here.
                   17887: 
1.1119    foxr     17888: 
1.243     albertel 17889: =back
                   17890: 
                   17891: =head2 General File Helper Routines
                   17892: 
                   17893: =over 4
1.191     harris41 17894: 
                   17895: =item *
                   17896: 
1.481     raeburn  17897: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   17898: (a) files in /uploaded
                   17899:   (i) If a local copy of the file exists - 
                   17900:       compares modification date of local copy with last-modified date for 
                   17901:       definitive version stored on home server for course. If local copy is 
                   17902:       stale, requests a new version from the home server and stores it. 
                   17903:       If the original has been removed from the home server, then local copy 
                   17904:       is unlinked.
                   17905:   (ii) If local copy does not exist -
                   17906:       requests the file from the home server and stores it. 
                   17907:   
                   17908:   If $caller is 'uploadrep':  
                   17909:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   17910:     for request for files originally uploaded via DOCS. 
                   17911:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   17912:   
                   17913:   Otherwise:
                   17914:      This indicates a call from the content generation phase of the request.
                   17915:      -  returns the entire contents of the file or -1.
                   17916:      
                   17917: (b) files in /res
                   17918:    - returns the entire contents of a file or -1; 
                   17919:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 17920: 
1.712     albertel 17921: 
                   17922: =item *
                   17923: 
                   17924: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   17925:                   reference
                   17926: 
                   17927: returns either a stat() list of data about the file or an empty list
                   17928: if the file doesn't exist or couldn't find out about it (connection
                   17929: problems or user unknown)
                   17930: 
1.191     harris41 17931: =item *
                   17932: 
1.243     albertel 17933: filelocation($dir,$file) : returns file system location of a file
                   17934: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   17935: directory that relative $file lookups are to looked in ($dir of /a/dir
                   17936: and a file of ../bob will become /a/bob)
1.191     harris41 17937: 
                   17938: =item *
                   17939: 
                   17940: hreflocation($dir,$file) : returns file system location or a URL; same as
                   17941: filelocation except for hrefs
                   17942: 
                   17943: =item *
                   17944: 
1.1261    raeburn  17945: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   17946: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 17947: 
1.243     albertel 17948: =back
                   17949: 
1.608     albertel 17950: =head2 Usererfile file routines (/uploaded*)
                   17951: 
                   17952: =over 4
                   17953: 
                   17954: =item *
                   17955: 
                   17956: userfileupload(): main rotine for putting a file in a user or course's
                   17957:                   filespace, arguments are,
                   17958: 
1.620     albertel 17959:  formname - required - this is the name of the element in $env where the
1.608     albertel 17960:            filename, and the contents of the file to create/modifed exist
1.620     albertel 17961:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   17962:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  17963:  context - if coursedoc, store the file in the course of the active role
                   17964:              of the current user; 
                   17965:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   17966:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 17967:  subdir - required - subdirectory to put the file in under ../userfiles/
                   17968:          if undefined, it will be placed in "unknown"
                   17969: 
                   17970:  (This routine calls clean_filename() to remove any dangerous
                   17971:  characters from the filename, and then calls finuserfileupload() to
                   17972:  complete the transaction)
                   17973: 
                   17974:  returns either the url of the uploaded file (/uploaded/....) if successful
                   17975:  and /adm/notfound.html if unsuccessful
                   17976: 
                   17977: =item *
                   17978: 
                   17979: clean_filename(): routine for cleaing a filename up for storage in
                   17980:                  userfile space, argument is:
                   17981: 
                   17982:  filename - proposed filename
                   17983: 
                   17984: returns: the new clean filename
                   17985: 
                   17986: =item *
                   17987: 
1.1090    raeburn  17988: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 17989: userspace, probably shouldn't be called directly
                   17990: 
                   17991:   docuname: username or courseid of destination for the file
                   17992:   docudom: domain of user/course of destination for the file
                   17993:   formname: same as for userfileupload()
1.1090    raeburn  17994:   fname: filename (including subdirectories) for the file
                   17995:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  17996:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  17997:   allfiles: reference to hash used to store objects found by parser
                   17998:   codebase: reference to hash used for codebases of java objects found by parser
                   17999:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   18000:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   18001:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   18002:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   18003:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   18004:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  18005:   mimetype: reference to scalar to accommodate mime type determined
                   18006:             from File::MMagic if $parser = parse.
1.608     albertel 18007: 
                   18008:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  18009:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   18010:  was 'overwrite').
                   18011:  
1.608     albertel 18012: 
                   18013: =item *
                   18014: 
                   18015: renameuserfile(): renames an existing userfile to a new name
                   18016: 
                   18017:   Args:
                   18018:    docuname: username or courseid of destination for the file
                   18019:    docudom: domain of user/course of destination for the file
                   18020:    old: current file name (including any subdirs under userfiles)
                   18021:    new: desired file name (including any subdirs under userfiles)
                   18022: 
                   18023: =item *
                   18024: 
                   18025: mkdiruserfile(): creates a directory is a userfiles dir
                   18026: 
                   18027:   Args:
                   18028:    docuname: username or courseid of destination for the file
                   18029:    docudom: domain of user/course of destination for the file
                   18030:    dir: dir to create (including any subdirs under userfiles)
                   18031: 
                   18032: =item *
                   18033: 
                   18034: removeuserfile(): removes a file that exists in userfiles
                   18035: 
                   18036:   Args:
                   18037:    docuname: username or courseid of destination for the file
                   18038:    docudom: domain of user/course of destination for the file
                   18039:    fname: filname to delete (including any subdirs under userfiles)
                   18040: 
                   18041: =item *
                   18042: 
                   18043: removeuploadedurl(): convience function for removeuserfile()
                   18044: 
                   18045:   Args:
                   18046:    url:  a full /uploaded/... url to delete
                   18047: 
1.747     albertel 18048: =item * 
                   18049: 
                   18050: get_portfile_permissions():
                   18051:   Args:
                   18052:     domain: domain of user or course contain the portfolio files
                   18053:     user: name of user or num of course contain the portfolio files
                   18054:   Returns:
                   18055:     hashref of a dump of the proper file_permissions.db
                   18056:    
                   18057: 
                   18058: =item * 
                   18059: 
                   18060: get_access_controls():
                   18061: 
                   18062: Args:
                   18063:   current_permissions: the hash ref returned from get_portfile_permissions()
                   18064:   group: (optional) the group you want the files associated with
                   18065:   file: (optional) the file you want access info on
                   18066: 
                   18067: Returns:
1.749     raeburn  18068:     a hash (keys are file names) of hashes containing
                   18069:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   18070:         values are XML containing access control settings (see below) 
1.747     albertel 18071: 
                   18072: Internal notes:
                   18073: 
1.749     raeburn  18074:  access controls are stored in file_permissions.db as key=value pairs.
                   18075:     key -> path to file/file_name\0uniqueID:scope_end_start
                   18076:         where scope -> public,guest,course,group,domains or users.
                   18077:               end -> UNIX time for end of access (0 -> no end date)
                   18078:               start -> UNIX time for start of access
                   18079: 
                   18080:     value -> XML description of access control
                   18081:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   18082:             <start></start>
                   18083:             <end></end>
                   18084: 
                   18085:             <password></password>  for scope type = guest
                   18086: 
                   18087:             <domain></domain>     for scope type = course or group
                   18088:             <number></number>
                   18089:             <roles id="">
                   18090:              <role></role>
                   18091:              <access></access>
                   18092:              <section></section>
                   18093:              <group></group>
                   18094:             </roles>
                   18095: 
                   18096:             <dom></dom>         for scope type = domains
                   18097: 
                   18098:             <users>             for scope type = users
                   18099:              <user>
                   18100:               <uname></uname>
                   18101:               <udom></udom>
                   18102:              </user>
                   18103:             </users>
                   18104:            </scope> 
                   18105:               
                   18106:  Access data is also aggregated for each file in an additional key=value pair:
                   18107:  key -> path to file/file_name\0accesscontrol 
                   18108:  value -> reference to hash
                   18109:           hash contains key = value pairs
                   18110:           where key = uniqueID:scope_end_start
                   18111:                 value = UNIX time record was last updated
                   18112: 
                   18113:           Used to improve speed of look-ups of access controls for each file.  
                   18114:  
                   18115:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   18116: 
1.1198    raeburn  18117: =item *
                   18118: 
1.749     raeburn  18119: modify_access_controls():
                   18120: 
                   18121: Modifies access controls for a portfolio file
                   18122: Args
                   18123: 1. file name
                   18124: 2. reference to hash of required changes,
                   18125: 3. domain
                   18126: 4. username
                   18127:   where domain,username are the domain of the portfolio owner 
                   18128:   (either a user or a course) 
                   18129: 
                   18130: Returns:
                   18131: 1. result of additions or updates ('ok' or 'error', with error message). 
                   18132: 2. result of deletions ('ok' or 'error', with error message).
                   18133: 3. reference to hash of any new or updated access controls.
                   18134: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   18135:    key = integer (inbound ID)
1.1198    raeburn  18136:    value = uniqueID
                   18137: 
                   18138: =item *
                   18139: 
                   18140: get_timebased_id():
                   18141: 
                   18142: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   18143: course via the Course Editor (e.g., folders, composite pages, 
                   18144: group bulletin boards).
                   18145: 
                   18146: Args: (first three required; six others optional)
                   18147: 
                   18148: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   18149:    docssequence, or name of group
                   18150: 
                   18151: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   18152:    e.g., num, boardids
                   18153: 
                   18154: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   18155:    file will be named nohist_namespace.db
                   18156: 
                   18157: 4. cdom: domain of course; default is current course domain from %env
                   18158: 
                   18159: 5. cnum: course number; default is current course number from %env
                   18160: 
                   18161: 6. idtype: set to concat if an additional digit is to be appended to the 
                   18162:    unix timestamp to form the suffix, if the plain timestamp is already
                   18163:    in use.  Default is to not do this, but simply increment the unix 
                   18164:    timestamp by 1 until a unique key is obtained.
                   18165: 
                   18166: 7. who: holder of locking key; defaults to user:domain for user.
                   18167: 
                   18168: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   18169:    retrying); default is 3.
                   18170: 
                   18171: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   18172: 
                   18173: Returns:
                   18174: 
                   18175: 1. suffix obtained (numeric)
                   18176: 
                   18177: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   18178: 
                   18179: 3. error: contains (localized) error message if an error occurred.
                   18180: 
1.747     albertel 18181: 
1.608     albertel 18182: =back
                   18183: 
1.243     albertel 18184: =head2 HTTP Helper Routines
                   18185: 
                   18186: =over 4
                   18187: 
1.191     harris41 18188: =item *
                   18189: 
                   18190: escape() : unpack non-word characters into CGI-compatible hex codes
                   18191: 
                   18192: =item *
                   18193: 
                   18194: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   18195: 
1.243     albertel 18196: =back
                   18197: 
                   18198: =head1 PRIVATE SUBROUTINES
                   18199: 
                   18200: =head2 Underlying communication routines (Shouldn't call)
                   18201: 
                   18202: =over 4
                   18203: 
                   18204: =item *
                   18205: 
                   18206: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   18207: 
                   18208: =item *
                   18209: 
                   18210: reply() : uses subreply to send a message to remote machine, logs all failures
                   18211: 
                   18212: =item *
                   18213: 
                   18214: critical() : passes a critical message to another server; if cannot
                   18215: get through then place message in connection buffer directory and
                   18216: returns con_delayed, if incapable of saving message, returns
                   18217: con_failed
                   18218: 
                   18219: =item *
                   18220: 
                   18221: reconlonc() : tries to reconnect lonc client processes.
                   18222: 
                   18223: =back
                   18224: 
                   18225: =head2 Resource Access Logging
                   18226: 
                   18227: =over 4
                   18228: 
                   18229: =item *
                   18230: 
                   18231: flushcourselogs() : flush (save) buffer logs and access logs
                   18232: 
                   18233: =item *
                   18234: 
                   18235: courselog($what) : save message for course in hash
                   18236: 
                   18237: =item *
                   18238: 
                   18239: courseacclog($what) : save message for course using &courselog().  Perform
                   18240: special processing for specific resource types (problems, exams, quizzes, etc).
                   18241: 
1.191     harris41 18242: =item *
                   18243: 
                   18244: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   18245: as a PerlChildExitHandler
1.243     albertel 18246: 
                   18247: =back
                   18248: 
                   18249: =head2 Other
                   18250: 
                   18251: =over 4
                   18252: 
                   18253: =item *
                   18254: 
                   18255: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 18256: 
                   18257: =back
                   18258: 
                   18259: =cut
1.877     foxr     18260: 

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