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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1517  ! raeburn     4: # $Id: lonnet.pm,v 1.1516 2023/10/06 01:22:06 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.1508    raeburn  2760:                                   'ltisec','toolsec','domexttool',
1.1512    raeburn  2761:                                   'exttool','privacy'],$domain);
1.1305    raeburn  2762:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2763:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2764:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2765:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2766:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2767:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2768:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2769:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1492    raeburn  2770:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
                   2771:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1340    raeburn  2772:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2773:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2774:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484    raeburn  2775:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2776:     } else {
                   2777:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2778:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2779:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2780:     }
1.976     raeburn  2781:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2782:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2783:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2784:         } else {
                   2785:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2786:         }
1.1177    raeburn  2787:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2788:         foreach my $item (@usertools) {
                   2789:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2790:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2791:             }
                   2792:         }
1.1229    raeburn  2793:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2794:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2795:         }
1.976     raeburn  2796:     }
1.985     raeburn  2797:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2798:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2799:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2800:         }
                   2801:     }
1.1183    raeburn  2802:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2803:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2804:     }
1.1517  ! raeburn  2805:     if (ref($domconfig{'authordefaults'}) eq 'HASH') {
        !          2806:         foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors') {
        !          2807:             if ($item eq 'editors') {
        !          2808:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
        !          2809:                     $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
        !          2810:                 }
        !          2811:             } else {
        !          2812:                 $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
        !          2813:             }
        !          2814:         }
        !          2815:     }
1.989     raeburn  2816:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2817:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2818:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2819:         }
                   2820:     }
1.1047    raeburn  2821:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2822:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2823:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476    raeburn  2824:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277    raeburn  2825:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2826:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2827:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2828:         }
1.1254    raeburn  2829:         foreach my $type (@coursetypes) {
                   2830:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2831:                 unless ($type eq 'community') {
                   2832:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2833:                 }
                   2834:             }
                   2835:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2836:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2837:             }
1.1514    raeburn  2838:             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
                   2839:                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
                   2840:             }
1.1277    raeburn  2841:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2842:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2843:                     $domdefaults{$type.'postsubtimeout'} = 
                   2844:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2845:                 }
                   2846:             }
1.1508    raeburn  2847:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
                   2848:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
                   2849:             } else {
                   2850:                 $domdefaults{$type.'domexttool'} = 1;
                   2851:             }
                   2852:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
                   2853:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
                   2854:             } else {
                   2855:                 $domdefaults{$type.'exttool'} = 0;
                   2856:             }
1.1230    raeburn  2857:         }
1.1286    raeburn  2858:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2859:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2860:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2861:                 if (@clonecodes) {
                   2862:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2863:                 }
                   2864:             }
                   2865:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2866:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2867:         }
1.1356    raeburn  2868:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2869:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480    raeburn  2870:         }
                   2871:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2872:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2873:         }
1.1047    raeburn  2874:     }
1.1073    raeburn  2875:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2876:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2877:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2878:         }
                   2879:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2880:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2881:         }
1.1279    raeburn  2882:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2883:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2884:         }
1.1440    raeburn  2885:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439    raeburn  2886:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2887:         }
1.1073    raeburn  2888:     }
1.1254    raeburn  2889:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2890:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2891:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2892:                             'approval','limit');
                   2893:             foreach my $type (@coursetypes) {
                   2894:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2895:                     my @mgrdc = ();
                   2896:                     foreach my $item (@settings) {
                   2897:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2898:                             push(@mgrdc,$item);
                   2899:                         }
                   2900:                     }
                   2901:                     if (@mgrdc) {
                   2902:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2903:                     }
                   2904:                 }
                   2905:             }
                   2906:         }
                   2907:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2908:             foreach my $type (@coursetypes) {
                   2909:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2910:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2911:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2912:                     }
                   2913:                 }
                   2914:             }
                   2915:         }
                   2916:     }
1.1258    raeburn  2917:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2918:         $domdefaults{'catauth'} = 'std';
                   2919:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2920:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2921:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2922:         }
                   2923:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2924:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2925:         }
                   2926:     }
1.1315    raeburn  2927:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2928:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2929:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2930:         }
1.1338    raeburn  2931:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2932:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2933:         }
                   2934:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2935:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2936:         }
                   2937:     }
1.1320    raeburn  2938:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2939:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2940:         foreach my $prefix (@prefixes) {
                   2941:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2942:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2943:             }
                   2944:         }
                   2945:     }
1.1314    raeburn  2946:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2947:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477    raeburn  2948:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314    raeburn  2949:     }
1.1332    raeburn  2950:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2951:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2952:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2953:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2954:         }
                   2955:     }
1.1434    raeburn  2956:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449    raeburn  2957:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434    raeburn  2958:             if ($domconfig{'wafproxy'}{$item}) {
                   2959:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2960:             }
                   2961:         }
1.1482    raeburn  2962:     }
                   2963:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2964:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2965:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2966:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2967:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2968:         }
                   2969:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2970:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
1.1504    raeburn  2971:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2972:             }
                   2973:         }
                   2974:     }
                   2975:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   2976:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
                   2977:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
                   2978:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
                   2979:         }
                   2980:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
                   2981:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2982:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
1.1482    raeburn  2983:             }
                   2984:         }
                   2985:     }
1.1512    raeburn  2986:     if (ref($domconfig{'privacy'}) eq 'HASH') {
                   2987:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
                   2988:             foreach my $domtype ('instdom','extdom') {
                   2989:                 if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
                   2990:                     foreach my $roletype ('domain','author','course','community') {
                   2991:                         if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
                   2992:                             $domdefaults{'userapprovals'} = 1;
                   2993:                             last;
                   2994:                         }
                   2995:                     }
                   2996:                 }
                   2997:                 last if ($domdefaults{'userapprovals'});
                   2998:             }
                   2999:         }
                   3000:     }
1.1219    raeburn  3001:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  3002:     return %domdefaults;
                   3003: }
                   3004: 
1.1412    raeburn  3005: sub get_dom_cats {
                   3006:     my ($dom) = @_;
                   3007:     return unless (&domain($dom));
                   3008:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   3009:     unless (defined($cached)) {
                   3010:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   3011:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   3012:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   3013:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   3014:             } else {
                   3015:                 $cats = {};
                   3016:             }
                   3017:         } else {
                   3018:             $cats = {};
                   3019:         }
1.1494    raeburn  3020:         &do_cache_new('cats',$dom,$cats,3600);
1.1412    raeburn  3021:     }
1.1413    raeburn  3022:     return $cats;
                   3023: }
                   3024: 
                   3025: sub get_dom_instcats {
                   3026:     my ($dom) = @_;
                   3027:     return unless (&domain($dom));
                   3028:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   3029:     unless (defined($cached)) {
                   3030:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   3031:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   3032:         if ($totcodes > 0) {
                   3033:             my $caller = 'global';
                   3034:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   3035:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   3036:                 $instcats = {
1.1503    raeburn  3037:                                 totcodes => $totcodes,
1.1413    raeburn  3038:                                 codes => \%codes,
                   3039:                                 codetitles => \@codetitles,
                   3040:                                 cat_titles => \%cat_titles,
                   3041:                                 cat_order => \%cat_order,
                   3042:                             };
                   3043:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   3044:             }
                   3045:         }
                   3046:     }
                   3047:     return $instcats;
                   3048: }
                   3049: 
                   3050: sub retrieve_instcodes {
                   3051:     my ($coursecodes,$dom) = @_;
                   3052:     my $totcodes;
                   3053:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   3054:     foreach my $course (keys(%courses)) {
                   3055:         if (ref($courses{$course}) eq 'HASH') {
                   3056:             if ($courses{$course}{'inst_code'} ne '') {
                   3057:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   3058:                 $totcodes ++;
                   3059:             }
                   3060:         }
                   3061:     }
                   3062:     return $totcodes;
1.1412    raeburn  3063: }
                   3064: 
1.1311    raeburn  3065: sub course_portal_url {
1.1451    raeburn  3066:     my ($cnum,$cdom,$r) = @_;
1.1311    raeburn  3067:     my $chome = &homeserver($cnum,$cdom);
                   3068:     my $hostname = &hostname($chome);
                   3069:     my $protocol = $protocol{$chome};
                   3070:     $protocol = 'http' if ($protocol ne 'https');
                   3071:     my %domdefaults = &get_domain_defaults($cdom);
                   3072:     my $firsturl;
                   3073:     if ($domdefaults{'portal_def'}) {
                   3074:         $firsturl = $domdefaults{'portal_def'};
                   3075:     } else {
1.1494    raeburn  3076:         my $alias = &use_proxy_alias($r,$chome);
1.1451    raeburn  3077:         $hostname = $alias if ($alias ne '');
1.1311    raeburn  3078:         $firsturl = $protocol.'://'.$hostname;
                   3079:     }
                   3080:     return $firsturl;
                   3081: }
                   3082: 
1.1492    raeburn  3083: sub url_prefix {
                   3084:     my ($r,$dom,$home,$context) = @_;
                   3085:     my $prefix;
                   3086:     my %domdefs = &get_domain_defaults($dom);
                   3087:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
                   3088:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
                   3089:             $prefix = $1;
                   3090:         }
                   3091:     }
                   3092:     if ($prefix eq '') {
                   3093:         my $hostname = &hostname($home);
                   3094:         my $protocol = $protocol{$home};
                   3095:         $protocol = 'http' if ($protocol{$home} ne 'https');
                   3096:         my $alias = &use_proxy_alias($r,$home);
                   3097:         $hostname = $alias if ($alias ne '');
                   3098:         $prefix = $protocol.'://'.$hostname;
                   3099:     }
                   3100:     return $prefix;
                   3101: }
                   3102: 
1.1407    raeburn  3103: # --------------------------------------------- Get domain config for passwords
                   3104: 
                   3105: sub get_passwdconf {
                   3106:     my ($dom) = @_;
                   3107:     my (%passwdconf,$gotconf,$lookup);
                   3108:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   3109:     if (defined($cached)) {
                   3110:         if (ref($result) eq 'HASH') {
                   3111:             %passwdconf = %{$result};
                   3112:             $gotconf = 1;
                   3113:         }
                   3114:     }
                   3115:     unless ($gotconf) {
                   3116:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   3117:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   3118:             %passwdconf = %{$domconfig{'passwords'}};
                   3119:         }
                   3120:         my $cachetime = 24*60*60;
                   3121:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   3122:     }
                   3123:     return %passwdconf;
                   3124: }
                   3125: 
1.344     www      3126: # --------------------------------------------------- Assign a key to a student
                   3127: 
                   3128: sub assign_access_key {
1.364     www      3129: #
                   3130: # a valid key looks like uname:udom#comments
                   3131: # comments are being appended
                   3132: #
1.498     www      3133:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   3134:     $kdom=
1.620     albertel 3135:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      3136:     $knum=
1.620     albertel 3137:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      3138:     $cdom=
1.620     albertel 3139:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3140:     $cnum=
1.620     albertel 3141:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3142:     $udom=$env{'user.name'} unless (defined($udom));
                   3143:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      3144:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      3145:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 3146:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      3147:                                                   # assigned to this person
                   3148:                                                   # - this should not happen,
1.345     www      3149:                                                   # unless something went wrong
                   3150:                                                   # the first time around
                   3151: # ready to assign
1.364     www      3152:         $logentry=$1.'; '.$logentry;
1.496     www      3153:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      3154:                                                  $kdom,$knum) eq 'ok') {
1.345     www      3155: # key now belongs to user
1.346     www      3156: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      3157:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  3158:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      3159:                 return 'ok';
                   3160:             } else {
                   3161:                 return 
                   3162:   'error: Count not permanently assign key, will need to be re-entered later.';
                   3163: 	    }
                   3164:         } else {
                   3165:             return 'error: Could not assign key, try again later.';
                   3166:         }
1.364     www      3167:     } elsif (!$existing{$ckey}) {
1.345     www      3168: # the key does not exist
                   3169: 	return 'error: The key does not exist';
                   3170:     } else {
                   3171: # the key is somebody else's
                   3172: 	return 'error: The key is already in use';
                   3173:     }
1.344     www      3174: }
                   3175: 
1.364     www      3176: # ------------------------------------------ put an additional comment on a key
                   3177: 
                   3178: sub comment_access_key {
                   3179: #
                   3180: # a valid key looks like uname:udom#comments
                   3181: # comments are being appended
                   3182: #
                   3183:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   3184:     $cdom=
1.620     albertel 3185:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      3186:     $cnum=
1.620     albertel 3187:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      3188:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   3189:     if ($existing{$ckey}) {
                   3190:         $existing{$ckey}.='; '.$logentry;
                   3191: # ready to assign
1.367     www      3192:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      3193:                                                  $cdom,$cnum) eq 'ok') {
                   3194: 	    return 'ok';
                   3195:         } else {
                   3196: 	    return 'error: Count not store comment.';
                   3197:         }
                   3198:     } else {
                   3199: # the key does not exist
                   3200: 	return 'error: The key does not exist';
                   3201:     }
                   3202: }
                   3203: 
1.344     www      3204: # ------------------------------------------------------ Generate a set of keys
                   3205: 
                   3206: sub generate_access_keys {
1.364     www      3207:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      3208:     $cdom=
1.620     albertel 3209:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3210:     $cnum=
1.620     albertel 3211:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      3212:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      3213:     unless (($cdom) && ($cnum)) { return 0; }
                   3214:     if ($number>10000) { return 0; }
                   3215:     sleep(2); # make sure don't get same seed twice
                   3216:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   3217:     my $total=0;
                   3218:     for (my $i=1;$i<=$number;$i++) {
                   3219:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   3220:                   sprintf("%lx",int(100000*rand)).'-'.
                   3221:                   sprintf("%lx",int(100000*rand));
                   3222:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   3223:        $newkey=~s/0/h/g; # and also 0 and O
                   3224:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   3225:        if ($existing{$newkey}) {
                   3226:            $i--;
                   3227:        } else {
1.364     www      3228: 	  if (&put('accesskeys',
                   3229:               { $newkey => '# generated '.localtime().
1.620     albertel 3230:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      3231:                            '; '.$logentry },
                   3232: 		   $cdom,$cnum) eq 'ok') {
1.344     www      3233:               $total++;
                   3234: 	  }
                   3235:        }
                   3236:     }
1.620     albertel 3237:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      3238:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   3239:     return $total;
                   3240: }
                   3241: 
                   3242: # ------------------------------------------------------- Validate an accesskey
                   3243: 
                   3244: sub validate_access_key {
                   3245:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   3246:     $cdom=
1.620     albertel 3247:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3248:     $cnum=
1.620     albertel 3249:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3250:     $udom=$env{'user.domain'} unless (defined($udom));
                   3251:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      3252:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 3253:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      3254: }
                   3255: 
                   3256: # ------------------------------------- Find the section of student in a course
1.652     albertel 3257: sub devalidate_getsection_cache {
                   3258:     my ($udom,$unam,$courseid)=@_;
                   3259:     my $hashid="$udom:$unam:$courseid";
                   3260:     &devalidate_cache_new('getsection',$hashid);
                   3261: }
1.298     matthew  3262: 
1.815     albertel 3263: sub courseid_to_courseurl {
                   3264:     my ($courseid) = @_;
                   3265:     #already url style courseid
                   3266:     return $courseid if ($courseid =~ m{^/});
                   3267: 
                   3268:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3269: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3270: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3271: 	return "/$cdom/$cnum";
                   3272:     }
                   3273: 
1.1494    raeburn  3274:     my %courseinfo=&coursedescription($courseid);
1.815     albertel 3275:     if (exists($courseinfo{'num'})) {
                   3276: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3277:     }
                   3278: 
                   3279:     return undef;
                   3280: }
                   3281: 
1.298     matthew  3282: sub getsection {
                   3283:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3284:     my $cachetime=1800;
1.551     albertel 3285: 
                   3286:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3287:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3288:     if (defined($cached)) { return $result; }
                   3289: 
1.298     matthew  3290:     my %Pending; 
                   3291:     my %Expired;
                   3292:     #
                   3293:     # Each role can either have not started yet (pending), be active, 
                   3294:     #    or have expired.
                   3295:     #
                   3296:     # If there is an active role, we are done.
                   3297:     #
                   3298:     # If there is more than one role which has not started yet, 
                   3299:     #     choose the one which will start sooner
                   3300:     # If there is one role which has not started yet, return it.
                   3301:     #
                   3302:     # If there is more than one expired role, choose the one which ended last.
                   3303:     # If there is a role which has expired, return it.
                   3304:     #
1.815     albertel 3305:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3306:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3307:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3308:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3309:         my $section=$1;
                   3310:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3311:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3312:         my $now=time;
1.548     albertel 3313:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3314:             $Expired{$end}=$section;
                   3315:             next;
                   3316:         }
1.548     albertel 3317:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3318:             $Pending{$start}=$section;
                   3319:             next;
                   3320:         }
1.599     albertel 3321:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3322:     }
                   3323:     #
                   3324:     # Presumedly there will be few matching roles from the above
                   3325:     # loop and the sorting time will be negligible.
                   3326:     if (scalar(keys(%Pending))) {
                   3327:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3328:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3329:     } 
                   3330:     if (scalar(keys(%Expired))) {
                   3331:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3332:         my $time = pop(@sorted);
1.599     albertel 3333:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3334:     }
1.599     albertel 3335:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3336: }
1.70      www      3337: 
1.599     albertel 3338: sub save_cache {
                   3339:     &purge_remembered();
1.722     albertel 3340:     #&Apache::loncommon::validate_page();
1.620     albertel 3341:     undef(%env);
1.780     albertel 3342:     undef($env_loaded);
1.599     albertel 3343: }
1.452     albertel 3344: 
1.599     albertel 3345: my $to_remember=-1;
                   3346: my %remembered;
                   3347: my %accessed;
                   3348: my $kicks=0;
                   3349: my $hits=0;
1.849     albertel 3350: sub make_key {
                   3351:     my ($name,$id) = @_;
1.872     albertel 3352:     if (length($id) > 65 
                   3353: 	&& length(&escape($id)) > 200) {
                   3354: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3355:     }
1.849     albertel 3356:     return &escape($name.':'.$id);
                   3357: }
                   3358: 
1.599     albertel 3359: sub devalidate_cache_new {
                   3360:     my ($name,$id,$debug) = @_;
                   3361:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3362:     my $remembered_id=$name.':'.$id;
1.849     albertel 3363:     $id=&make_key($name,$id);
1.599     albertel 3364:     $memcache->delete($id);
1.1319    damieng  3365:     delete($remembered{$remembered_id});
                   3366:     delete($accessed{$remembered_id});
1.599     albertel 3367: }
                   3368: 
                   3369: sub is_cached_new {
                   3370:     my ($name,$id,$debug) = @_;
1.1319    damieng  3371:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3372:     if (exists($remembered{$remembered_id})) {
                   3373: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3374: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3375: 	$hits++;
1.1319    damieng  3376: 	return ($remembered{$remembered_id},1);
1.599     albertel 3377:     }
1.1319    damieng  3378:     $id=&make_key($name,$id);
1.599     albertel 3379:     my $value = $memcache->get($id);
                   3380:     if (!(defined($value))) {
                   3381: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3382: 	return (undef,undef);
1.416     albertel 3383:     }
1.599     albertel 3384:     if ($value eq '__undef__') {
                   3385: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3386: 	$value=undef;
                   3387:     }
1.1319    damieng  3388:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3389:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3390:     return ($value,1);
                   3391: }
                   3392: 
                   3393: sub do_cache_new {
                   3394:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3395:     my $remembered_id=$name.':'.$id;
1.849     albertel 3396:     $id=&make_key($name,$id);
1.599     albertel 3397:     my $setvalue=$value;
                   3398:     if (!defined($setvalue)) {
                   3399: 	$setvalue='__undef__';
                   3400:     }
1.623     albertel 3401:     if (!defined($time) ) {
                   3402: 	$time=600;
                   3403:     }
1.599     albertel 3404:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3405:     my $result = $memcache->set($id,$setvalue,$time);
                   3406:     if (! $result) {
1.872     albertel 3407: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3408: 	$memcache->disconnect_all();
1.872     albertel 3409:     }
1.600     albertel 3410:     # need to make a copy of $value
1.1319    damieng  3411:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3412:     return $value;
                   3413: }
                   3414: 
                   3415: sub make_room {
1.1319    damieng  3416:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3417: 
1.1319    damieng  3418:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3419:                                     : $value;
1.599     albertel 3420:     if ($to_remember<0) { return; }
1.1319    damieng  3421:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3422:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3423:     my $to_kick;
                   3424:     my $max_time=0;
                   3425:     foreach my $other (keys(%accessed)) {
                   3426: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3427: 	    $to_kick=$other;
                   3428: 	    $max_time=&tv_interval($accessed{$other});
                   3429: 	}
                   3430:     }
                   3431:     delete($remembered{$to_kick});
                   3432:     delete($accessed{$to_kick});
                   3433:     $kicks++;
                   3434:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3435:     return;
                   3436: }
                   3437: 
1.599     albertel 3438: sub purge_remembered {
1.604     albertel 3439:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3440:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3441:     undef(%remembered);
                   3442:     undef(%accessed);
1.428     albertel 3443: }
1.70      www      3444: # ------------------------------------- Read an entry from a user's environment
                   3445: 
                   3446: sub userenvironment {
                   3447:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3448:     my $items;
                   3449:     foreach my $item (@what) {
                   3450:         $items.=&escape($item).'&';
                   3451:     }
                   3452:     $items=~s/\&$//;
1.70      www      3453:     my %returnhash=();
1.1009    raeburn  3454:     my $uhome = &homeserver($unam,$udom);
                   3455:     unless ($uhome eq 'no_host') {
                   3456:         my @answer=split(/\&/, 
                   3457:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3458:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3459:             return %returnhash;
                   3460:         }
1.1009    raeburn  3461:         my $i;
                   3462:         for ($i=0;$i<=$#what;$i++) {
                   3463: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3464:         }
1.70      www      3465:     }
                   3466:     return %returnhash;
1.1       albertel 3467: }
                   3468: 
1.617     albertel 3469: # ---------------------------------------------------------- Get a studentphoto
                   3470: sub studentphoto {
                   3471:     my ($udom,$unam,$ext) = @_;
1.1494    raeburn  3472:     my $home=&homeserver($unam,$udom);
1.706     raeburn  3473:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3474:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3475:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3476:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3477:             } else {
                   3478:                 my ($result,$perm_reqd)=
1.1494    raeburn  3479: 		    &auto_photo_permission($unam,$udom);
1.706     raeburn  3480:                 if ($result eq 'ok') {
                   3481:                     if (!($perm_reqd eq 'yes')) {
                   3482:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3483:                     }
                   3484:                 }
                   3485:             }
                   3486:         }
                   3487:     } else {
                   3488:         my ($result,$perm_reqd) = 
1.1494    raeburn  3489: 	    &auto_photo_permission($unam,$udom);
1.706     raeburn  3490:         if ($result eq 'ok') {
                   3491:             if (!($perm_reqd eq 'yes')) {
                   3492:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3493:             }
                   3494:         }
                   3495:     }
                   3496:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3497: }
                   3498: 
                   3499: sub retrievestudentphoto {
                   3500:     my ($udom,$unam,$ext,$type) = @_;
1.1494    raeburn  3501:     my $home=&homeserver($unam,$udom);
                   3502:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
1.706     raeburn  3503:     if ($ret eq 'ok') {
                   3504:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3505:         if ($type eq 'thumbnail') {
                   3506:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3507:         }
1.1494    raeburn  3508:         my $tokenurl=&tokenwrapper($url);
1.706     raeburn  3509:         return $tokenurl;
                   3510:     } else {
                   3511:         if ($type eq 'thumbnail') {
                   3512:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3513:         } else { 
                   3514:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3515:         }
1.617     albertel 3516:     }
                   3517: }
                   3518: 
1.263     www      3519: # -------------------------------------------------------------------- New chat
                   3520: 
                   3521: sub chatsend {
1.724     raeburn  3522:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3523:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3524:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3525:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3526:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3527: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3528: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3529: }
                   3530: 
                   3531: # ------------------------------------------ Find current version of a resource
                   3532: 
                   3533: sub getversion {
                   3534:     my $fname=&clutter(shift);
1.1189    raeburn  3535:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3536:     return &currentversion(&filelocation('',$fname));
                   3537: }
                   3538: 
                   3539: sub currentversion {
                   3540:     my $fname=shift;
                   3541:     my $author=$fname;
                   3542:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3543:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3544:     my $home=&homeserver($uname,$udom);
1.292     www      3545:     if ($home eq 'no_host') { 
                   3546:         return -1; 
                   3547:     }
1.1112    www      3548:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3549:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3550: 	return -1;
                   3551:     }
1.1112    www      3552:     return $answer;
1.263     www      3553: }
                   3554: 
1.1111    www      3555: #
                   3556: # Return special version number of resource if set by override, empty otherwise
                   3557: #
                   3558: sub usedversion {
                   3559:     my $fname=shift;
                   3560:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3561:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3562:     if ($urlversion) { return $urlversion; }
                   3563:     return '';
                   3564: }
                   3565: 
1.1       albertel 3566: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3567: 
1.1       albertel 3568: sub subscribe {
                   3569:     my $fname=shift;
1.761     raeburn  3570:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3571:     $fname=~s/[\n\r]//g;
1.1       albertel 3572:     my $author=$fname;
                   3573:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3574:     my ($udom,$uname)=split(/\//,$author);
                   3575:     my $home=homeserver($uname,$udom);
1.335     albertel 3576:     if ($home eq 'no_host') {
                   3577:         return 'not_found';
1.1       albertel 3578:     }
                   3579:     my $answer=reply("sub:$fname",$home);
1.64      www      3580:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3581: 	$answer.=' by '.$home;
                   3582:     }
1.1       albertel 3583:     return $answer;
                   3584: }
                   3585:     
1.8       www      3586: # -------------------------------------------------------------- Replicate file
                   3587: 
                   3588: sub repcopy {
                   3589:     my $filename=shift;
1.23      www      3590:     $filename=~s/\/+/\//g;
1.1142    raeburn  3591:     my $londocroot = $perlvar{'lonDocRoot'};
                   3592:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3593:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3594:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3595: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3596: 	return &repcopy_userfile($filename);
                   3597:     }
1.532     albertel 3598:     $filename=~s/[\n\r]//g;
1.8       www      3599:     my $transname="$filename.in.transfer";
1.828     www      3600: # FIXME: this should flock
1.607     raeburn  3601:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3602:     my $remoteurl=subscribe($filename);
1.64      www      3603:     if ($remoteurl =~ /^con_lost by/) {
                   3604: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3605:            return 'unavailable';
1.8       www      3606:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3607: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3608: 	   return 'not_found';
1.64      www      3609:     } elsif ($remoteurl =~ /^rejected by/) {
                   3610: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3611:            return 'forbidden';
1.20      www      3612:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3613:            return 'ok';
1.8       www      3614:     } else {
1.290     www      3615:         my $author=$filename;
                   3616:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3617:         my ($udom,$uname)=split(/\//,$author);
                   3618:         my $home=homeserver($uname,$udom);
                   3619:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3620:            my @parts=split(/\//,$filename);
                   3621:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3622:            if ($path ne "$londocroot/res") {
1.8       www      3623:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3624: 	       return 'bad_request';
1.8       www      3625:            }
                   3626:            my $count;
                   3627:            for ($count=5;$count<$#parts;$count++) {
                   3628:                $path.="/$parts[$count]";
                   3629:                if ((-e $path)!=1) {
                   3630: 		   mkdir($path,0777);
                   3631:                }
                   3632:            }
                   3633:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3634:            my $response;
                   3635:            if ($remoteurl =~ m{/raw/}) {
                   3636:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3637:            } else {
                   3638:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3639:            }
1.8       www      3640:            if ($response->is_error()) {
                   3641: 	       unlink($transname);
                   3642:                my $message=$response->status_line;
1.672     albertel 3643:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3644:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3645:                return 'unavailable';
1.8       www      3646:            } else {
1.16      www      3647: 	       if ($remoteurl!~/\.meta$/) {
                   3648:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3649:                   my $mresponse;
                   3650:                   if ($remoteurl =~ m{/raw/}) {
                   3651:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3652:                   } else {
                   3653:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3654:                   }
1.16      www      3655:                   if ($mresponse->is_error()) {
                   3656: 		      unlink($filename.'.meta');
                   3657:                       &logthis(
1.672     albertel 3658:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3659:                   }
                   3660: 	       }
1.8       www      3661:                rename($transname,$filename);
1.607     raeburn  3662:                return 'ok';
1.8       www      3663:            }
1.290     www      3664:        }
1.8       www      3665:     }
1.330     www      3666: }
                   3667: 
1.1422    raeburn  3668: # ------------------------------------------------- Unsubscribe from a resource
                   3669: 
                   3670: sub unsubscribe {
                   3671:     my ($fname) = @_;
                   3672:     my $answer;
                   3673:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3674:     $fname=~s/[\n\r]//g;
                   3675:     my $author=$fname;
                   3676:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3677:     my ($udom,$uname)=split(/\//,$author);
                   3678:     my $home=homeserver($uname,$udom);
                   3679:     if ($home eq 'no_host') {
                   3680:         $answer = 'no_host';
                   3681:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3682:         $answer = 'home';
                   3683:     } else {
                   3684:         my $defdom = $perlvar{'lonDefDomain'};
                   3685:         if (&will_trust('content',$defdom,$udom)) {
                   3686:             $answer = reply("unsub:$fname",$home);
                   3687:         } else {
                   3688:             $answer = 'untrusted';
                   3689:         }
                   3690:     }
                   3691:     return $answer;
                   3692: }
                   3693: 
1.330     www      3694: # ------------------------------------------------ Get server side include body
                   3695: sub ssi_body {
1.381     albertel 3696:     my ($filelink,%form)=@_;
1.606     matthew  3697:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3698:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3699:     }
1.953     www      3700:     my $output='';
                   3701:     my $response;
1.980     raeburn  3702:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3703:        ($output,$response)=&externalssi($filelink);
1.953     www      3704:     } else {
1.1004    droeschl 3705:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3706:        $filelink .= 'inhibitmenu=yes';
1.953     www      3707:        ($output,$response)=&ssi($filelink,%form);
                   3708:     }
1.778     albertel 3709:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3710:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3711:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3712:     if (wantarray) {
                   3713:         return ($output, $response);
                   3714:     } else {
                   3715:         return $output;
                   3716:     }
1.8       www      3717: }
                   3718: 
1.15      www      3719: # --------------------------------------------------------- Server Side Include
                   3720: 
1.782     albertel 3721: sub absolute_url {
1.1447    raeburn  3722:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3723:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3724:     if ($host_name eq '') {
                   3725: 	$host_name = $ENV{'SERVER_NAME'};
                   3726:     }
1.1447    raeburn  3727:     if ($unalias) {
                   3728:         my $alias = &get_proxy_alias();
                   3729:         if ($alias eq $host_name) {
                   3730:             my $lonhost = $perlvar{'lonHostID'};
                   3731:             my $hostname = &hostname($lonhost);
                   3732:             my $lcproto; 
                   3733:             if (($keep_proto) || ($hostname eq '')) {
                   3734:                 $lcproto = $protocol;
                   3735:             } else {
                   3736:                 $lcproto = $protocol{$lonhost};
                   3737:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3738:                 $lcproto .= '://';
                   3739:             }
                   3740:             unless ($hostname eq '') {
                   3741:                 return $lcproto.$hostname;
                   3742:             }
                   3743:         }
                   3744:     }
1.782     albertel 3745:     return $protocol.$host_name;
                   3746: }
                   3747: 
1.942     foxr     3748: #
                   3749: #   Server side include.
                   3750: # Parameters:
                   3751: #  fn     Possibly encrypted resource name/id.
                   3752: #  form   Hash that describes how the rendering should be done
                   3753: #         and other things.
1.944     foxr     3754: # Returns:
1.950     raeburn  3755: #   Scalar context: The content of the response.
                   3756: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3757: #     
1.15      www      3758: sub ssi {
                   3759: 
1.944     foxr     3760:     my ($fn,%form)=@_;
1.1447    raeburn  3761:     my ($host,$request,$response);
                   3762:     $host = &absolute_url('',1);
1.711     albertel 3763: 
                   3764:     $form{'no_update_last_known'}=1;
1.895     albertel 3765:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3766:     if (%form) {
1.1447    raeburn  3767:       $request=new HTTP::Request('POST',$host.$fn);
1.1272    droeschl 3768:       $request->content(join('&',map { 
                   3769:             my $name = escape($_);
                   3770:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3771:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3772:             : &escape($form{$_}) );    
                   3773:         } keys(%form)));
1.23      www      3774:     } else {
1.1447    raeburn  3775:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3776:     }
                   3777: 
1.15      www      3778:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3779:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3780:     my $islocal;
                   3781:     if (($env{'request.course.id'}) &&
                   3782:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3783:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3784:         ($form{'grade_symb'} ne '') &&
1.1494    raeburn  3785:         (&allowed('mgr',$env{'request.course.id'}.
                   3786:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1385    raeburn  3787:         $islocal = 1;
                   3788:     }
1.1447    raeburn  3789:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
                   3790:                                              '','','',$islocal);
1.1182    foxr     3791: 
1.944     foxr     3792:     if (wantarray) {
1.1345    raeburn  3793: 	return ($response->content, $response);
1.944     foxr     3794:     } else {
1.1345    raeburn  3795: 	return $response->content;
1.942     foxr     3796:     }
1.324     www      3797: }
                   3798: 
                   3799: sub externalssi {
                   3800:     my ($url)=@_;
                   3801:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3802:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3803:     if (wantarray) {
                   3804:         return ($response->content, $response);
                   3805:     } else {
                   3806:         return $response->content;
                   3807:     }
1.15      www      3808: }
1.254     www      3809: 
1.1354    raeburn  3810: 
                   3811: # If the local copy of a replicated resource is outdated, trigger a  
                   3812: # connection from the homeserver to flush the delayed queue. If no update 
                   3813: # happens, remove local copies of outdated resource (and corresponding
                   3814: # metadata file).
                   3815: 
1.1352    raeburn  3816: sub remove_stale_resfile {
                   3817:     my ($url) = @_;
1.1354    raeburn  3818:     my $removed;
1.1352    raeburn  3819:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3820:         my $audom = $1;
                   3821:         my $auname = $2;
1.1353    raeburn  3822:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3823:             my $homeserver = &homeserver($auname,$audom);
                   3824:             unless (($homeserver eq 'no_host') ||
                   3825:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3826:                 my $fname = &filelocation('',$url);
                   3827:                 if (-e $fname) {
                   3828:                     my $hostname = &hostname($homeserver);
                   3829:                     if ($hostname) {
1.1397    raeburn  3830:                         my $protocol = $protocol{$homeserver};
                   3831:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3832:                         my $uri = &declutter($url);
                   3833:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3834:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3835:                         if ($response->is_success()) {
                   3836:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3837:                             my $locmodtime = (stat($fname))[9];
                   3838:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3839:                                 my $stale;
                   3840:                                 my $answer = &reply('pong',$homeserver);
                   3841:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3842:                                     sleep(0.2);
                   3843:                                     $locmodtime = (stat($fname))[9];
                   3844:                                     if ($locmodtime < $remmodtime) {
                   3845:                                         my $posstransfer = $fname.'.in.transfer';
                   3846:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3847:                                             $removed = 1;
                   3848:                                         } else {
                   3849:                                             $stale = 1;
                   3850:                                         }
                   3851:                                     } else {
                   3852:                                         $removed = 1;
                   3853:                                     }
                   3854:                                 } else {
                   3855:                                     $stale = 1;
                   3856:                                 }
                   3857:                                 if ($stale) {
1.1421    raeburn  3858:                                     if (unlink($fname)) {
                   3859:                                         if ($uri!~/\.meta$/) {
                   3860:                                             if (-e $fname.'.meta') {
                   3861:                                                 unlink($fname.'.meta');
                   3862:                                             }
                   3863:                                         }
1.1422    raeburn  3864:                                         my $unsubresult = &unsubscribe($fname);
                   3865:                                         unless ($unsubresult eq 'ok') {
                   3866:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3867:                                         }
1.1421    raeburn  3868:                                         $removed = 1;
1.1354    raeburn  3869:                                     }
1.1352    raeburn  3870:                                 }
                   3871:                             }
                   3872:                         }
                   3873:                     }
                   3874:                 }
                   3875:             }
                   3876:         }
                   3877:     }
1.1354    raeburn  3878:     return $removed;
1.1352    raeburn  3879: }
                   3880: 
1.492     albertel 3881: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3882: 
                   3883: sub allowuploaded {
                   3884:     my ($srcurl,$url)=@_;
                   3885:     $url=&clutter(&declutter($url));
                   3886:     my $dir=$url;
                   3887:     $dir=~s/\/[^\/]+$//;
                   3888:     my %httpref=();
                   3889:     my $httpurl=&hreflocation('',$url);
                   3890:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3891:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3892: }
1.477     raeburn  3893: 
1.1193    raeburn  3894: #
                   3895: # Determine if the current user should be able to edit a particular resource,
                   3896: # when viewing in course context.
                   3897: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3898: #     Functions.
                   3899: # (b) When displaying folder contents in course editor, used to determine if
                   3900: #     "Edit" link will be displayed alongside resource.
                   3901: #
1.1196    raeburn  3902: #  input: six args -- filename (decluttered), course number, course domain,
                   3903: #                   url, symb (if registered) and group (if this is a group
                   3904: #                   item -- e.g., bulletin board, group page etc.).
                   3905: #  output: array of five scalars -- 
1.1193    raeburn  3906: #          $cfile -- url for file editing if editable on current server
                   3907: #          $home -- homeserver of resource (i.e., for author if published,
                   3908: #                                           or course if uploaded.).
                   3909: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3910: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3911: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3912: #
                   3913: 
                   3914: sub can_edit_resource {
1.1194    raeburn  3915:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3916:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3917: #
                   3918: # For aboutme pages user can only edit his/her own.
                   3919: #
1.1199    raeburn  3920:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3921:         my ($sdom,$sname) = ($1,$2);
                   3922:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3923:             $home = $env{'user.home'};
                   3924:             $cfile = $resurl;
                   3925:             if ($env{'form.forceedit'}) {
                   3926:                 $forceview = 1;
                   3927:             } else {
                   3928:                 $forceedit = 1;
                   3929:             }
                   3930:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3931:         } else {
                   3932:             return;
                   3933:         }
                   3934:     }
                   3935: 
1.1517  ! raeburn  3936: #
        !          3937: # For /adm/viewcoauthors can only edit if author or co-author who is manager.
        !          3938: #
        !          3939: 
        !          3940:     if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
        !          3941:         if (((&allowed('cca',"$cdom/$cnum")) ||
        !          3942:              (&allowed('caa',"$cdom/$cnum"))) ||
        !          3943:              ((&allowed('vca',"$cdom/$cnum") ||
        !          3944:                &allowed('vaa',"$cdom/$cnum")) &&
        !          3945:               ($env{"environment.internal.manager./$cdom/$cnum"}))) {
        !          3946:             $home = $env{'user.home'};
        !          3947:             $cfile = $resurl;
        !          3948:             if ($env{'form.forceedit'}) {
        !          3949:                 $forceview = 1;
        !          3950:             } else {
        !          3951:                 $forceedit = 1;
        !          3952:             }
        !          3953:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
        !          3954:         } else {
        !          3955:             return;
        !          3956:         }
        !          3957:     }
        !          3958: 
1.1194    raeburn  3959:     if ($env{'request.course.id'}) {
1.1494    raeburn  3960:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
1.1194    raeburn  3961:         if ($group ne '') {
                   3962: # if this is a group homepage or group bulletin board, check group privs
                   3963:             my $allowed = 0;
1.1197    raeburn  3964:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3965:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3966:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3967:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3968:                     $allowed = 1;
                   3969:                 }
1.1197    raeburn  3970:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3971:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3972:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3973:                     $allowed = 1;
                   3974:                 }
                   3975:             }
                   3976:             if ($allowed) {
                   3977:                 $home=&homeserver($cnum,$cdom);
                   3978:                 if ($env{'form.forceedit'}) {
                   3979:                     $forceview = 1;
                   3980:                 } else {
                   3981:                     $forceedit = 1;
                   3982:                 }
                   3983:                 $cfile = $resurl;
                   3984:             } else {
                   3985:                 return;
                   3986:             }
                   3987:         } else {
1.1208    raeburn  3988:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
1.1494    raeburn  3989:                 unless (&allowed('opa',$env{'request.course.id'})) {
1.1208    raeburn  3990:                     return;
                   3991:                 }
                   3992:             } elsif (!$crsedit) {
1.1507    raeburn  3993:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
1.1194    raeburn  3994: #
                   3995: # No edit allowed where CC has switched to student role.
                   3996: #
1.1507    raeburn  3997:                     return;
                   3998:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
                   3999:                          ($resurl =~ m{^/res/lib/templates/})) {
                   4000:                     return;
                   4001:                 }
1.1194    raeburn  4002:             }
                   4003:         }
                   4004:     }
                   4005: 
1.1193    raeburn  4006:     if ($file ne '') {
                   4007:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  4008:             if (&is_course_upload($file,$cnum,$cdom)) {
                   4009:                 $uploaded = 1;
                   4010:                 $incourse = 1;
1.1193    raeburn  4011:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   4012:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  4013:                     if ($env{'form.forceedit'}) {
                   4014:                         $forceview = 1;
                   4015:                     } else {
                   4016:                         $forceedit = 1;
                   4017:                     }
1.1194    raeburn  4018:                 }
                   4019:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   4020:                 $incourse = 1;
                   4021:                 if ($env{'form.forceedit'}) {
                   4022:                     $forceview = 1;
                   4023:                 } else {
                   4024:                     $forceedit = 1;
                   4025:                 }
                   4026:                 $cfile = $resurl;
1.1507    raeburn  4027:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
1.1194    raeburn  4028:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   4029:                     $incourse = 1;
                   4030:                     if ($env{'form.forceedit'}) {
                   4031:                         $forceview = 1;
                   4032:                     } else {
                   4033:                         $forceedit = 1;
                   4034:                     }
                   4035:                     $cfile = $resurl;
1.1199    raeburn  4036:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  4037:                     $incourse = 1;
                   4038:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  4039:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  4040:                     $incourse = 1;
1.1199    raeburn  4041:                     if ($env{'form.forceedit'}) {
                   4042:                         $forceview = 1;
                   4043:                     } else {
                   4044:                         $forceedit = 1;
                   4045:                     }
                   4046:                     $cfile = $resurl;
1.1419    raeburn  4047:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   4048:                     my ($map,$id,$res) = &decode_symb($symb);
                   4049:                     if ($map =~ /\.page$/) {
                   4050:                         $incourse = 1;
                   4051:                         if ($env{'form.forceedit'}) {
                   4052:                             $forceview = 1;
                   4053:                             $cfile = $map;
                   4054:                         } else {
                   4055:                             $forceedit = 1;
                   4056:                             $cfile =  '/adm/wrapper'.$resurl;
                   4057:                         }
                   4058:                     }
1.1343    raeburn  4059:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  4060:                     $incourse = 1;
                   4061:                     if ($env{'form.forceedit'}) {
                   4062:                         $forceview = 1;
                   4063:                     } else {
                   4064:                         $forceedit = 1;
                   4065:                     }
                   4066:                     $cfile = $resurl;
1.1208    raeburn  4067:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   4068:                     $incourse = 1;
                   4069:                     if ($env{'form.forceedit'}) {
                   4070:                         $forceview = 1;
                   4071:                     } else {
                   4072:                         $forceedit = 1;
                   4073:                     }
                   4074:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  4075:                 }
                   4076:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   4077:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   4078:                 if (&is_on_map($template)) { 
                   4079:                     $incourse = 1;
                   4080:                     $forceview = 1;
                   4081:                     $cfile = $template;
1.1193    raeburn  4082:                 }
1.1199    raeburn  4083:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  4084:                 $incourse = 1;
                   4085:                 if ($env{'form.forceedit'}) {
                   4086:                     $forceview = 1;
                   4087:                 } else {
                   4088:                     $forceedit = 1;
                   4089:                 }
                   4090:                 $cfile = $resurl;
1.1343    raeburn  4091:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  4092:                 $incourse = 1;
                   4093:                 if ($env{'form.forceedit'}) {
                   4094:                     $forceview = 1;
                   4095:                 } else {
                   4096:                     $forceedit = 1;
                   4097:                 }
                   4098:                 $cfile = $resurl;
1.1199    raeburn  4099:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   4100:                 $incourse = 1;
                   4101:                 $forceview = 1;
                   4102:                 if ($symb) {
                   4103:                     my ($map,$id,$res)=&decode_symb($symb);
                   4104:                     $env{'request.symb'} = $symb;
                   4105:                     $cfile = &clutter($res);
                   4106:                 } else {
                   4107:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  4108:                     my $escfile = &unescape($cfile);
1.1343    raeburn  4109:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  4110:                         $cfile = '/adm/wrapper'.$escfile;
                   4111:                     } else {
                   4112:                         $escfile =~ s{^http://}{};
                   4113:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   4114:                     }
1.1199    raeburn  4115:                 }
1.1234    raeburn  4116:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   4117:                 if ($env{'form.forceedit'}) {
                   4118:                     $forceview = 1;
                   4119:                 } else {
                   4120:                     $forceedit = 1;
                   4121:                 }
                   4122:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  4123:             }
                   4124:         }
1.1194    raeburn  4125:         if ($uploaded || $incourse) {
                   4126:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  4127:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  4128:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   4129:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   4130:             # Check that the user has permission to edit this resource
                   4131:             my $setpriv = 1;
                   4132:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   4133:             if (defined($cfudom)) {
                   4134:                 $home=&homeserver($cfuname,$cfudom);
                   4135:                 $cfile=$file;
                   4136:             }
                   4137:         }
1.1194    raeburn  4138:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   4139:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  4140:             my @ids=&current_machine_ids();
                   4141:             unless (grep(/^\Q$home\E$/,@ids)) {
                   4142:                 $switchserver=1;
                   4143:             }
                   4144:         }
                   4145:     }
1.1194    raeburn  4146:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  4147: }
                   4148: 
                   4149: sub is_course_upload {
                   4150:     my ($file,$cnum,$cdom) = @_;
                   4151:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   4152:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  4153:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   4154:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  4155:         return 1;
                   4156:     }
                   4157:     return;
                   4158: }
                   4159: 
1.1194    raeburn  4160: sub in_course {
1.1195    raeburn  4161:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   4162:     if ($hideprivileged) {
                   4163:         my $skipuser;
1.1219    raeburn  4164:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   4165:         my @possdoms = ($cdom);  
                   4166:         if ($coursehash{'checkforpriv'}) { 
                   4167:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   4168:         }
                   4169:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  4170:             $skipuser = 1;
                   4171:             if ($coursehash{'nothideprivileged'}) {
                   4172:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4173:                     my $user;
                   4174:                     if ($item =~ /:/) {
                   4175:                         $user = $item;
                   4176:                     } else {
                   4177:                         $user = join(':',split(/[\@]/,$item));
                   4178:                     }
                   4179:                     if ($user eq $uname.':'.$udom) {
                   4180:                         undef($skipuser);
                   4181:                         last;
                   4182:                     }
                   4183:                 }
                   4184:             }
                   4185:             if ($skipuser) {
                   4186:                 return 0;
                   4187:             }
                   4188:         }
                   4189:     }
1.1194    raeburn  4190:     $type ||= 'any';
                   4191:     if (!defined($cdom) || !defined($cnum)) {
                   4192:         my $cid  = $env{'request.course.id'};
                   4193:         $cdom = $env{'course.'.$cid.'.domain'};
                   4194:         $cnum = $env{'course.'.$cid.'.num'};
                   4195:     }
                   4196:     my $typesref;
1.1195    raeburn  4197:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  4198:         $typesref = ['active','previous','future'];
                   4199:     } elsif ($type eq 'previous' || $type eq 'future') {
                   4200:         $typesref = [$type];
                   4201:     }
                   4202:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   4203:                               $typesref,undef,[$cdom]);
                   4204:     my ($tmp) = keys(%roles);
                   4205:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   4206:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   4207:     if (@course_roles > 0) {
                   4208:         return 1;
                   4209:     }
                   4210:     return 0;
                   4211: }
                   4212: 
1.478     albertel 4213: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 4214: # input: action, courseID, current domain, intended
1.637     raeburn  4215: #        path to file, source of file, instruction to parse file for objects,
                   4216: #        ref to hash for embedded objects,
                   4217: #        ref to hash for codebase of java objects.
1.1095    raeburn  4218: #        reference to scalar to accommodate mime type determined
                   4219: #          from File::MMagic if $parser = parse.
1.637     raeburn  4220: #
1.485     raeburn  4221: # output: url to file (if action was uploaddoc), 
                   4222: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  4223: #
1.478     albertel 4224: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   4225: # course.
1.477     raeburn  4226: #
1.478     albertel 4227: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4228: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   4229: #          course's home server.
1.477     raeburn  4230: #
1.478     albertel 4231: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   4232: #          be copied from $source (current location) to 
                   4233: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4234: #         and will then be copied to
                   4235: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   4236: #         course's home server.
1.485     raeburn  4237: #
1.481     raeburn  4238: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 4239: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  4240: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4241: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   4242: #         in course's home server.
1.637     raeburn  4243: #
1.477     raeburn  4244: 
                   4245: sub process_coursefile {
1.1095    raeburn  4246:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   4247:         $mimetype)=@_;
1.477     raeburn  4248:     my $fetchresult;
1.638     albertel 4249:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  4250:     if ($action eq 'propagate') {
1.638     albertel 4251:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   4252: 			     $home);
1.481     raeburn  4253:     } else {
1.477     raeburn  4254:         my $fpath = '';
                   4255:         my $fname = $file;
1.478     albertel 4256:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  4257:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  4258:         my $filepath = &build_filepath($fpath);
1.481     raeburn  4259:         if ($action eq 'copy') {
                   4260:             if ($source eq '') {
                   4261:                 $fetchresult = 'no source file';
                   4262:                 return $fetchresult;
                   4263:             } else {
                   4264:                 my $destination = $filepath.'/'.$fname;
                   4265:                 rename($source,$destination);
                   4266:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4267:                                  $home);
1.481     raeburn  4268:             }
                   4269:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  4270:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 4271:             print $fh $env{'form.'.$source};
1.481     raeburn  4272:             close($fh);
1.637     raeburn  4273:             if ($parser eq 'parse') {
1.1024    raeburn  4274:                 my $mm = new File::MMagic;
1.1095    raeburn  4275:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   4276:                 if ($type eq 'text/html') {
1.1024    raeburn  4277:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   4278:                     unless ($parse_result eq 'ok') {
                   4279:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   4280:                     }
1.637     raeburn  4281:                 }
1.1095    raeburn  4282:                 if (ref($mimetype)) {
                   4283:                     $$mimetype = $type;
                   4284:                 } 
1.637     raeburn  4285:             }
1.477     raeburn  4286:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4287:                                  $home);
1.481     raeburn  4288:             if ($fetchresult eq 'ok') {
                   4289:                 return '/uploaded/'.$fpath.'/'.$fname;
                   4290:             } else {
                   4291:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4292:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  4293:                 return '/adm/notfound.html';
                   4294:             }
1.477     raeburn  4295:         }
                   4296:     }
1.485     raeburn  4297:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4298:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4299:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4300:     }
                   4301:     return $fetchresult;
                   4302: }
                   4303: 
1.637     raeburn  4304: sub build_filepath {
                   4305:     my ($fpath) = @_;
                   4306:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4307:     unless ($fpath eq '') {
                   4308:         my @parts=split('/',$fpath);
                   4309:         foreach my $part (@parts) {
                   4310:             $filepath.= '/'.$part;
                   4311:             if ((-e $filepath)!=1) {
                   4312:                 mkdir($filepath,0777);
                   4313:             }
                   4314:         }
                   4315:     }
                   4316:     return $filepath;
                   4317: }
                   4318: 
                   4319: sub store_edited_file {
1.638     albertel 4320:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4321:     my $file = $primary_url;
                   4322:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4323:     my $fpath = '';
                   4324:     my $fname = $file;
                   4325:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4326:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4327:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4328:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4329:     print $fh $content;
                   4330:     close($fh);
1.638     albertel 4331:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4332:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4333: 			  $home);
1.637     raeburn  4334:     if ($$fetchresult eq 'ok') {
                   4335:         return '/uploaded/'.$fpath.'/'.$fname;
                   4336:     } else {
1.638     albertel 4337:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4338: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4339:         return '/adm/notfound.html';
                   4340:     }
                   4341: }
                   4342: 
1.531     albertel 4343: sub clean_filename {
1.831     albertel 4344:     my ($fname,$args)=@_;
1.315     www      4345: # Replace Windows backslashes by forward slashes
1.257     www      4346:     $fname=~s/\\/\//g;
1.831     albertel 4347:     if (!$args->{'keep_path'}) {
                   4348:         # Get rid of everything but the actual filename
                   4349: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4350:     }
1.315     www      4351: # Replace spaces by underscores
                   4352:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4353: # Transliterate non-ascii text to ascii
                   4354:     my $lang = &Apache::lonlocal::current_language();
                   4355:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4356: # Replace all other weird characters by nothing
1.831     albertel 4357:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4358: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4359: # numbers
                   4360:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443    raeburn  4361: # Replace three or more adjacent underscores with one for consistency 
                   4362: # with loncfile::filename_check() so complete url can be extracted by
                   4363: # lonnet::decode_symb()
                   4364:     $fname=~s/_{3,}/_/g;
1.531     albertel 4365:     return $fname;
                   4366: }
1.1406    raeburn  4367: 
1.1051    raeburn  4368: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4369: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4370: # image with the same aspect ratio as the original, but with dimensions which do 
                   4371: # not exceed $resizewidth and $resizeheight.
                   4372:  
1.984     neumanie 4373: sub resizeImage {
1.1051    raeburn  4374:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4375:     my $ima = Image::Magick->new;
                   4376:     my $resized;
                   4377:     if (-e $img_path) {
                   4378:         $ima->Read($img_path);
                   4379:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4380:             my $width = $ima->Get('width');
                   4381:             my $height = $ima->Get('height');
                   4382:             if ($width > $resizewidth) {
                   4383: 	        my $factor = $width/$resizewidth;
                   4384:                 my $newheight = $height/$factor;
                   4385:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4386:                 $resized = 1;
                   4387:             }
                   4388:         }
                   4389:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4390:             my $width = $ima->Get('width');
                   4391:             my $height = $ima->Get('height');
                   4392:             if ($height > $resizeheight) {
                   4393:                 my $factor = $height/$resizeheight;
                   4394:                 my $newwidth = $width/$factor;
                   4395:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4396:                 $resized = 1;
                   4397:             }
                   4398:         }
                   4399:         if ($resized) {
                   4400:             $ima->Write($img_path);
                   4401:         }
                   4402:     }
                   4403:     return;
1.977     amueller 4404: }
                   4405: 
1.608     albertel 4406: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4407: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4408: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4409: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1504    raeburn  4410: #                                    canceloverwrite, scantron, toollogo  or ''.
1.1090    raeburn  4411: #                   if 'coursedoc': upload to the current course
                   4412: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4413: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4414: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4415: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4416: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4417: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4418: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4419: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4420: #        $allfiles - reference to hash for embedded objects
                   4421: #        $codebase - reference to hash for codebase of java objects
1.1504    raeburn  4422: #        $destuname - username for permanent storage of uploaded file
                   4423: #        $destudom - domain for permanaent storage of uploaded file
1.860     raeburn  4424: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4425: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4426: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4427: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4428: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4429: #                    from File::MMagic.
1.858     raeburn  4430: # 
1.686     albertel 4431: # output: url of file in userspace, or error: <message> 
                   4432: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4433: 
1.531     albertel 4434: sub userfileupload {
1.1090    raeburn  4435:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4436:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4437:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4438:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4439:     $fname=&clean_filename($fname);
1.1090    raeburn  4440:     # See if there is anything left
1.257     www      4441:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4442:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4443:     if ($fname =~ /^\./) {
                   4444:         my ($s,$usec) = &gettimeofday();
                   4445:         while (length($usec) < 6) {
                   4446:             $usec = '0'.$usec;
                   4447:         }
                   4448:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4449:     }
1.1090    raeburn  4450:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4451:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4452:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4453:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4454:         my $now = time;
1.1090    raeburn  4455:         my $filepath;
1.1095    raeburn  4456:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4457:              $filepath = 'tmp/helprequests/'.$now;
                   4458:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4459:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4460:                          '_'.$env{'user.domain'}.'/pending';
                   4461:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4462:             my ($docuname,$docudom);
1.1350    raeburn  4463:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4464:                 $docudom = $destudom;
                   4465:             } else {
                   4466:                 $docudom = $env{'user.domain'};
                   4467:             }
1.1350    raeburn  4468:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4469:                 $docuname = $destuname;
                   4470:             } else {
                   4471:                 $docuname = $env{'user.name'};
                   4472:             }
                   4473:             if (exists($env{'form.group'})) {
                   4474:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4475:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4476:             }
                   4477:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4478:             if ($context eq 'canceloverwrite') {
                   4479:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4480:                 if (-e  $tempfile) {
                   4481:                     my @info = stat($tempfile);
                   4482:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4483:                         unlink($tempfile);
                   4484:                     }
                   4485:                 }
                   4486:                 return;
1.523     raeburn  4487:             }
                   4488:         }
1.1090    raeburn  4489:         # Create the directory if not present
1.741     raeburn  4490:         my @parts=split(/\//,$filepath);
                   4491:         my $fullpath = $perlvar{'lonDaemons'};
                   4492:         for (my $i=0;$i<@parts;$i++) {
                   4493:             $fullpath .= '/'.$parts[$i];
                   4494:             if ((-e $fullpath)!=1) {
                   4495:                 mkdir($fullpath,0777);
                   4496:             }
                   4497:         }
1.1359    raeburn  4498:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4499:         print $fh $env{'form.'.$formname};
                   4500:         close($fh);
1.1090    raeburn  4501:         if ($context eq 'existingfile') {
                   4502:             my @info = stat($fullpath.'/'.$fname);
                   4503:             return ($fullpath.'/'.$fname,$info[9]);
                   4504:         } else {
                   4505:             return $fullpath.'/'.$fname;
                   4506:         }
1.523     raeburn  4507:     }
1.995     raeburn  4508:     if ($subdir eq 'scantron') {
                   4509:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4510:     } else {
1.995     raeburn  4511:         $fname="$subdir/$fname";
                   4512:     }
1.1090    raeburn  4513:     if ($context eq 'coursedoc') {
1.638     albertel 4514: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4515: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4516:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4517:             return &finishuserfileupload($docuname,$docudom,
                   4518: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4519: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4520:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4521:         } else {
1.1218    raeburn  4522:             if ($env{'form.folder'}) {
                   4523:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4524:             }
1.638     albertel 4525:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4526: 				       $fname,$formname,$parser,
1.1095    raeburn  4527: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4528:         }
1.719     banghart 4529:     } elsif (defined($destuname)) {
                   4530:         my $docuname=$destuname;
                   4531:         my $docudom=$destudom;
1.860     raeburn  4532: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4533: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4534:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4535:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4536:     } else {
1.638     albertel 4537:         my $docuname=$env{'user.name'};
                   4538:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4539:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4540:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4541:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4542:         }
1.860     raeburn  4543: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4544: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4545:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4546:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4547:     }
1.271     www      4548: }
                   4549: 
                   4550: sub finishuserfileupload {
1.860     raeburn  4551:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4552:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4553:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4554:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4555:   
1.860     raeburn  4556:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4557:     $file=$fname;
                   4558:     if ($fname=~m|/|) {
                   4559:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4560: 	$path.=$fnamepath.'/';
                   4561:     }
1.259     www      4562:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4563:     my $count;
                   4564:     for ($count=4;$count<=$#parts;$count++) {
                   4565:         $filepath.="/$parts[$count]";
                   4566:         if ((-e $filepath)!=1) {
                   4567: 	    mkdir($filepath,0777);
                   4568:         }
                   4569:     }
1.984     neumanie 4570: 
1.258     www      4571: # Save the file
                   4572:     {
1.1359    raeburn  4573: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4574: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4575: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4576: 	    return '/adm/notfound.html';
                   4577: 	}
1.1090    raeburn  4578:         if ($context eq 'overwrite') {
1.1117    foxr     4579:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4580:             my $target = $filepath.'/'.$file;
                   4581:             if (-e $source) {
                   4582:                 my @info = stat($source);
                   4583:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4584:                     unless (&File::Copy::move($source,$target)) {
                   4585:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4586:                         return "Moving from $source failed";
                   4587:                     }
                   4588:                 } else {
                   4589:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4590:                 }
                   4591:             } else {
                   4592:                 return "Temporary file: $source missing";
                   4593:             }
                   4594:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4595: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4596: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4597: 	    return '/adm/notfound.html';
                   4598: 	}
1.570     albertel 4599: 	close(FH);
1.1051    raeburn  4600:         if ($resizewidth && $resizeheight) {
                   4601:             my $mm = new File::MMagic;
                   4602:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4603:             if ($mime_type =~ m{^image/}) {
                   4604: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4605:             }  
1.977     amueller 4606: 	}
1.258     www      4607:     }
1.1152    raeburn  4608:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4609:         if (ref($mimetype)) {
                   4610:             if ($$mimetype eq '') {
                   4611:                 my $mm = new File::MMagic;
                   4612:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4613:                 $$mimetype = $type;
                   4614:             }
                   4615:         }
                   4616:     }
1.1401    raeburn  4617:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4618:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4619:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4620:                                                        $allfiles,$codebase);
                   4621:             unless ($parse_result eq 'ok') {
                   4622:                 &logthis('Failed to parse '.$filepath.$file.
                   4623: 	   	         ' for embedded media: '.$parse_result); 
                   4624:             }
1.637     raeburn  4625:         }
1.1401    raeburn  4626:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4627:         my $format = $env{'form.scantron_format'};
                   4628:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4629:     }
1.860     raeburn  4630:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4631:         my $input = $filepath.'/'.$file;
                   4632:         my $output = $filepath.'/'.'tn-'.$file;
1.1504    raeburn  4633:         my $makethumb; 
1.860     raeburn  4634:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1504    raeburn  4635:         if ($context eq 'toollogo') {
                   4636:             my ($fullwidth,$fullheight) = &check_dimensions($input);
                   4637:             if ($fullwidth ne '' && $fullheight ne '') {
                   4638:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
                   4639:                     $makethumb = 1;
                   4640:                 }
                   4641:             }
                   4642:         } else {
                   4643:             $makethumb = 1;
                   4644:         }
                   4645:         if ($makethumb) {
                   4646:             my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4647:             system({$args[0]} @args);
                   4648:             if (-e $filepath.'/'.'tn-'.$file) {
                   4649:                 $fetchthumb  = 1; 
                   4650:             }
1.860     raeburn  4651:         }
                   4652:     }
1.858     raeburn  4653:  
1.259     www      4654: # Notify homeserver to grep it
                   4655: #
1.984     neumanie 4656:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4657:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4658:     if ($fetchresult eq 'ok') {
1.860     raeburn  4659:         if ($fetchthumb) {
                   4660:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4661:             if ($thumbresult ne 'ok') {
                   4662:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4663:                          $docuhome.': '.$thumbresult);
                   4664:             }
                   4665:         }
1.259     www      4666: #
1.258     www      4667: # Return the URL to it
1.494     albertel 4668:         return '/uploaded/'.$path.$file;
1.263     www      4669:     } else {
1.494     albertel 4670:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4671: 		 ': '.$fetchresult);
1.263     www      4672:         return '/adm/notfound.html';
1.858     raeburn  4673:     }
1.493     albertel 4674: }
                   4675: 
1.637     raeburn  4676: sub extract_embedded_items {
1.961     raeburn  4677:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4678:     my @state = ();
1.1164    raeburn  4679:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4680:     my %javafiles = (
                   4681:                       codebase => '',
                   4682:                       code => '',
                   4683:                       archive => ''
                   4684:                     );
                   4685:     my %mediafiles = (
                   4686:                       src => '',
                   4687:                       movie => '',
                   4688:                      );
1.648     raeburn  4689:     my $p;
                   4690:     if ($content) {
                   4691:         $p = HTML::LCParser->new($content);
                   4692:     } else {
1.961     raeburn  4693:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4694:     }
1.641     albertel 4695:     while (my $t=$p->get_token()) {
1.640     albertel 4696: 	if ($t->[0] eq 'S') {
                   4697: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4698: 	    push(@state, $tagname);
1.648     raeburn  4699:             if (lc($tagname) eq 'allow') {
                   4700:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4701:             }
1.640     albertel 4702: 	    if (lc($tagname) eq 'img') {
                   4703: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4704: 	    }
1.886     albertel 4705: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4706:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4707:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4708:                 }
1.886     albertel 4709: 	    }
1.645     raeburn  4710:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4711:                 my $src;
1.645     raeburn  4712:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4713:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4714:                 } else {
1.1164    raeburn  4715:                     if ($attr->{'src'} ne '') {
                   4716:                         $src = $attr->{'src'};
                   4717:                         &add_filetype($allfiles,$src,'src');
                   4718:                     }
                   4719:                 }
                   4720:                 my $text = $p->get_trimmed_text();
                   4721:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4722:                     my @swfargs = split(/,/,$1);
                   4723:                     foreach my $item (@swfargs) {
                   4724:                         $item =~ s/["']//g;
                   4725:                         $item =~ s/^\s+//;
                   4726:                         $item =~ s/\s+$//;
                   4727:                     }
                   4728:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4729:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4730:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4731:                         } else {
                   4732:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4733:                         }
                   4734:                     }
1.645     raeburn  4735:                 }
                   4736:             }
                   4737:             if (lc($tagname) eq 'link') {
                   4738:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4739:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4740:                 }
                   4741:             }
1.640     albertel 4742: 	    if (lc($tagname) eq 'object' ||
                   4743: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4744: 		foreach my $item (keys(%javafiles)) {
                   4745: 		    $javafiles{$item} = '';
                   4746: 		}
1.1164    raeburn  4747:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4748:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4749:                 }
1.640     albertel 4750: 	    }
                   4751: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4752: 		my $name = lc($attr->{'name'});
                   4753: 		foreach my $item (keys(%javafiles)) {
                   4754: 		    if ($name eq $item) {
                   4755: 			$javafiles{$item} = $attr->{'value'};
                   4756: 			last;
                   4757: 		    }
                   4758: 		}
1.1164    raeburn  4759:                 my $pathfrom;
1.640     albertel 4760: 		foreach my $item (keys(%mediafiles)) {
                   4761: 		    if ($name eq $item) {
1.1164    raeburn  4762:                         $pathfrom = $attr->{'value'};
                   4763:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4764: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4765: 			last;
                   4766: 		    }
                   4767: 		}
1.1164    raeburn  4768:                 if ($name eq 'flashvars') {
                   4769:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4770:                 }
                   4771:                 if ($pathfrom ne '') {
                   4772:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4773:                                          $pathfrom);
                   4774:                 }
1.640     albertel 4775: 	    }
                   4776: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4777: 		foreach my $item (keys(%javafiles)) {
                   4778: 		    if ($attr->{$item}) {
                   4779: 			$javafiles{$item} = $attr->{$item};
                   4780: 			last;
                   4781: 		    }
                   4782: 		}
                   4783: 		foreach my $item (keys(%mediafiles)) {
                   4784: 		    if ($attr->{$item}) {
                   4785: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4786: 			last;
                   4787: 		    }
                   4788: 		}
1.1164    raeburn  4789:                 if (lc($tagname) eq 'embed') {
                   4790:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4791:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4792:                                              $attr->{'src'});
                   4793:                     }
                   4794:                 }
1.640     albertel 4795: 	    }
1.1243    raeburn  4796:             if (lc($tagname) eq 'iframe') {
                   4797:                 my $src = $attr->{'src'} ;
                   4798:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4799:                     &add_filetype($allfiles,$src,'src');
                   4800:                 } elsif ($src =~ m{^/}) {
                   4801:                     if ($env{'request.course.id'}) {
                   4802:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4803:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4804:                         my $url = &hreflocation('',$fullpath);
                   4805:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4806:                             my $relpath = $1;
                   4807:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4808:                                 &add_filetype($allfiles,$1,'src');
                   4809:                             }
                   4810:                         }
                   4811:                     }
                   4812:                 }
                   4813:             }
1.1164    raeburn  4814:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4815:                 pop(@state);
1.1164    raeburn  4816:             }
1.640     albertel 4817: 	} elsif ($t->[0] eq 'E') {
                   4818: 	    my ($tagname) = ($t->[1]);
                   4819: 	    if ($javafiles{'codebase'} ne '') {
                   4820: 		$javafiles{'codebase'} .= '/';
                   4821: 	    }  
                   4822: 	    if (lc($tagname) eq 'applet' ||
                   4823: 		lc($tagname) eq 'object' ||
                   4824: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4825: 		) {
                   4826: 		foreach my $item (keys(%javafiles)) {
                   4827: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4828: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4829: 			&add_filetype($allfiles,$file,$item);
                   4830: 		    }
                   4831: 		}
                   4832: 	    } 
                   4833: 	    pop @state;
                   4834: 	}
                   4835:     }
1.1164    raeburn  4836:     foreach my $id (sort(keys(%flashvars))) {
                   4837:         if ($shockwave{$id} ne '') {
                   4838:             my @pairs = split(/\&/,$flashvars{$id});
                   4839:             foreach my $pair (@pairs) {
                   4840:                 my ($key,$value) = split(/\=/,$pair);
                   4841:                 if ($key eq 'thumb') {
                   4842:                     &add_filetype($allfiles,$value,$key);
                   4843:                 } elsif ($key eq 'content') {
                   4844:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4845:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4846:                     if ($ext ne '') {
                   4847:                         &add_filetype($allfiles,$path.$value,$ext);
                   4848:                     }
                   4849:                 }
                   4850:             }
                   4851:         }
                   4852:     }
1.637     raeburn  4853:     return 'ok';
                   4854: }
                   4855: 
1.639     albertel 4856: sub add_filetype {
                   4857:     my ($allfiles,$file,$type)=@_;
                   4858:     if (exists($allfiles->{$file})) {
                   4859: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4860: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4861: 	}
                   4862:     } else {
                   4863: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4864:     }
                   4865: }
                   4866: 
1.1164    raeburn  4867: sub embedded_dependency {
                   4868:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4869:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4870:         if (($identifier ne '') &&
                   4871:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4872:             ($pathfrom ne '')) {
                   4873:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4874:             foreach my $dep (@{$related->{$identifier}}) {
                   4875:                 &add_filetype($allfiles,$path.$dep,'object');
                   4876:             }
                   4877:         }
                   4878:     }
                   4879:     return;
                   4880: }
                   4881: 
1.1504    raeburn  4882: sub check_dimensions {
                   4883:     my ($inputfile) = @_;
                   4884:     my ($fullwidth,$fullheight);
                   4885:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
                   4886:         my $mm = new File::MMagic;
                   4887:         my $mime_type = $mm->checktype_filename($inputfile);
                   4888:         if ($mime_type =~ m{^image/}) {
                   4889:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
                   4890:                 my $imageinfo = <PIPE>;
                   4891:                 if (!close(PIPE)) {
                   4892:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
                   4893:                 }
                   4894:                 chomp($imageinfo);
                   4895:                 my ($fullsize) =
                   4896:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
                   4897:                 if ($fullsize) {
                   4898:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
                   4899:                 }
                   4900:             }
                   4901:         }
                   4902:     }
                   4903:     return ($fullwidth,$fullheight);
                   4904: }
                   4905: 
1.1401    raeburn  4906: sub bubblesheet_converter {
                   4907:     my ($cdom,$fullpath,$config,$format) = @_;
                   4908:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4909:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4910:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4911:         my (%csvcols,%csvoptions);
                   4912:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4913:             %csvcols = %{$config->{'fields'}};
                   4914:         }
                   4915:         if (ref($config->{'options'}) eq 'HASH') {
                   4916:             %csvoptions = %{$config->{'options'}};
                   4917:         }
1.1401    raeburn  4918:         my %csvbynum = reverse(%csvcols);
                   4919:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4920:         if (keys(%scantronconf)) {
                   4921:             my %bynum = (
                   4922:                           $scantronconf{CODEstart} => 'CODEstart',
                   4923:                           $scantronconf{IDstart}   => 'IDstart',
                   4924:                           $scantronconf{PaperID}   => 'PaperID',
                   4925:                           $scantronconf{FirstName} => 'FirstName',
                   4926:                           $scantronconf{LastName}  => 'LastName',
                   4927:                           $scantronconf{Qstart}    => 'Qstart',
                   4928:                         );
                   4929:             my @ordered;
                   4930:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4931:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4932:             }
                   4933:             my %mapstart = (
                   4934:                               CODEstart => 'CODE',
                   4935:                               IDstart   => 'ID',
                   4936:                               PaperID   => 'PaperID',
                   4937:                               FirstName => 'FirstName',
                   4938:                               LastName  => 'LastName',
                   4939:                               Qstart    => 'FirstQuestion',
                   4940:                            );
                   4941:             my %maplength = (
                   4942:                               CODEstart => 'CODElength',
                   4943:                               IDstart   => 'IDlength',
                   4944:                               PaperID   => 'PaperIDlength',
                   4945:                               FirstName => 'FirstNamelength',
                   4946:                               LastName  => 'LastNamelength',
                   4947:             );
                   4948:             if (open(my $fh,'<',$fullpath)) {
                   4949:                 my $output;
1.1403    raeburn  4950:                 my %lettdig = &letter_to_digits();
                   4951:                 my %diglett = reverse(%lettdig);
                   4952:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4953:                 my $num = 0;
1.1401    raeburn  4954:                 while (my $line=<$fh>) {
1.1404    raeburn  4955:                     $num ++;
                   4956:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4957:                     $line =~ s{[\r\n]+$}{};
                   4958:                     my %found;
1.1475    raeburn  4959:                     my @values = split(/,/,$line,-1);
1.1401    raeburn  4960:                     my ($qstart,$record);
                   4961:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4962:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4963:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4964:                             if ($values[$i] eq '') {
                   4965:                                 $values[$i] = $scantronconf{'Qoff'};
                   4966:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4967:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4968:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4969:                                 }
                   4970:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4971:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4972:                                     $values[$i] = $diglett{$values[$i]};
                   4973:                                 }
                   4974:                             } else {
                   4975:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4976:                                     my $digit;
                   4977:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4978:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4979:                                         if ($values[$i] eq 'J') {
                   4980:                                             $digit += $numletts;
                   4981:                                         }
                   4982:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4983:                                         $digit = $values[$i]-1;
                   4984:                                         if ($values[$i] eq '0') {
                   4985:                                             $digit += $numletts;
                   4986:                                         }
                   4987:                                     }
                   4988:                                     my $qval='';
                   4989:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4990:                                         if ($j == $digit) {
                   4991:                                             $qval .= $scantronconf{'Qon'};
                   4992:                                         } else {
                   4993:                                             $qval .= $scantronconf{'Qoff'};
                   4994:                                         }
                   4995:                                     }
                   4996:                                     $values[$i] = $qval;
                   4997:                                 }
                   4998:                             }
                   4999:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   5000:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   5001:                             }
                   5002:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   5003:                             if ($numblank > 0) {
                   5004:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   5005:                             }
1.1401    raeburn  5006:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   5007:                                 $qstart = $i;
1.1403    raeburn  5008:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  5009:                             } else {
1.1403    raeburn  5010:                                 $found{'FirstQuestion'} .= $values[$i];
                   5011:                             }
                   5012:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  5013:                             if ($csvoptions{'rem'}) {
                   5014:                                 $values[$i] =~ s/^\s+//;
                   5015:                             }
                   5016:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  5017:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   5018:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  5019:                                 }
                   5020:                             }
                   5021:                             $found{$csvbynum{$i}} = $values[$i];
                   5022:                         }
                   5023:                     }
                   5024:                     foreach my $item (@ordered) {
                   5025:                         my $currlength = 1+length($record);
                   5026:                         my $numspaces = $scantronconf{$item} - $currlength;
                   5027:                         if ($numspaces > 0) {
                   5028:                             $record .= (' ' x $numspaces);
                   5029:                         }
                   5030:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   5031:                             unless ($item eq 'Qstart') {
                   5032:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   5033:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   5034:                                 }
                   5035:                             }
                   5036:                             $record .= $found{$mapstart{$item}};
                   5037:                         }
                   5038:                     }
                   5039:                     $output .= "$record\n";
                   5040:                 }
                   5041:                 close($fh);
                   5042:                 if ($output) {
                   5043:                     if (open(my $fh,'>',$fullpath)) {
                   5044:                         print $fh $output;
                   5045:                         close($fh);
                   5046:                     }
                   5047:                 }
                   5048:             }
                   5049:         }
                   5050:         return;
                   5051:     }
                   5052: }
                   5053: 
1.1403    raeburn  5054: sub letter_to_digits {
                   5055:     my %lettdig = (
                   5056:                     A => 1,
                   5057:                     B => 2,
                   5058:                     C => 3,
                   5059:                     D => 4,
                   5060:                     E => 5,
                   5061:                     F => 6,
                   5062:                     G => 7,
                   5063:                     H => 8,
                   5064:                     I => 9,
                   5065:                     J => 0,
                   5066:                   );
                   5067:     return %lettdig;
                   5068: }
                   5069: 
1.1401    raeburn  5070: sub get_scantron_config {
                   5071:     my ($which,$cdom) = @_;
                   5072:     my @lines = &get_scantronformat_file($cdom);
                   5073:     my %config;
                   5074:     #FIXME probably should move to XML it has already gotten a bit much now
                   5075:     foreach my $line (@lines) {
                   5076:         my ($name,$descrip)=split(/:/,$line);
                   5077:         if ($name ne $which ) { next; }
                   5078:         chomp($line);
                   5079:         my @config=split(/:/,$line);
                   5080:         $config{'name'}=$config[0];
                   5081:         $config{'description'}=$config[1];
                   5082:         $config{'CODElocation'}=$config[2];
                   5083:         $config{'CODEstart'}=$config[3];
                   5084:         $config{'CODElength'}=$config[4];
                   5085:         $config{'IDstart'}=$config[5];
                   5086:         $config{'IDlength'}=$config[6];
                   5087:         $config{'Qstart'}=$config[7];
                   5088:         $config{'Qlength'}=$config[8];
                   5089:         $config{'Qoff'}=$config[9];
                   5090:         $config{'Qon'}=$config[10];
                   5091:         $config{'PaperID'}=$config[11];
                   5092:         $config{'PaperIDlength'}=$config[12];
                   5093:         $config{'FirstName'}=$config[13];
                   5094:         $config{'FirstNamelength'}=$config[14];
                   5095:         $config{'LastName'}=$config[15];
                   5096:         $config{'LastNamelength'}=$config[16];
                   5097:         $config{'BubblesPerRow'}=$config[17];
                   5098:         last;
                   5099:     }
                   5100:     return %config;
                   5101: }
                   5102: 
                   5103: sub get_scantronformat_file {
                   5104:     my ($cdom) = @_;
                   5105:     if ($cdom eq '') {
                   5106:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5107:     }
                   5108:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   5109:     my $gottab = 0;
                   5110:     my @lines;
                   5111:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5112:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5113:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5114:             if ($formatfile ne '-1') {
                   5115:                 @lines = split("\n",$formatfile,-1);
                   5116:                 $gottab = 1;
                   5117:             }
                   5118:         }
                   5119:     }
                   5120:     if (!$gottab) {
                   5121:         my $confname = $cdom.'-domainconfig';
                   5122:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5123:         my $formatfile = &getfile($default);
                   5124:         if ($formatfile ne '-1') {
                   5125:             @lines = split("\n",$formatfile,-1);
                   5126:             $gottab = 1;
                   5127:         }
                   5128:     }
                   5129:     if (!$gottab) {
                   5130:         my @domains = &current_machine_domains();
                   5131:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5132:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   5133:                 @lines = <$fh>;
                   5134:                 close($fh);
1.1403    raeburn  5135:             }
1.1401    raeburn  5136:         } else {
                   5137:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   5138:                 @lines = <$fh>;
                   5139:                 close($fh);
                   5140:             }
                   5141:         }
1.1488    raeburn  5142:         chomp(@lines);
1.1401    raeburn  5143:     }
                   5144:     return @lines;
                   5145: }
                   5146: 
1.493     albertel 5147: sub removeuploadedurl {
1.984     neumanie 5148:     my ($url)=@_;	
                   5149:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 5150:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 5151: }
                   5152: 
                   5153: sub removeuserfile {
                   5154:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 5155:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  5156:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 5157:     if ($result eq 'ok') {	
1.798     raeburn  5158:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   5159:             my $metafile = $fname.'.meta';
                   5160:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 5161: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 5162:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  5163:             my $sqlresult = 
1.823     albertel 5164:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  5165:                                         'portfolio_metadata',$group,
                   5166:                                         'delete');
1.798     raeburn  5167:         }
                   5168:     }
                   5169:     return $result;
1.257     www      5170: }
1.15      www      5171: 
1.530     albertel 5172: sub mkdiruserfile {
                   5173:     my ($docuname,$docudom,$dir)=@_;
                   5174:     my $home=&homeserver($docuname,$docudom);
                   5175:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   5176: }
                   5177: 
1.531     albertel 5178: sub renameuserfile {
                   5179:     my ($docuname,$docudom,$old,$new)=@_;
                   5180:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  5181:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   5182:                         &escape("$old").':'.&escape("$new"),$home);
                   5183:     if ($result eq 'ok') {
                   5184:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   5185:             my $oldmeta = $old.'.meta';
                   5186:             my $newmeta = $new.'.meta';
                   5187:             my $metaresult = 
                   5188:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 5189: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   5190:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  5191:             my $sqlresult = 
1.823     albertel 5192:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  5193:                                         'portfolio_metadata',$group,
                   5194:                                         'delete');
1.798     raeburn  5195:         }
                   5196:     }
                   5197:     return $result;
1.531     albertel 5198: }
                   5199: 
1.14      www      5200: # ------------------------------------------------------------------------- Log
                   5201: 
                   5202: sub log {
                   5203:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      5204:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      5205: }
                   5206: 
                   5207: # ------------------------------------------------------------------ Course Log
1.352     www      5208: #
                   5209: # This routine flushes several buffers of non-mission-critical nature
                   5210: #
1.157     www      5211: 
                   5212: sub flushcourselogs {
1.352     www      5213:     &logthis('Flushing log buffers');
                   5214: #
                   5215: # course logs
                   5216: # This is a log of all transactions in a course, which can be used
                   5217: # for data mining purposes
                   5218: #
                   5219: # It also collects the courseid database, which lists last transaction
                   5220: # times and course titles for all courseids
                   5221: #
                   5222:     my %courseidbuffer=();
1.921     raeburn  5223:     foreach my $crsid (keys(%courselogs)) {
1.352     www      5224:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      5225: 		          &escape($courselogs{$crsid}),
                   5226: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      5227: 	    delete $courselogs{$crsid};
                   5228:         } else {
                   5229:             &logthis('Failed to flush log buffer for '.$crsid);
                   5230:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 5231:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      5232:                         " exceeded maximum size, deleting.</font>");
                   5233:                delete $courselogs{$crsid};
                   5234:             }
1.352     www      5235:         }
1.920     raeburn  5236:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  5237:             'description' => $coursedescrbuf{$crsid},
                   5238:             'inst_code'    => $courseinstcodebuf{$crsid},
                   5239:             'type'        => $coursetypebuf{$crsid},
                   5240:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  5241:         };
1.191     harris41 5242:     }
1.352     www      5243: #
                   5244: # Write course id database (reverse lookup) to homeserver of courses 
                   5245: # Is used in pickcourse
                   5246: #
1.840     albertel 5247:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  5248:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  5249:                                     $courseidbuffer{$crs_home},
                   5250:                                     $crs_home,'timeonly');
1.352     www      5251:     }
                   5252: #
                   5253: # File accesses
                   5254: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   5255: #
1.449     matthew  5256:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  5257:         if ($entry =~ /___count$/) {
                   5258:             my ($dom,$name);
1.807     albertel 5259:             ($dom,$name,undef)=
1.811     albertel 5260: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  5261:             if (! defined($dom) || $dom eq '' || 
                   5262:                 ! defined($name) || $name eq '') {
1.620     albertel 5263:                 my $cid = $env{'request.course.id'};
1.1472    raeburn  5264: #
                   5265: # FIXME 11/29/2021
                   5266: # Typo in rev. 1.458 (2003/12/09)??
                   5267: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   5268: #
1.1509    raeburn  5269: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1472    raeburn  5270: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   5271: # in a nohist_accesscount.db file for the user rather than the course.
                   5272: #
                   5273: # That said there is a lot of noise in the data being stored.
                   5274: # So counts for prtspool/  and adm/ etc. are recorded.
                   5275: #
                   5276: # A review of which items ending '___count' are written to %accesshash should likely be 
                   5277: # made before deciding whether to set these to 'course.' instead of 'request.'
                   5278: #
                   5279: # Under the current scheme each user receives a nohist_accesscount.db file listing 
                   5280: # accesses for things which are not published resources, regardless of course, and
                   5281: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   5282: # anyone in the course for things which are not published resources.
                   5283: #
                   5284: # For an author, nohist_accesscount.db ends up having records for other items
                   5285: # mixed up with the legitimate access counts for the author's published resources.
                   5286: #
1.620     albertel 5287:                 $dom  = $env{'request.'.$cid.'.domain'};
                   5288:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  5289:             }
1.450     matthew  5290:             my $value = $accesshash{$entry};
                   5291:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   5292:             my %temphash=($url => $value);
1.449     matthew  5293:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   5294:             if ($result eq 'ok') {
                   5295:                 delete $accesshash{$entry};
                   5296:             }
                   5297:         } else {
1.811     albertel 5298:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      5299:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  5300:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  5301:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   5302:                 delete $accesshash{$entry};
                   5303:             }
1.185     www      5304:         }
1.191     harris41 5305:     }
1.352     www      5306: #
                   5307: # Roles
                   5308: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   5309: #
1.800     albertel 5310:     foreach my $entry (keys(%userrolehash)) {
1.351     www      5311:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      5312: 	    split(/\:/,$entry);
1.1494    raeburn  5313:         if (&put('nohist_userroles',
1.351     www      5314:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      5315:                 $rudom,$runame) eq 'ok') {
                   5316: 	    delete $userrolehash{$entry};
                   5317:         }
                   5318:     }
1.662     raeburn  5319: #
1.1334    raeburn  5320: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5321: #
                   5322:     my %domrolebuffer = ();
1.1000    raeburn  5323:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5324:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5325:         if ($domrolebuffer{$rudom}) {
                   5326:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5327:                       '='.&escape($domainrolehash{$entry});
                   5328:         } else {
                   5329:             $domrolebuffer{$rudom}.=&escape($entry).
                   5330:                       '='.&escape($domainrolehash{$entry});
                   5331:         }
                   5332:         delete $domainrolehash{$entry};
                   5333:     }
                   5334:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  5335: 	my %servers;
                   5336: 	if (defined(&domain($dom,'primary'))) {
                   5337: 	    my $primary=&domain($dom,'primary');
                   5338: 	    my $hostname=&hostname($primary);
                   5339: 	    $servers{$primary} = $hostname;
                   5340: 	} else { 
                   5341: 	    %servers = &get_servers($dom,'library');
                   5342: 	}
1.841     albertel 5343: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  5344: 	    if (&reply('domroleput:'.$dom.':'.
                   5345: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5346: 		last;
                   5347: 	    } else {  
1.841     albertel 5348: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5349: 	    }
1.662     raeburn  5350:         }
                   5351:     }
1.186     www      5352:     $dumpcount++;
1.157     www      5353: }
                   5354: 
                   5355: sub courselog {
                   5356:     my $what=shift;
1.158     www      5357:     $what=time.':'.$what;
1.620     albertel 5358:     unless ($env{'request.course.id'}) { return ''; }
                   5359:     $coursedombuf{$env{'request.course.id'}}=
                   5360:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5361:     $coursenumbuf{$env{'request.course.id'}}=
                   5362:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5363:     $coursehombuf{$env{'request.course.id'}}=
                   5364:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5365:     $coursedescrbuf{$env{'request.course.id'}}=
                   5366:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5367:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5368:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5369:     $courseownerbuf{$env{'request.course.id'}}=
                   5370:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5371:     $coursetypebuf{$env{'request.course.id'}}=
                   5372:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5373:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5374: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5375:     } else {
1.620     albertel 5376: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5377:     }
1.620     albertel 5378:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5379: 	&flushcourselogs();
                   5380:     }
1.158     www      5381: }
                   5382: 
                   5383: sub courseacclog {
                   5384:     my $fnsymb=shift;
1.620     albertel 5385:     unless ($env{'request.course.id'}) { return ''; }
                   5386:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5387:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5388:         $what.=':POST';
1.583     matthew  5389:         # FIXME: Probably ought to escape things....
1.800     albertel 5390: 	foreach my $key (keys(%env)) {
                   5391:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5392:                 my $formitem = $1;
                   5393:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5394:                     $what.=':'.$formitem.'='.$env{$key};
                   5395:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5396:                     if ($formitem eq 'proctorpassword') {
1.1433    raeburn  5397:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5398:                     } else {
                   5399:                         $what.=':'.$formitem.'='.$env{$key};
                   5400:                     }
1.975     raeburn  5401:                 }
1.158     www      5402:             }
1.191     harris41 5403:         }
1.583     matthew  5404:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5405:         # FIXME: We should not be depending on a form parameter that someone
                   5406:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5407:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5408:             $what.= ':POST';
                   5409:             # FIXME: Probably ought to escape things....
                   5410:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5411:                                  'crsdiscuss') {
1.620     albertel 5412:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5413:             }
                   5414:         }
1.158     www      5415:     }
                   5416:     &courselog($what);
1.149     www      5417: }
                   5418: 
1.185     www      5419: sub countacc {
                   5420:     my $url=&declutter(shift);
1.458     matthew  5421:     return if (! defined($url) || $url eq '');
1.620     albertel 5422:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5423: #
                   5424: # Mark that this url was used in this course
                   5425: #
1.620     albertel 5426:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5427: #
                   5428: # Increase the access count for this resource in this child process
                   5429: #
1.281     www      5430:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5431:     $accesshash{$key}++;
1.185     www      5432: }
1.349     www      5433: 
1.361     www      5434: sub linklog {
                   5435:     my ($from,$to)=@_;
                   5436:     $from=&declutter($from);
                   5437:     $to=&declutter($to);
                   5438:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5439:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5440: }
1.1160    www      5441: 
                   5442: sub statslog {
                   5443:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5444:     if ($users<2) { return; }
                   5445:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5446:             'course'       => $env{'request.course.id'},
                   5447:             'sections'     => '"all"',
                   5448:             'num_students' => $users,
                   5449:             'part'         => $part,
                   5450:             'symb'         => $symb,
                   5451:             'mean_tries'   => $av_attempts,
                   5452:             'deg_of_diff'  => $degdiff});
                   5453:     foreach my $key (keys(%dynstore)) {
                   5454:         $accesshash{$key}=$dynstore{$key};
                   5455:     }
                   5456: }
1.361     www      5457:   
1.349     www      5458: sub userrolelog {
                   5459:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5460:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5461:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5462:        $userrolehash
                   5463:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5464:                     =$tend.':'.$tstart;
1.662     raeburn  5465:     }
1.1169    droeschl 5466:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5467:        $userrolehash
                   5468:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5469:                     =$tend.':'.$tstart;
                   5470:     }
1.1334    raeburn  5471:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5472:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5473:        $domainrolehash
                   5474:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5475:                     = $tend.':'.$tstart;
                   5476:     }
1.351     www      5477: }
                   5478: 
1.957     raeburn  5479: sub courserolelog {
1.1512    raeburn  5480:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
                   5481:         $context,$othdomby,$requester)=@_;
1.1184    raeburn  5482:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5483:         my $cdom = $1;
                   5484:         my $cnum = $2;
                   5485:         my $sec = $3;
                   5486:         my $namespace = 'rolelog';
                   5487:         my %storehash = (
                   5488:                            role    => $trole,
                   5489:                            start   => $tstart,
                   5490:                            end     => $tend,
                   5491:                            selfenroll => $selfenroll,
                   5492:                            context    => $context,
                   5493:                         );
1.1512    raeburn  5494:         if ($othdomby) {
                   5495:             if ($othdomby eq 'othdombydc') {
                   5496:                 $storehash{'approval'} = 'domain';
                   5497:             } elsif ($othdomby eq 'othdombyuser') {
                   5498:                 $storehash{'approval'} = 'user'; 
                   5499:             }
                   5500:             if ($requester ne '') {
                   5501:                 $storehash{'requester'} = $requester;
                   5502:             }
                   5503:         }
1.1184    raeburn  5504:         if ($trole eq 'gr') {
                   5505:             $namespace = 'groupslog';
                   5506:             $storehash{'group'} = $sec;
                   5507:         } else {
                   5508:             $storehash{'section'} = $sec;
1.1516    raeburn  5509:             my ($curruserdomstr,$newuserdomstr);
1.1515    raeburn  5510:             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
                   5511:                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
1.1516    raeburn  5512:             } else {
1.1515    raeburn  5513:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
                   5514:                 $curruserdomstr = $courseinfo{'internal.userdomains'};
                   5515:             }
1.1516    raeburn  5516:             if ($curruserdomstr ne '') {
                   5517:                 my @udoms = split(/,/,$curruserdomstr);
1.1515    raeburn  5518:                 unless (grep(/^\Q$domain\E/,@udoms)) {
                   5519:                     push(@udoms,$domain);
                   5520:                     $newuserdomstr = join(',',sort(@udoms));
                   5521:                 }
                   5522:             } else {
                   5523:                 $newuserdomstr = $domain;
                   5524:             }
                   5525:             if ($newuserdomstr ne '') {
                   5526:                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
                   5527:                                      $cdom,$cnum);
                   5528:                 if ($putresult eq 'ok') {
                   5529:                     unless (($selfenroll) || ($context eq 'selfenroll')) { 
                   5530:                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
                   5531:                             ($context eq 'automated') || ($context eq 'domain')) {
                   5532:                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
                   5533:                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   5534:                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
                   5535:                         }
                   5536:                     }
                   5537:                 }
                   5538:             }
1.1184    raeburn  5539:         }
1.1188    raeburn  5540:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5541:                    $domain,$cnum,$cdom);
1.1184    raeburn  5542:         if (($trole ne 'st') || ($sec ne '')) {
                   5543:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5544:         }
                   5545:     }
                   5546:     return;
                   5547: }
                   5548: 
1.1184    raeburn  5549: sub domainrolelog {
1.1512    raeburn  5550:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
                   5551:         $context,$othdomby,$requester)=@_;
1.1184    raeburn  5552:     if ($area =~ m{^/($match_domain)/$}) {
                   5553:         my $cdom = $1;
1.1494    raeburn  5554:         my $domconfiguser = &get_domainconfiguser($cdom);
1.1184    raeburn  5555:         my $namespace = 'rolelog';
                   5556:         my %storehash = (
                   5557:                            role    => $trole,
                   5558:                            start   => $tstart,
                   5559:                            end     => $tend,
                   5560:                            context => $context,
                   5561:                         );
1.1512    raeburn  5562:         if ($othdomby) {
                   5563:             if ($othdomby eq 'othdombydc') {
                   5564:                 $storehash{'approval'} = 'domain';
                   5565:             } elsif ($othdomby eq 'othdombyuser') {
                   5566:                 $storehash{'approval'} = 'user';
                   5567:             }
                   5568:             if ($requester ne '') {
                   5569:                 $storehash{'requester'} = $requester;
                   5570:             }
                   5571:         }
1.1188    raeburn  5572:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5573:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5574:     }
                   5575:     return;
                   5576: 
                   5577: }
                   5578: 
                   5579: sub coauthorrolelog {
1.1512    raeburn  5580:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
                   5581:         $context,$othdomby,$requester)=@_;
1.1184    raeburn  5582:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5583:         my $audom = $1;
                   5584:         my $auname = $2;
                   5585:         my $namespace = 'rolelog';
                   5586:         my %storehash = (
                   5587:                            role    => $trole,
                   5588:                            start   => $tstart,
                   5589:                            end     => $tend,
                   5590:                            context => $context,
                   5591:                         );
1.1512    raeburn  5592:         if ($othdomby) {
                   5593:             if ($othdomby eq 'othdombydc') {
                   5594:                 $storehash{'approval'} = 'domain';
                   5595:             } elsif ($othdomby eq 'othdombyuser') {
                   5596:                 $storehash{'approval'} = 'user';
                   5597:             }
                   5598:             if ($requester ne '') {
                   5599:                 $storehash{'requester'} = $requester;
                   5600:             }
                   5601:         }
1.1188    raeburn  5602:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5603:                    $domain,$auname,$audom);
1.1184    raeburn  5604:     }
                   5605:     return;
                   5606: }
                   5607: 
1.351     www      5608: sub get_course_adv_roles {
1.948     raeburn  5609:     my ($cid,$codes) = @_;
1.620     albertel 5610:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5611:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5612:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5613:     my %nothide=();
1.800     albertel 5614:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5615:         if ($user !~ /:/) {
                   5616: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5617:         } else {
                   5618:             $nothide{$user}=1;
                   5619:         }
1.470     www      5620:     }
1.1219    raeburn  5621:     my @possdoms = ($coursehash{'domain'});
                   5622:     if ($coursehash{'checkforpriv'}) {
                   5623:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5624:     }
1.351     www      5625:     my %returnhash=();
                   5626:     my %dumphash=
                   5627:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5628:     my $now=time;
1.997     raeburn  5629:     my %privileged;
1.1000    raeburn  5630:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5631: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5632:         if (($tstart) && ($tstart<0)) { next; }
                   5633:         if (($tend) && ($tend<$now)) { next; }
                   5634:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5635:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5636: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5637:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5638:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5639: 	if ($role eq 'cr') { next; }
1.948     raeburn  5640:         if ($codes) {
                   5641:             if ($section) { $role .= ':'.$section; }
                   5642:             if ($returnhash{$role}) {
                   5643:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5644:             } else {
                   5645:                 $returnhash{$role}=$username.':'.$domain;
                   5646:             }
1.351     www      5647:         } else {
1.988     raeburn  5648:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5649:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5650:             if ($returnhash{$key}) {
                   5651: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5652:             } else {
                   5653:                 $returnhash{$key}=$username.':'.$domain;
                   5654:             }
1.351     www      5655:         }
1.948     raeburn  5656:     }
1.400     www      5657:     return %returnhash;
                   5658: }
                   5659: 
                   5660: sub get_my_roles {
1.937     raeburn  5661:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5662:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5663:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5664:     my (%dumphash,%nothide);
1.1086    raeburn  5665:     if ($context eq 'userroles') {
1.1166    raeburn  5666:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5667:     } else {
1.1219    raeburn  5668:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5669:         if ($hidepriv) {
                   5670:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5671:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5672:                 if ($user !~ /:/) {
                   5673:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5674:                 } else {
                   5675:                     $nothide{$user} = 1;
                   5676:                 }
                   5677:             }
                   5678:         }
1.858     raeburn  5679:     }
1.400     www      5680:     my %returnhash=();
                   5681:     my $now=time;
1.999     raeburn  5682:     my %privileged;
1.800     albertel 5683:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5684:         my ($role,$tend,$tstart);
                   5685:         if ($context eq 'userroles') {
1.1149    raeburn  5686:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5687: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5688:         } else {
                   5689:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5690:         }
1.400     www      5691:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5692:         my $status = 'active';
1.939     raeburn  5693:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5694:             $status = 'previous';
                   5695:         } 
                   5696:         if (($tstart) && ($now<$tstart)) {
                   5697:             $status = 'future';
                   5698:         }
                   5699:         if (ref($types) eq 'ARRAY') {
                   5700:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5701:                 next;
                   5702:             } 
                   5703:         } else {
                   5704:             if ($status ne 'active') {
                   5705:                 next;
                   5706:             }
                   5707:         }
1.867     raeburn  5708:         my ($rolecode,$username,$domain,$section,$area);
                   5709:         if ($context eq 'userroles') {
1.1186    raeburn  5710:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5711:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5712:         } else {
                   5713:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5714:         }
1.832     raeburn  5715:         if (ref($roledoms) eq 'ARRAY') {
                   5716:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5717:                 next;
                   5718:             }
                   5719:         }
                   5720:         if (ref($roles) eq 'ARRAY') {
                   5721:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5722:                 if ($role =~ /^cr\//) {
                   5723:                     if (!grep(/^cr$/,@{$roles})) {
                   5724:                         next;
                   5725:                     }
1.1104    raeburn  5726:                 } elsif ($role =~ /^gr\//) {
                   5727:                     if (!grep(/^gr$/,@{$roles})) {
                   5728:                         next;
                   5729:                     }
1.922     raeburn  5730:                 } else {
                   5731:                     next;
                   5732:                 }
1.832     raeburn  5733:             }
1.867     raeburn  5734:         }
1.937     raeburn  5735:         if ($hidepriv) {
1.1219    raeburn  5736:             my @privroles = ('dc','su');
1.999     raeburn  5737:             if ($context eq 'userroles') {
1.1219    raeburn  5738:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5739:             } else {
1.1219    raeburn  5740:                 my $possdoms = [$domain];
                   5741:                 if (ref($roledoms) eq 'ARRAY') {
                   5742:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5743:                 }
1.1219    raeburn  5744:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5745:                     if (!$nothide{$username.':'.$domain}) {
                   5746:                         next;
                   5747:                     }
                   5748:                 }
1.937     raeburn  5749:             }
                   5750:         }
1.933     raeburn  5751:         if ($withsec) {
                   5752:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5753:                 $tstart.':'.$tend;
                   5754:         } else {
                   5755:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5756:         }
1.832     raeburn  5757:     }
1.373     www      5758:     return %returnhash;
1.399     www      5759: }
                   5760: 
1.1333    raeburn  5761: sub get_all_adhocroles {
                   5762:     my ($dom) = @_;
                   5763:     my @roles_by_num = ();
                   5764:     my %domdefaults = &get_domain_defaults($dom);
                   5765:     my (%description,%access_in_dom,%access_info);
                   5766:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5767:         my $count = 0;
                   5768:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5769:         my %ordered;
                   5770:         foreach my $role (sort(keys(%domcurrent))) {
                   5771:             my ($order,$desc,$access_in_dom);
                   5772:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5773:                 $order = $domcurrent{$role}{'order'};
                   5774:                 $desc = $domcurrent{$role}{'desc'};
                   5775:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5776:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5777:             }
                   5778:             if ($order eq '') {
                   5779:                 $order = $count;
                   5780:             }
                   5781:             $ordered{$order} = $role;
                   5782:             if ($desc ne '') {
                   5783:                 $description{$role} = $desc;
                   5784:             } else {
                   5785:                 $description{$role}= $role;
                   5786:             }
                   5787:             $count++;
                   5788:         }
                   5789:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5790:             push(@roles_by_num,$ordered{$item});
                   5791:         }
                   5792:     }
                   5793:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5794: }
                   5795: 
1.1332    raeburn  5796: sub get_my_adhocroles {
1.1333    raeburn  5797:     my ($cid,$checkreg) = @_;
                   5798:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5799:     if ($env{'request.course.id'} eq $cid) {
                   5800:         $cdom = $env{'course.'.$cid.'.domain'};
                   5801:         $cnum = $env{'course.'.$cid.'.num'};
                   5802:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5803:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5804:         $cdom = $1;
                   5805:         $cnum = $2;
1.1494    raeburn  5806:         %info = &get('environment',['internal.coursecode'],
                   5807:                      $cdom,$cnum);
1.1333    raeburn  5808:     }
                   5809:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5810:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5811:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5812:         if ($rosterhash{$user} ne '') {
                   5813:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5814:             return ([],{}) if ($type eq 'auto');
                   5815:         }
                   5816:     }
                   5817:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5818:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5819:             my $then=$env{'user.login.time'};
                   5820:             my $update=$env{'user.update.time'};
1.1335    raeburn  5821:             if (!$update) {
                   5822:                 $update = $then;
                   5823:             }
                   5824:             my @liveroles;
1.1334    raeburn  5825:             foreach my $role ('dh','da') {
                   5826:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5827:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5828:                     my $limit = $update;
                   5829:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5830:                         $limit = $then;
                   5831:                     }
1.1335    raeburn  5832:                     my $activerole = 1;
                   5833:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5834:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5835:                     if ($activerole) {
                   5836:                         push(@liveroles,$role);
                   5837:                     }
1.1334    raeburn  5838:                 }
1.1332    raeburn  5839:             }
1.1335    raeburn  5840:             if (@liveroles) {
1.1332    raeburn  5841:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5842:                     my ($accessref,$accessinfo,%access_in_dom);
                   5843:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5844:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5845:                         if (@{$roles_by_num}) {
1.1332    raeburn  5846:                             my %settings;
                   5847:                             if ($env{'request.course.id'} eq $cid) {
                   5848:                                 foreach my $envkey (keys(%env)) {
                   5849:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5850:                                         $settings{$1} = $env{$envkey};
                   5851:                                     }
                   5852:                                 }
                   5853:                             } else {
                   5854:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5855:                             }
                   5856:                             my %setincrs;
                   5857:                             if ($settings{'internal.adhocaccess'}) {
                   5858:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5859:                             }
                   5860:                             my @statuses;
                   5861:                             if ($env{'environment.inststatus'}) {
                   5862:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5863:                             }
                   5864:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5865:                             if (ref($accessref) eq 'HASH') {
                   5866:                                 %access_in_dom = %{$accessref};
                   5867:                             }
                   5868:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5869:                                 my ($curraccess,@okstatus,@personnel);
                   5870:                                 if ($setincrs{$role}) {
                   5871:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5872:                                     if ($curraccess eq 'status') {
                   5873:                                         @okstatus = split(/\&/,$rest);
                   5874:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5875:                                         @personnel = split(/\&/,$rest);
                   5876:                                     }
                   5877:                                 } else {
                   5878:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5879:                                     if (ref($accessinfo) eq 'HASH') {
                   5880:                                         if ($curraccess eq 'status') {
                   5881:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5882:                                                 @okstatus = @{$accessinfo->{$role}};
                   5883:                                             }
                   5884:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5885:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5886:                                                 @personnel = @{$accessinfo->{$role}};
                   5887:                                             }
1.1332    raeburn  5888:                                         }
                   5889:                                     }
                   5890:                                 }
                   5891:                                 if ($curraccess eq 'none') {
                   5892:                                     next;
                   5893:                                 } elsif ($curraccess eq 'all') {
                   5894:                                     push(@possroles,$role);
1.1336    raeburn  5895:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5896:                                     if (grep(/^dh$/,@liveroles)) {
                   5897:                                         push(@possroles,$role);
                   5898:                                     } else {
                   5899:                                         next;
                   5900:                                     }
1.1336    raeburn  5901:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5902:                                     if (grep(/^da$/,@liveroles)) {
                   5903:                                         push(@possroles,$role);
                   5904:                                     } else {
                   5905:                                         next;
                   5906:                                     }
1.1332    raeburn  5907:                                 } elsif ($curraccess eq 'status') {
                   5908:                                     if (@okstatus) {
                   5909:                                         if (!@statuses) {
                   5910:                                             if (grep(/^default$/,@okstatus)) {
                   5911:                                                 push(@possroles,$role);
                   5912:                                             }
                   5913:                                         } else {
                   5914:                                             foreach my $status (@okstatus) {
                   5915:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5916:                                                     push(@possroles,$role);
                   5917:                                                     last;
                   5918:                                                 }
                   5919:                                             }
                   5920:                                         }
                   5921:                                     }
                   5922:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5923:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5924:                                         if ($curraccess eq 'exc') {
                   5925:                                             push(@possroles,$role);
                   5926:                                         }
                   5927:                                     } elsif ($curraccess eq 'inc') {
                   5928:                                         push(@possroles,$role);
                   5929:                                     }
                   5930:                                 }
                   5931:                             }
                   5932:                         }
                   5933:                     }
                   5934:                 }
                   5935:             }
                   5936:         }
                   5937:     }
1.1333    raeburn  5938:     unless (ref($description) eq 'HASH') {
                   5939:         if (ref($roles_by_num) eq 'ARRAY') {
                   5940:             my %desc;
                   5941:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5942:             $description = \%desc;
                   5943:         } else {
                   5944:             $description = {};
                   5945:         }
                   5946:     }
                   5947:     return (\@possroles,$description);
1.1332    raeburn  5948: }
                   5949: 
1.399     www      5950: # ----------------------------------------------------- Frontpage Announcements
                   5951: #
                   5952: #
                   5953: 
                   5954: sub postannounce {
                   5955:     my ($server,$text)=@_;
1.844     albertel 5956:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5957:     unless ($text=~/\w/) { $text=''; }
                   5958:     return &reply('setannounce:'.&escape($text),$server);
                   5959: }
                   5960: 
                   5961: sub getannounce {
1.448     albertel 5962: 
1.1359    raeburn  5963:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5964: 	my $announcement='';
1.800     albertel 5965: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5966: 	close($fh);
1.399     www      5967: 	if ($announcement=~/\w/) { 
                   5968: 	    return 
                   5969:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5970:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5971: 	} else {
                   5972: 	    return '';
                   5973: 	}
                   5974:     } else {
                   5975: 	return '';
                   5976:     }
1.351     www      5977: }
1.353     www      5978: 
                   5979: # ---------------------------------------------------------- Course ID routines
                   5980: # Deal with domain's nohist_courseid.db files
                   5981: #
                   5982: 
                   5983: sub courseidput {
1.921     raeburn  5984:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5985:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5986:     my $outcome;
                   5987:     if ($caller eq 'timeonly') {
                   5988:         my $cids = '';
                   5989:         foreach my $item (keys(%$storehash)) {
                   5990:             $cids.=&escape($item).'&';
                   5991:         }
                   5992:         $cids=~s/\&$//;
                   5993:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5994:                           $coursehome);       
                   5995:     } else {
                   5996:         my $items = '';
                   5997:         foreach my $item (keys(%$storehash)) {
                   5998:             $items.= &escape($item).'='.
                   5999:                      &freeze_escape($$storehash{$item}).'&';
                   6000:         }
                   6001:         $items=~s/\&$//;
                   6002:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   6003:                           $coursehome);
1.918     raeburn  6004:     }
                   6005:     if ($outcome eq 'unknown_cmd') {
                   6006:         my $what;
                   6007:         foreach my $cid (keys(%$storehash)) {
                   6008:             $what .= &escape($cid).'=';
1.921     raeburn  6009:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  6010:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  6011:             }
                   6012:             $what =~ s/\:$/&/;
                   6013:         }
                   6014:         $what =~ s/\&$//;  
                   6015:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   6016:     } else {
                   6017:         return $outcome;
                   6018:     }
1.353     www      6019: }
                   6020: 
                   6021: sub courseiddump {
1.921     raeburn  6022:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  6023:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  6024:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  6025:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  6026:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  6027:     my $as_hash = 1;
                   6028:     my %returnhash;
                   6029:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 6030:     my %libserv = &all_library();
                   6031:     foreach my $tryserver (keys(%libserv)) {
                   6032:         if ( (  $hostidflag == 1 
                   6033: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   6034: 	     || (!defined($hostidflag)) ) {
                   6035: 
1.918     raeburn  6036: 	    if (($domfilter eq '') ||
                   6037: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 6038:                 my $rep;
                   6039:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   6040:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   6041:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   6042:                                 &escape($descfilter), &escape($instcodefilter), 
                   6043:                                 &escape($ownerfilter), &escape($coursefilter),
                   6044:                                 &escape($typefilter), &escape($regexp_ok), 
                   6045:                                 $as_hash, &escape($selfenrollonly), 
                   6046:                                 &escape($catfilter), $showhidden, $caller, 
                   6047:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   6048:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  6049:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   6050:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 6051:                 } else {
                   6052:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   6053:                              $sincefilter.':'.&escape($descfilter).':'.
                   6054:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   6055:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   6056:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   6057:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   6058:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   6059:                              &escape($cc_clone).':'.$cloneonly.':'.
                   6060:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  6061:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   6062:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 6063:                 }
                   6064:                      
1.918     raeburn  6065:                 my @pairs=split(/\&/,$rep);
                   6066:                 foreach my $item (@pairs) {
                   6067:                     my ($key,$value)=split(/\=/,$item,2);
                   6068:                     $key = &unescape($key);
                   6069:                     next if ($key =~ /^error: 2 /);
                   6070:                     my $result = &thaw_unescape($value);
                   6071:                     if (ref($result) eq 'HASH') {
                   6072:                         $returnhash{$key}=$result;
                   6073:                     } else {
1.921     raeburn  6074:                         my @responses = split(/:/,$value);
                   6075:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  6076:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  6077:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  6078:                         }
1.1008    raeburn  6079:                     }
1.353     www      6080:                 }
                   6081:             }
                   6082:         }
                   6083:     }
                   6084:     return %returnhash;
                   6085: }
                   6086: 
1.1055    raeburn  6087: sub courselastaccess {
                   6088:     my ($cdom,$cnum,$hostidref) = @_;
                   6089:     my %returnhash;
                   6090:     if ($cdom && $cnum) {
                   6091:         my $chome = &homeserver($cnum,$cdom);
                   6092:         if ($chome ne 'no_host') {
                   6093:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   6094:             &extract_lastaccess(\%returnhash,$rep);
                   6095:         }
                   6096:     } else {
                   6097:         if (!$cdom) { $cdom=''; }
                   6098:         my %libserv = &all_library();
                   6099:         foreach my $tryserver (keys(%libserv)) {
                   6100:             if (ref($hostidref) eq 'ARRAY') {
                   6101:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   6102:             } 
                   6103:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   6104:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   6105:                 &extract_lastaccess(\%returnhash,$rep);
                   6106:             }
                   6107:         }
                   6108:     }
                   6109:     return %returnhash;
                   6110: }
                   6111: 
                   6112: sub extract_lastaccess {
                   6113:     my ($returnhash,$rep) = @_;
                   6114:     if (ref($returnhash) eq 'HASH') {
                   6115:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   6116:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   6117:                  $rep eq '') {
                   6118:             my @pairs=split(/\&/,$rep);
                   6119:             foreach my $item (@pairs) {
                   6120:                 my ($key,$value)=split(/\=/,$item,2);
                   6121:                 $key = &unescape($key);
                   6122:                 next if ($key =~ /^error: 2 /);
                   6123:                 $returnhash->{$key} = &thaw_unescape($value);
                   6124:             }
                   6125:         }
                   6126:     }
                   6127:     return;
                   6128: }
                   6129: 
1.658     raeburn  6130: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  6131: 
                   6132: sub dcmailput {
1.685     raeburn  6133:     my ($domain,$msgid,$message,$server)=@_;
1.1494    raeburn  6134:     my $status = &critical(
1.740     www      6135:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   6136:        &escape($message),$server);
1.662     raeburn  6137:     return $status;
                   6138: }
                   6139: 
1.658     raeburn  6140: sub dcmaildump {
                   6141:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  6142:     my %returnhash=();
1.846     albertel 6143: 
                   6144:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  6145:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   6146:                                                          &escape($enddate).':';
                   6147: 	my @esc_senders=map { &escape($_)} @$senders;
                   6148: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 6149: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 6150:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  6151:             if (($key) && ($value)) {
                   6152:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  6153:             }
                   6154:         }
                   6155:     }
                   6156:     return %returnhash;
                   6157: }
1.662     raeburn  6158: # ---------------------------------------------------------- Domain roles
                   6159: 
                   6160: sub get_domain_roles {
                   6161:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  6162:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  6163:         $startdate = '.';
                   6164:     }
1.1018    raeburn  6165:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  6166:         $enddate = '.';
                   6167:     }
1.922     raeburn  6168:     my $rolelist;
                   6169:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  6170:         $rolelist = join('&',@{$roles});
1.922     raeburn  6171:     }
1.662     raeburn  6172:     my %personnel = ();
1.841     albertel 6173: 
                   6174:     my %servers = &get_servers($dom,'library');
                   6175:     foreach my $tryserver (keys(%servers)) {
                   6176: 	%{$personnel{$tryserver}}=();
                   6177: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   6178: 					    &escape($startdate).':'.
                   6179: 					    &escape($enddate).':'.
                   6180: 					    &escape($rolelist), $tryserver))) {
                   6181: 	    my ($key,$value) = split(/\=/,$line,2);
                   6182: 	    if (($key) && ($value)) {
                   6183: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   6184: 	    }
                   6185: 	}
1.662     raeburn  6186:     }
                   6187:     return %personnel;
                   6188: }
1.658     raeburn  6189: 
1.1332    raeburn  6190: sub get_active_domroles {
                   6191:     my ($dom,$roles) = @_;
                   6192:     return () unless (ref($roles) eq 'ARRAY');
                   6193:     my $now = time;
                   6194:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   6195:     my %domroles;
                   6196:     foreach my $server (keys(%dompersonnel)) {
                   6197:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   6198:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   6199:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   6200:         }
                   6201:     }
                   6202:     return %domroles;
                   6203: }
                   6204: 
1.1057    www      6205: # ----------------------------------------------------------- Interval timing 
1.149     www      6206: 
1.1153    www      6207: {
                   6208: # Caches needed for speedup of navmaps
                   6209: # We don't want to cache this for very long at all (5 seconds at most)
                   6210: # 
                   6211: # The user for whom we cache
                   6212: my $cachedkey='';
                   6213: # The cached times for this user
                   6214: my %cachedtimes=();
                   6215: # When this was last done
1.1282    raeburn  6216: my $cachedtime='';
1.1153    www      6217: 
                   6218: sub load_all_first_access {
1.1308    raeburn  6219:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      6220:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  6221:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   6222:         (!$ignorecache)) {
1.1154    raeburn  6223:         return;
                   6224:     }
                   6225:     $cachedtime=time;
                   6226:     $cachedkey=$uname.':'.$udom;
                   6227:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      6228: }
                   6229: 
1.504     albertel 6230: sub get_first_access {
1.1308    raeburn  6231:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 6232:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 6233:     if ($argsymb) { $symb=$argsymb; }
                   6234:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  6235:     if ($argmap) { $map = $argmap; }
1.926     albertel 6236:     if ($type eq 'course') {
                   6237: 	$res='course';
                   6238:     } elsif ($type eq 'map') {
1.588     albertel 6239: 	$res=&symbread($map);
                   6240:     } else {
                   6241: 	$res=$symb;
                   6242:     }
1.1308    raeburn  6243:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      6244:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 6245: }
                   6246: 
                   6247: sub set_first_access {
1.1162    raeburn  6248:     my ($type,$interval)=@_;
1.790     albertel 6249:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 6250:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 6251:     if ($type eq 'course') {
                   6252: 	$res='course';
                   6253:     } elsif ($type eq 'map') {
1.588     albertel 6254: 	$res=&symbread($map);
                   6255:     } else {
                   6256: 	$res=$symb;
                   6257:     }
1.1153    www      6258:     $cachedkey='';
1.1162    raeburn  6259:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  6260:     if ($firstaccess) {
                   6261:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  6262:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   6263:                  "in $courseid");
1.1386    raeburn  6264:         return 'already_set';
                   6265:     } else {
1.1162    raeburn  6266:         my $start = time;
                   6267: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   6268:                           $udom,$uname);
                   6269:         if ($putres eq 'ok') {
                   6270:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   6271:                  $udom,$uname); 
                   6272:             &appenv(
                   6273:                      {
                   6274:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   6275:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   6276:                      }
                   6277:                   );
1.1365    raeburn  6278:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   6279:                 $cachedtimes{"$courseid\0$res"} = $start;
                   6280:             }
1.1386    raeburn  6281:         } elsif ($putres ne 'refused') {
                   6282:             &logthis("Result: $putres when attempting to set first access time ".
                   6283:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  6284:         }
                   6285:         return $putres;
1.505     albertel 6286:     }
                   6287:     return 'already_set';
1.504     albertel 6288: }
1.1153    www      6289: }
1.1282    raeburn  6290: 
1.110     www      6291: # --------------------------------------------- Set Expire Date for Spreadsheet
                   6292: 
                   6293: sub expirespread {
                   6294:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 6295:     my $cid=$env{'request.course.id'}; 
1.110     www      6296:     if ($cid) {
                   6297:        my $now=time;
                   6298:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6299:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6300:                             $env{'course.'.$cid.'.num'}.
1.110     www      6301: 	        	    ':nohist_expirationdates:'.
                   6302:                             &escape($key).'='.$now,
1.620     albertel 6303:                             $env{'course.'.$cid.'.home'})
1.110     www      6304:     }
                   6305:     return 'ok';
1.14      www      6306: }
                   6307: 
1.109     www      6308: # ----------------------------------------------------- Devalidate Spreadsheets
                   6309: 
                   6310: sub devalidate {
1.325     www      6311:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6312:     my $cid=$env{'request.course.id'}; 
1.109     www      6313:     if ($cid) {
1.391     matthew  6314:         # delete the stored spreadsheets for
                   6315:         # - the student level sheet of this user in course's homespace
                   6316:         # - the assessment level sheet for this resource 
                   6317:         #   for this user in user's homespace
1.553     albertel 6318: 	# - current conditional state info
1.325     www      6319: 	my $key=$uname.':'.$udom.':';
1.109     www      6320:         my $status=
1.299     matthew  6321: 	    &del('nohist_calculatedsheets',
1.391     matthew  6322: 		 [$key.'studentcalc:'],
1.620     albertel 6323: 		 $env{'course.'.$cid.'.domain'},
                   6324: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6325: 		.' '.
                   6326: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6327: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6328:         unless ($status eq 'ok ok') {
                   6329:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6330:                     $uname.' at '.$udom.' for '.
1.109     www      6331: 		    $symb.': '.$status);
1.133     albertel 6332:         }
1.553     albertel 6333: 	&delenv('user.state.'.$cid);
1.109     www      6334:     }
                   6335: }
                   6336: 
1.265     albertel 6337: sub get_scalar {
                   6338:     my ($string,$end) = @_;
                   6339:     my $value;
                   6340:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6341: 	$value = $1;
                   6342:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6343: 	$value = $1;
                   6344:     }
                   6345:     return &unescape($value);
                   6346: }
                   6347: 
                   6348: sub array2str {
                   6349:   my (@array) = @_;
                   6350:   my $result=&arrayref2str(\@array);
                   6351:   $result=~s/^__ARRAY_REF__//;
                   6352:   $result=~s/__END_ARRAY_REF__$//;
                   6353:   return $result;
                   6354: }
                   6355: 
1.204     albertel 6356: sub arrayref2str {
                   6357:   my ($arrayref) = @_;
1.265     albertel 6358:   my $result='__ARRAY_REF__';
1.204     albertel 6359:   foreach my $elem (@$arrayref) {
1.265     albertel 6360:     if(ref($elem) eq 'ARRAY') {
                   6361:       $result.=&arrayref2str($elem).'&';
                   6362:     } elsif(ref($elem) eq 'HASH') {
                   6363:       $result.=&hashref2str($elem).'&';
                   6364:     } elsif(ref($elem)) {
                   6365:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6366:     } else {
                   6367:       $result.=&escape($elem).'&';
                   6368:     }
                   6369:   }
                   6370:   $result=~s/\&$//;
1.265     albertel 6371:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6372:   return $result;
                   6373: }
                   6374: 
1.168     albertel 6375: sub hash2str {
1.204     albertel 6376:   my (%hash) = @_;
                   6377:   my $result=&hashref2str(\%hash);
1.265     albertel 6378:   $result=~s/^__HASH_REF__//;
                   6379:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6380:   return $result;
                   6381: }
                   6382: 
                   6383: sub hashref2str {
                   6384:   my ($hashref)=@_;
1.265     albertel 6385:   my $result='__HASH_REF__';
1.800     albertel 6386:   foreach my $key (sort(keys(%$hashref))) {
                   6387:     if (ref($key) eq 'ARRAY') {
                   6388:       $result.=&arrayref2str($key).'=';
                   6389:     } elsif (ref($key) eq 'HASH') {
                   6390:       $result.=&hashref2str($key).'=';
                   6391:     } elsif (ref($key)) {
1.265     albertel 6392:       $result.='=';
1.800     albertel 6393:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6394:     } else {
1.1132    raeburn  6395: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6396:     }
                   6397: 
1.800     albertel 6398:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6399:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6400:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6401:       $result.=&hashref2str($hashref->{$key}).'&';
                   6402:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6403:        $result.='&';
1.800     albertel 6404:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6405:     } else {
1.800     albertel 6406:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6407:     }
                   6408:   }
1.168     albertel 6409:   $result=~s/\&$//;
1.265     albertel 6410:   $result .= '__END_HASH_REF__';
1.168     albertel 6411:   return $result;
                   6412: }
                   6413: 
                   6414: sub str2hash {
1.265     albertel 6415:     my ($string)=@_;
                   6416:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6417:     return %$hash;
                   6418: }
                   6419: 
                   6420: sub str2hashref {
1.168     albertel 6421:   my ($string) = @_;
1.265     albertel 6422: 
                   6423:   my %hash;
                   6424: 
                   6425:   if($string !~ /^__HASH_REF__/) {
                   6426:       if (! ($string eq '' || !defined($string))) {
                   6427: 	  $hash{'error'}='Not hash reference';
                   6428:       }
                   6429:       return (\%hash, $string);
                   6430:   }
                   6431: 
                   6432:   $string =~ s/^__HASH_REF__//;
                   6433: 
                   6434:   while($string !~ /^__END_HASH_REF__/) {
                   6435:       #key
                   6436:       my $key='';
                   6437:       if($string =~ /^__HASH_REF__/) {
                   6438:           ($key, $string)=&str2hashref($string);
                   6439:           if(defined($key->{'error'})) {
                   6440:               $hash{'error'}='Bad data';
                   6441:               return (\%hash, $string);
                   6442:           }
                   6443:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6444:           ($key, $string)=&str2arrayref($string);
                   6445:           if($key->[0] eq 'Array reference error') {
                   6446:               $hash{'error'}='Bad data';
                   6447:               return (\%hash, $string);
                   6448:           }
                   6449:       } else {
                   6450:           $string =~ s/^(.*?)=//;
1.267     albertel 6451: 	  $key=&unescape($1);
1.265     albertel 6452:       }
                   6453:       $string =~ s/^=//;
                   6454: 
                   6455:       #value
                   6456:       my $value='';
                   6457:       if($string =~ /^__HASH_REF__/) {
                   6458:           ($value, $string)=&str2hashref($string);
                   6459:           if(defined($value->{'error'})) {
                   6460:               $hash{'error'}='Bad data';
                   6461:               return (\%hash, $string);
                   6462:           }
                   6463:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6464:           ($value, $string)=&str2arrayref($string);
                   6465:           if($value->[0] eq 'Array reference error') {
                   6466:               $hash{'error'}='Bad data';
                   6467:               return (\%hash, $string);
                   6468:           }
                   6469:       } else {
                   6470: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6471:       }
                   6472:       $string =~ s/^&//;
                   6473: 
                   6474:       $hash{$key}=$value;
1.204     albertel 6475:   }
1.265     albertel 6476: 
                   6477:   $string =~ s/^__END_HASH_REF__//;
                   6478: 
                   6479:   return (\%hash, $string);
1.204     albertel 6480: }
                   6481: 
                   6482: sub str2array {
1.265     albertel 6483:     my ($string)=@_;
                   6484:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6485:     return @$array;
                   6486: }
                   6487: 
                   6488: sub str2arrayref {
1.204     albertel 6489:   my ($string) = @_;
1.265     albertel 6490:   my @array;
                   6491: 
                   6492:   if($string !~ /^__ARRAY_REF__/) {
                   6493:       if (! ($string eq '' || !defined($string))) {
                   6494: 	  $array[0]='Array reference error';
                   6495:       }
                   6496:       return (\@array, $string);
                   6497:   }
                   6498: 
                   6499:   $string =~ s/^__ARRAY_REF__//;
                   6500: 
                   6501:   while($string !~ /^__END_ARRAY_REF__/) {
                   6502:       my $value='';
                   6503:       if($string =~ /^__HASH_REF__/) {
                   6504:           ($value, $string)=&str2hashref($string);
                   6505:           if(defined($value->{'error'})) {
                   6506:               $array[0] ='Array reference error';
                   6507:               return (\@array, $string);
                   6508:           }
                   6509:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6510:           ($value, $string)=&str2arrayref($string);
                   6511:           if($value->[0] eq 'Array reference error') {
                   6512:               $array[0] ='Array reference error';
                   6513:               return (\@array, $string);
                   6514:           }
                   6515:       } else {
                   6516: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6517:       }
                   6518:       $string =~ s/^&//;
                   6519: 
                   6520:       push(@array, $value);
1.191     harris41 6521:   }
1.265     albertel 6522: 
                   6523:   $string =~ s/^__END_ARRAY_REF__//;
                   6524: 
                   6525:   return (\@array, $string);
1.168     albertel 6526: }
                   6527: 
1.167     albertel 6528: # -------------------------------------------------------------------Temp Store
                   6529: 
1.168     albertel 6530: sub tmpreset {
                   6531:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6532:   if (!$symb) {
                   6533:     $symb=&symbread();
1.620     albertel 6534:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6535:   }
                   6536:   $symb=escape($symb);
                   6537: 
1.620     albertel 6538:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6539:   $namespace=~s/\//\_/g;
                   6540:   $namespace=~s/\W//g;
                   6541: 
1.620     albertel 6542:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6543:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6544:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6545:       $stuname=&get_requestor_ip();
1.591     albertel 6546:   }
1.1117    foxr     6547:   my $path=LONCAPA::tempdir();
1.168     albertel 6548:   my %hash;
                   6549:   if (tie(%hash,'GDBM_File',
                   6550: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6551: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6552:     foreach my $key (keys(%hash)) {
1.180     albertel 6553:       if ($key=~ /:$symb/) {
1.168     albertel 6554: 	delete($hash{$key});
                   6555:       }
                   6556:     }
                   6557:   }
                   6558: }
                   6559: 
1.167     albertel 6560: sub tmpstore {
1.168     albertel 6561:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6562: 
                   6563:   if (!$symb) {
                   6564:     $symb=&symbread();
1.620     albertel 6565:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6566:   }
                   6567:   $symb=escape($symb);
                   6568: 
                   6569:   if (!$namespace) {
                   6570:     # I don't think we would ever want to store this for a course.
                   6571:     # it seems this will only be used if we don't have a course.
1.620     albertel 6572:     #$namespace=$env{'request.course.id'};
1.168     albertel 6573:     #if (!$namespace) {
1.620     albertel 6574:       $namespace=$env{'request.state'};
1.168     albertel 6575:     #}
                   6576:   }
                   6577:   $namespace=~s/\//\_/g;
                   6578:   $namespace=~s/\W//g;
1.620     albertel 6579:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6580:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6581:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6582:       $stuname=&get_requestor_ip();
1.591     albertel 6583:   }
1.168     albertel 6584:   my $now=time;
                   6585:   my %hash;
1.1117    foxr     6586:   my $path=LONCAPA::tempdir();
1.168     albertel 6587:   if (tie(%hash,'GDBM_File',
                   6588: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6589: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6590:     $hash{"version:$symb"}++;
                   6591:     my $version=$hash{"version:$symb"};
                   6592:     my $allkeys=''; 
                   6593:     foreach my $key (keys(%$storehash)) {
                   6594:       $allkeys.=$key.':';
1.591     albertel 6595:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6596:     }
                   6597:     $hash{"$version:$symb:timestamp"}=$now;
                   6598:     $allkeys.='timestamp';
                   6599:     $hash{"$version:keys:$symb"}=$allkeys;
                   6600:     if (untie(%hash)) {
                   6601:       return 'ok';
                   6602:     } else {
                   6603:       return "error:$!";
                   6604:     }
                   6605:   } else {
                   6606:     return "error:$!";
                   6607:   }
                   6608: }
1.167     albertel 6609: 
1.168     albertel 6610: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6611: 
1.168     albertel 6612: sub tmprestore {
                   6613:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6614: 
1.168     albertel 6615:   if (!$symb) {
                   6616:     $symb=&symbread();
1.620     albertel 6617:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6618:   }
                   6619:   $symb=escape($symb);
                   6620: 
1.620     albertel 6621:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6622: 
1.620     albertel 6623:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6624:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6625:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6626:       $stuname=&get_requestor_ip();
1.591     albertel 6627:   }
1.168     albertel 6628:   my %returnhash;
                   6629:   $namespace=~s/\//\_/g;
                   6630:   $namespace=~s/\W//g;
                   6631:   my %hash;
1.1117    foxr     6632:   my $path=LONCAPA::tempdir();
1.168     albertel 6633:   if (tie(%hash,'GDBM_File',
                   6634: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6635: 	  &GDBM_READER(),0640)) {
1.168     albertel 6636:     my $version=$hash{"version:$symb"};
                   6637:     $returnhash{'version'}=$version;
                   6638:     my $scope;
                   6639:     for ($scope=1;$scope<=$version;$scope++) {
                   6640:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6641:       my @keys=split(/:/,$vkeys);
                   6642:       my $key;
                   6643:       $returnhash{"$scope:keys"}=$vkeys;
                   6644:       foreach $key (@keys) {
1.591     albertel 6645: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6646: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6647:       }
                   6648:     }
1.168     albertel 6649:     if (!(untie(%hash))) {
                   6650:       return "error:$!";
                   6651:     }
                   6652:   } else {
                   6653:     return "error:$!";
                   6654:   }
                   6655:   return %returnhash;
1.167     albertel 6656: }
                   6657: 
1.9       www      6658: # ----------------------------------------------------------------------- Store
                   6659: 
                   6660: sub store {
1.1269    raeburn  6661:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6662:     my $home='';
                   6663: 
1.168     albertel 6664:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6665: 
1.213     www      6666:     $symb=&symbclean($symb);
1.122     albertel 6667:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6668: 
1.620     albertel 6669:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6670:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6671: 
                   6672:     &devalidate($symb,$stuname,$domain);
1.109     www      6673: 
                   6674:     $symb=escape($symb);
1.187     www      6675:     if (!$namespace) { 
1.620     albertel 6676:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6677:           return ''; 
                   6678:        } 
                   6679:     }
1.620     albertel 6680:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6681: 
1.1434    raeburn  6682:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6683:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6684: 
1.12      www      6685:     my $namevalue='';
1.800     albertel 6686:     foreach my $key (keys(%$storehash)) {
                   6687:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6688:     }
1.12      www      6689:     $namevalue=~s/\&$//;
1.187     www      6690:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6691:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6692: }
                   6693: 
1.47      www      6694: # -------------------------------------------------------------- Critical Store
                   6695: 
                   6696: sub cstore {
1.1269    raeburn  6697:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6698:     my $home='';
                   6699: 
1.168     albertel 6700:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6701: 
1.213     www      6702:     $symb=&symbclean($symb);
1.122     albertel 6703:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6704: 
1.620     albertel 6705:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6706:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6707: 
                   6708:     &devalidate($symb,$stuname,$domain);
1.109     www      6709: 
                   6710:     $symb=escape($symb);
1.187     www      6711:     if (!$namespace) { 
1.620     albertel 6712:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6713:           return ''; 
                   6714:        } 
                   6715:     }
1.620     albertel 6716:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6717: 
1.1434    raeburn  6718:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6719:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6720: 
1.47      www      6721:     my $namevalue='';
1.800     albertel 6722:     foreach my $key (keys(%$storehash)) {
                   6723:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6724:     }
1.47      www      6725:     $namevalue=~s/\&$//;
1.187     www      6726:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6727:     return critical
1.1269    raeburn  6728:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6729: }
                   6730: 
1.9       www      6731: # --------------------------------------------------------------------- Restore
                   6732: 
                   6733: sub restore {
1.124     www      6734:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6735:     my $home='';
                   6736: 
1.168     albertel 6737:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6738: 
1.122     albertel 6739:     if (!$symb) {
1.1224    raeburn  6740:         return if ($namespace eq 'courserequests');
                   6741:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6742:     } else {
1.1224    raeburn  6743:         unless ($namespace eq 'courserequests') {
                   6744:             $symb=&escape(&symbclean($symb));
                   6745:         }
1.122     albertel 6746:     }
1.188     www      6747:     if (!$namespace) { 
1.620     albertel 6748:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6749:           return ''; 
                   6750:        } 
                   6751:     }
1.620     albertel 6752:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6753:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6754:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6755:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6756: 
1.12      www      6757:     my %returnhash=();
1.800     albertel 6758:     foreach my $line (split(/\&/,$answer)) {
                   6759: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6760:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6761:     }
1.75      www      6762:     my $version;
                   6763:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6764:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6765:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6766:        }
1.75      www      6767:     }
1.13      www      6768:     return %returnhash;
1.34      www      6769: }
                   6770: 
                   6771: # ---------------------------------------------------------- Course Description
1.1118    foxr     6772: #
                   6773: #  
1.34      www      6774: 
                   6775: sub coursedescription {
1.731     albertel 6776:     my ($courseid,$args)=@_;
1.34      www      6777:     $courseid=~s/^\///;
1.49      www      6778:     $courseid=~s/\_/\//g;
1.34      www      6779:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6780:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6781:     my $normalid=$cdomain.'_'.$cnum;
                   6782:     # need to always cache even if we get errors otherwise we keep 
                   6783:     # trying and trying and trying to get the course description.
                   6784:     my %envhash=();
                   6785:     my %returnhash=();
1.731     albertel 6786:     
                   6787:     my $expiretime=600;
                   6788:     if ($env{'request.course.id'} eq $normalid) {
                   6789: 	$expiretime=120;
                   6790:     }
                   6791: 
                   6792:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6793:     if (!$args->{'freshen_cache'}
                   6794: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6795: 	foreach my $key (keys(%env)) {
                   6796: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6797: 	    my ($setting) = $1;
                   6798: 	    $returnhash{$setting} = $env{$key};
                   6799: 	}
                   6800: 	return %returnhash;
                   6801:     }
                   6802: 
1.1118    foxr     6803:     # get the data again
                   6804: 
1.731     albertel 6805:     if (!$args->{'one_time'}) {
                   6806: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6807:     }
1.811     albertel 6808: 
1.34      www      6809:     if ($chome ne 'no_host') {
1.302     albertel 6810:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6811:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6812: 	   my $username = $env{'user.name'}; # Defult username
                   6813: 	   if(defined $args->{'user'}) {
                   6814: 	       $username = $args->{'user'};
                   6815: 	   }
1.129     albertel 6816:            $returnhash{'home'}= $chome;
                   6817: 	   $returnhash{'domain'} = $cdomain;
                   6818: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6819:            if (!defined($returnhash{'type'})) {
                   6820:                $returnhash{'type'} = 'Course';
                   6821:            }
1.130     albertel 6822:            while (my ($name,$value) = each %returnhash) {
1.53      www      6823:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6824:            }
1.270     www      6825:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6826:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6827: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6828:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6829:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6830:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6831:        }
                   6832:     }
1.731     albertel 6833:     if (!$args->{'one_time'}) {
1.949     raeburn  6834: 	&appenv(\%envhash);
1.731     albertel 6835:     }
1.302     albertel 6836:     return %returnhash;
1.461     www      6837: }
                   6838: 
1.1080    raeburn  6839: sub update_released_required {
                   6840:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6841:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6842:         $cid = $env{'request.course.id'};
                   6843:         $cdom = $env{'course.'.$cid.'.domain'};
                   6844:         $cnum = $env{'course.'.$cid.'.num'};
                   6845:         $chome = $env{'course.'.$cid.'.home'};
                   6846:     }
                   6847:     if ($needsrelease) {
                   6848:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6849:         my $needsupdate;
                   6850:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6851:             $needsupdate = 1;
                   6852:         } else {
                   6853:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6854:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6855:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6856:                 $needsupdate = 1;
                   6857:             }
                   6858:         }
                   6859:         if ($needsupdate) {
                   6860:             my %needshash = (
                   6861:                              'internal.releaserequired' => $needsrelease,
                   6862:                             );
                   6863:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6864:             if ($putresult eq 'ok') {
                   6865:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6866:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6867:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6868:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6869:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6870:                 }
                   6871:             }
                   6872:         }
                   6873:     }
                   6874:     return;
                   6875: }
                   6876: 
1.461     www      6877: # -------------------------------------------------See if a user is privileged
                   6878: 
                   6879: sub privileged {
1.1219    raeburn  6880:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6881:     my $now = time;
1.1219    raeburn  6882:     my $roles;
                   6883:     if (ref($possroles) eq 'ARRAY') {
                   6884:         $roles = $possroles; 
                   6885:     } else {
                   6886:         $roles = ['dc','su'];
                   6887:     }
                   6888:     if (ref($possdomains) eq 'ARRAY') {
                   6889:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6890:         foreach my $dom (@{$possdomains}) {
                   6891:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6892:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6893:                 foreach my $role (@{$roles}) {
                   6894:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6895:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6896:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6897:                             return 1 unless (($end && $end < $now) ||
                   6898:                                              ($start && $start > $now));
                   6899:                         }
                   6900:                     }
                   6901:                 }
                   6902:             }
                   6903:         }
                   6904:     } else {
                   6905:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6906:         my $now = time;
1.1170    droeschl 6907: 
1.1275    musolffc 6908:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6909:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6910:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6911:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6912:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6913:             }
1.1219    raeburn  6914:         }
                   6915:     }
                   6916:     return 0;
                   6917: }
1.1170    droeschl 6918: 
1.1219    raeburn  6919: sub privileged_by_domain {
                   6920:     my ($domains,$roles) = @_;
                   6921:     my %privileged = ();
                   6922:     my $cachetime = 60*60*24;
                   6923:     my $now = time;
                   6924:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6925:         return %privileged;
                   6926:     }
                   6927:     foreach my $dom (@{$domains}) {
                   6928:         next if (ref($privileged{$dom}) eq 'HASH');
                   6929:         my $needroles;
                   6930:         foreach my $role (@{$roles}) {
                   6931:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6932:             if (defined($cached)) {
                   6933:                 if (ref($result) eq 'HASH') {
                   6934:                     $privileged{$dom}{$role} = $result;
                   6935:                 }
                   6936:             } else {
                   6937:                 $needroles = 1;
                   6938:             }
                   6939:         }
                   6940:         if ($needroles) {
                   6941:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6942:             $privileged{$dom} = {};
                   6943:             foreach my $server (keys(%dompersonnel)) {
                   6944:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6945:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6946:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6947:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6948:                         next if ($end && $end < $now);
                   6949:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6950:                             $dompersonnel{$server}{$item};
                   6951:                     }
                   6952:                 }
                   6953:             }
                   6954:             if (ref($privileged{$dom}) eq 'HASH') {
                   6955:                 foreach my $role (@{$roles}) {
                   6956:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6957:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6958:                     } else {
                   6959:                         my %hash = ();
                   6960:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6961:                     }
                   6962:                 }
                   6963:             }
                   6964:         }
                   6965:     }
                   6966:     return %privileged;
1.9       www      6967: }
1.1       albertel 6968: 
1.103     harris41 6969: # -------------------------------------------------------- Get user privileges
1.11      www      6970: 
                   6971: sub rolesinit {
1.1169    droeschl 6972:     my ($domain, $username) = @_;
                   6973:     my %userroles = ('user.login.time' => time);
                   6974:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6975: 
                   6976:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6977:     # also, blocking can be triggered by an activating timer
                   6978:     # it's saved in the user's %env.
                   6979:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6980:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6981:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
1.1517  ! raeburn  6982:         %timerintchk, %timerintenv, %coauthorenv);
1.1169    droeschl 6983: 
1.1162    raeburn  6984:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6985:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6986:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6987:     }
1.1169    droeschl 6988: 
1.1162    raeburn  6989:     foreach my $key (keys(%timerinterval)) {
                   6990:         my ($cid,$rest) = split(/\0/,$key);
                   6991:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6992:     }
1.1169    droeschl 6993: 
1.11      www      6994:     my %allroles=();
1.1162    raeburn  6995:     my %allgroups=();
1.1517  ! raeburn  6996:     my %gotcoauconfig=();
1.11      www      6997: 
1.1274    raeburn  6998:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6999:         my $role = $rolesdump{$area};
                   7000:         $area =~ s/\_\w\w$//;
                   7001: 
                   7002:         my ($trole, $tend, $tstart, $group_privs);
                   7003: 
                   7004:         if ($role =~ /^cr/) {
                   7005:         # Custom role, defined by a user 
                   7006:         # e.g., user.role.cr/msu/smith/mynewrole
                   7007:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   7008:                 $trole = $1;
                   7009:                 ($tend, $tstart) = split('_', $2);
                   7010:             } else {
                   7011:                 $trole = $role;
                   7012:             }
                   7013:         } elsif ($role =~ m|^gr/|) {
                   7014:         # Role of member in a group, defined within a course/community
                   7015:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   7016:             ($trole, $tend, $tstart) = split(/_/, $role);
                   7017:             next if $tstart eq '-1';
                   7018:             ($trole, $group_privs) = split(/\//, $trole);
                   7019:             $group_privs = &unescape($group_privs);
                   7020:         } else {
                   7021:         # Just a normal role, defined in roles.tab
                   7022:             ($trole, $tend, $tstart) = split(/_/,$role);
                   7023:         }
                   7024: 
                   7025:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   7026:                  $username);
                   7027:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   7028: 
                   7029:         # role expired or not available yet?
                   7030:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   7031:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   7032: 
                   7033:         next if $area eq '' or $trole eq '';
                   7034: 
                   7035:         my $spec = "$trole.$area";
                   7036:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   7037: 
                   7038:         if ($trole =~ /^cr\//) {
                   7039:         # Custom role, defined by a user
                   7040:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7041:         } elsif ($trole eq 'gr') {
                   7042:         # Role of a member in a group, defined within a course/community
                   7043:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   7044:             next;
                   7045:         } else {
                   7046:         # Normal role, defined in roles.tab
                   7047:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.1517  ! raeburn  7048:             if (($trole eq 'ca') || ($trole eq 'aa')) {
        !          7049:                 (undef,my ($audom,$auname)) = split(/\//,$area);
        !          7050:                 unless ($gotcoauconfig{$area}) {
        !          7051:                     my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
        !          7052:                     my %info = &userenvironment($audom,$auname,@ca_settings);
        !          7053:                     $gotcoauconfig{$area} = 1;
        !          7054:                     foreach my $item (@ca_settings) {
        !          7055:                         if (exists($info{$item})) {
        !          7056:                             $coauthorenv{"environment.internal.$item.$area"} = $info{$item};
        !          7057:                         }
        !          7058:                     }
        !          7059:                 }
        !          7060:             }
1.1169    droeschl 7061:         }
                   7062: 
                   7063:         my $cid = $tdomain.'_'.$trest;
                   7064:         unless ($firstaccchk{$cid}) {
                   7065:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   7066:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   7067:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   7068:                         $coursetimerstarts{$cid}{$item}; 
                   7069:                 }
                   7070:             }
                   7071:             $firstaccchk{$cid} = 1;
                   7072:         }
                   7073:         unless ($timerintchk{$cid}) {
                   7074:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   7075:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   7076:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   7077:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  7078:                 }
1.12      www      7079:             }
1.1169    droeschl 7080:             $timerintchk{$cid} = 1;
1.191     harris41 7081:         }
1.11      www      7082:     }
1.1169    droeschl 7083: 
1.1341    raeburn  7084:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   7085:                                                           \%allroles, \%allgroups);
1.1169    droeschl 7086:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  7087:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 7088: 
1.1517  ! raeburn  7089:     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
1.11      www      7090: }
                   7091: 
1.567     raeburn  7092: sub set_arearole {
1.1215    raeburn  7093:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   7094:     unless ($nolog) {
1.567     raeburn  7095: # log the associated role with the area
1.1215    raeburn  7096:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   7097:     }
1.743     albertel 7098:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  7099: }
                   7100: 
                   7101: sub custom_roleprivs {
                   7102:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   7103:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  7104:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 7105:     if (&hostname($homsvr) ne '') {
1.567     raeburn  7106:         my ($rdummy,$roledef)=
                   7107:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   7108:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   7109:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   7110:             if (defined($syspriv)) {
1.1043    raeburn  7111:                 if ($trest =~ /^$match_community$/) {
                   7112:                     $syspriv =~ s/bre\&S//; 
                   7113:                 }
1.567     raeburn  7114:                 $$allroles{'cm./'}.=':'.$syspriv;
                   7115:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   7116:             }
                   7117:             if ($tdomain ne '') {
                   7118:                 if (defined($dompriv)) {
                   7119:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   7120:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   7121:                 }
                   7122:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  7123:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   7124:                         my $rolename = $1;
                   7125:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   7126:                     }
1.567     raeburn  7127:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   7128:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   7129:                 }
                   7130:             }
                   7131:         }
                   7132:     }
                   7133: }
                   7134: 
1.1332    raeburn  7135: sub course_adhocrole_privs {
                   7136:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   7137:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   7138:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   7139:         my (%currprivs,%storeprivs);
                   7140:         foreach my $item (split(/:/,$coursepriv)) {
                   7141:             my ($priv,$restrict) = split(/\&/,$item);
                   7142:             $currprivs{$priv} = $restrict;
                   7143:         }
                   7144:         my (%possadd,%possremove,%full);
                   7145:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   7146:             my ($priv,$restrict)=split(/\&/,$item);
                   7147:             $full{$priv} = $restrict;
                   7148:         }
                   7149:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490    raeburn  7150:             next if ($item eq '');
                   7151:             my ($rule,$rest) = split(/=/,$item);
                   7152:             next unless (($rule eq 'off') || ($rule eq 'on'));
                   7153:             foreach my $priv (split(/:/,$rest)) {
                   7154:                 if ($priv ne '') {
                   7155:                     if ($rule eq 'off') {
                   7156:                         $possremove{$priv} = 1;
                   7157:                     } else {
                   7158:                         $possadd{$priv} = 1;
                   7159:                     }
                   7160:                 }
                   7161:             }
                   7162:         }
                   7163:         foreach my $priv (sort(keys(%full))) {
                   7164:             if (exists($currprivs{$priv})) {
                   7165:                 unless (exists($possremove{$priv})) {
                   7166:                     $storeprivs{$priv} = $currprivs{$priv};
                   7167:                 }
                   7168:             } elsif (exists($possadd{$priv})) {
                   7169:                 $storeprivs{$priv} = $full{$priv};
                   7170:             }
                   7171:         }
                   7172:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   7173:     }
                   7174:     return $coursepriv;
1.1332    raeburn  7175: }
                   7176: 
1.678     raeburn  7177: sub group_roleprivs {
                   7178:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   7179:     my $access = 1;
                   7180:     my $now = time;
                   7181:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   7182:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   7183:     if ($access) {
1.811     albertel 7184:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  7185:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   7186:     }
                   7187: }
1.567     raeburn  7188: 
                   7189: sub standard_roleprivs {
                   7190:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   7191:     if (defined($pr{$trole.':s'})) {
                   7192:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   7193:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   7194:     }
                   7195:     if ($tdomain ne '') {
                   7196:         if (defined($pr{$trole.':d'})) {
                   7197:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   7198:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   7199:         }
                   7200:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   7201:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   7202:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   7203:         }
                   7204:     }
                   7205: }
                   7206: 
                   7207: sub set_userprivs {
1.1064    raeburn  7208:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  7209:     my $author=0;
                   7210:     my $adv=0;
1.1341    raeburn  7211:     my $rar=0;
1.678     raeburn  7212:     my %grouproles = ();
                   7213:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  7214:         my @groupkeys; 
1.1000    raeburn  7215:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  7216:             push(@groupkeys,$role);
                   7217:         }
                   7218:         if (ref($groups_roles) eq 'HASH') {
                   7219:             foreach my $key (keys(%{$groups_roles})) {
                   7220:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   7221:                     push(@groupkeys,$key);
                   7222:                 }
                   7223:             }
                   7224:         }
                   7225:         if (@groupkeys > 0) {
                   7226:             foreach my $role (@groupkeys) {
                   7227:                 my ($trole,$area,$sec,$extendedarea);
                   7228:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   7229:                     $trole = $1;
                   7230:                     $area = $2;
                   7231:                     $sec = $3;
                   7232:                     $extendedarea = $area.$sec;
                   7233:                     if (exists($$allgroups{$area})) {
                   7234:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   7235:                             my $spec = $trole.'.'.$extendedarea;
                   7236:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  7237:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  7238:                         }
1.678     raeburn  7239:                     }
                   7240:                 }
                   7241:             }
                   7242:         }
                   7243:     }
1.800     albertel 7244:     foreach my $group (keys(%grouproles)) {
                   7245:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  7246:     }
1.800     albertel 7247:     foreach my $role (keys(%{$allroles})) {
                   7248:         my %thesepriv;
1.941     raeburn  7249:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 7250:         foreach my $item (split(/:/,$$allroles{$role})) {
                   7251:             if ($item ne '') {
                   7252:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  7253:                 if ($restrictions eq '') {
                   7254:                     $thesepriv{$privilege}='F';
                   7255:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   7256:                     $thesepriv{$privilege}.=$restrictions;
                   7257:                 }
                   7258:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  7259:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  7260:             }
                   7261:         }
                   7262:         my $thesestr='';
1.1104    raeburn  7263:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 7264: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   7265: 	}
                   7266:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  7267:     }
1.1341    raeburn  7268:     return ($author,$adv,$rar);
1.567     raeburn  7269: }
                   7270: 
1.994     raeburn  7271: sub role_status {
1.1104    raeburn  7272:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  7273:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  7274:         my ($one,$two) = split(m{\./},$rolekey,2);
                   7275:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  7276:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  7277:             $$where = '/'.$two;
1.994     raeburn  7278:             $$trolecode=$$role.'.'.$$where;
                   7279:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   7280:             $$tstatus='is';
1.1104    raeburn  7281:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  7282:                 $$tstatus='future';
1.1034    raeburn  7283:                 if ($$tstart<$now) {
                   7284:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  7285:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  7286:                             my (%allroles,%allgroups,$group_privs,
                   7287:                                 %groups_roles,@rolecodes);
1.1002    raeburn  7288:                             my %userroles = (
                   7289:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   7290:                             );
1.1064    raeburn  7291:                             @rolecodes = ('cm'); 
1.1002    raeburn  7292:                             my $spec=$$role.'.'.$$where;
                   7293:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   7294:                             if ($$role =~ /^cr\//) {
                   7295:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  7296:                                 push(@rolecodes,'cr');
1.1002    raeburn  7297:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  7298:                                 push(@rolecodes,$$role);
1.1002    raeburn  7299:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   7300:                                                     $env{'user.name'});
1.1064    raeburn  7301:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  7302:                                 (undef,my $group_privs) = split(/\//,$trole);
                   7303:                                 $group_privs = &unescape($group_privs);
                   7304:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  7305:                                 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  7306:                                 &get_groups_roles($tdomain,$trest,
                   7307:                                                   \%course_roles,\@rolecodes,
                   7308:                                                   \%groups_roles);
1.1002    raeburn  7309:                             } else {
1.1064    raeburn  7310:                                 push(@rolecodes,$$role);
1.1002    raeburn  7311:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7312:                             }
1.1341    raeburn  7313:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7314:                                                                    \%groups_roles);
1.1064    raeburn  7315:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  7316:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7317:                         }
                   7318:                     }
1.1034    raeburn  7319:                     $$tstatus = 'is';
1.1002    raeburn  7320:                 }
1.994     raeburn  7321:             }
                   7322:             if ($$tend) {
1.1104    raeburn  7323:                 if ($$tend<$update) {
1.994     raeburn  7324:                     $$tstatus='expired';
                   7325:                 } elsif ($$tend<$now) {
                   7326:                     $$tstatus='will_not';
                   7327:                 }
                   7328:             }
                   7329:         }
                   7330:     }
                   7331: }
                   7332: 
1.1104    raeburn  7333: sub get_groups_roles {
                   7334:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7335:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7336:                   (ref($rolecodes) eq 'ARRAY') && 
                   7337:                   (ref($groups_roles) eq 'HASH')); 
                   7338:     if (keys(%{$cdom_courseroles}) > 0) {
                   7339:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7340:         if ($cdom ne '' && $cnum ne '') {
                   7341:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7342:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7343:                     my $crsrole = $1;
                   7344:                     my $crssec = $2;
                   7345:                     if ($crsrole =~ /^cr/) {
                   7346:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7347:                             push(@{$rolecodes},'cr');
                   7348:                         }
                   7349:                     } else {
                   7350:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7351:                             push(@{$rolecodes},$crsrole);
                   7352:                         }
                   7353:                     }
                   7354:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7355:                     if ($crssec ne '') {
                   7356:                         $rolekey .= "/$crssec";
                   7357:                     }
                   7358:                     $rolekey .= './';
                   7359:                     $groups_roles->{$rolekey} = $rolecodes;
                   7360:                 }
                   7361:             }
                   7362:         }
                   7363:     }
                   7364:     return;
                   7365: }
                   7366: 
                   7367: sub delete_env_groupprivs {
                   7368:     my ($where,$courseroles,$possroles) = @_;
                   7369:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7370:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7371:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7372:         %{$courseroles->{$udom}} =
                   7373:             &get_my_roles('','','userroles',['active'],
                   7374:                           $possroles,[$udom],1);
                   7375:     }
                   7376:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7377:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7378:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7379:             my $area = '/'.$cdom.'/'.$cnum;
                   7380:             my $privkey = "user.priv.$crsrole.$area";
                   7381:             if ($crssec ne '') {
                   7382:                 $privkey .= '/'.$crssec;
                   7383:             }
                   7384:             $privkey .= ".$area/$group";
                   7385:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7386:         }
                   7387:     }
                   7388:     return;
                   7389: }
                   7390: 
1.994     raeburn  7391: sub check_adhoc_privs {
1.1329    raeburn  7392:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7393:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  7394:     if ($sec) {
                   7395:         $cckey .= '/'.$sec;
                   7396:     } 
1.1185    raeburn  7397:     my $setprivs;
1.994     raeburn  7398:     if ($env{$cckey}) {
                   7399:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7400:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7401:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  7402:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7403:             $setprivs = 1;
1.994     raeburn  7404:         }
                   7405:     } else {
1.1330    raeburn  7406:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7407:         $setprivs = 1;
1.994     raeburn  7408:     }
1.1185    raeburn  7409:     return $setprivs;
1.994     raeburn  7410: }
                   7411: 
                   7412: sub set_adhoc_privileges {
1.1326    raeburn  7413: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  7414:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7415:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  7416:     if ($sec ne '') {
                   7417:         $area .= '/'.$sec;
                   7418:     }
1.994     raeburn  7419:     my $spec = $role.'.'.$area;
                   7420:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  7421:                                   $env{'user.name'},1);
1.1326    raeburn  7422:     my %rolehash = ();
1.1332    raeburn  7423:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7424:         my $rolename = $1;
1.1326    raeburn  7425:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  7426:         my %domdef = &get_domain_defaults($dcdom);
                   7427:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7428:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7429:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7430:             }
                   7431:         }
1.1326    raeburn  7432:     } else {
                   7433:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7434:     }
1.1341    raeburn  7435:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7436:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  7437:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  7438:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7439:             ($caller eq 'tiny')) {
1.1088    raeburn  7440:         &appenv( {'request.role'        => $spec,
                   7441:                   'request.role.domain' => $dcdom,
1.1332    raeburn  7442:                   'request.course.sec'  => $sec,
1.1088    raeburn  7443:                  }
                   7444:                );
                   7445:         my $tadv=0;
                   7446:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7447:         &appenv({'request.role.adv'    => $tadv});
                   7448:     }
1.994     raeburn  7449: }
                   7450: 
1.12      www      7451: # --------------------------------------------------------------- get interface
                   7452: 
                   7453: sub get {
1.131     albertel 7454:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7455:    my $items='';
1.800     albertel 7456:    foreach my $item (@$storearr) {
                   7457:        $items.=&escape($item).'&';
1.191     harris41 7458:    }
1.12      www      7459:    $items=~s/\&$//;
1.620     albertel 7460:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7461:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7462:    my $uhome=&homeserver($uname,$udomain);
                   7463: 
1.133     albertel 7464:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7465:    my @pairs=split(/\&/,$rep);
1.273     albertel 7466:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7467:      return @pairs;
                   7468:    }
1.15      www      7469:    my %returnhash=();
1.42      www      7470:    my $i=0;
1.800     albertel 7471:    foreach my $item (@$storearr) {
                   7472:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7473:       $i++;
1.191     harris41 7474:    }
1.15      www      7475:    return %returnhash;
1.27      www      7476: }
                   7477: 
                   7478: # --------------------------------------------------------------- del interface
                   7479: 
                   7480: sub del {
1.133     albertel 7481:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7482:    my $items='';
1.800     albertel 7483:    foreach my $item (@$storearr) {
                   7484:        $items.=&escape($item).'&';
1.191     harris41 7485:    }
1.984     neumanie 7486: 
1.27      www      7487:    $items=~s/\&$//;
1.620     albertel 7488:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7489:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7490:    my $uhome=&homeserver($uname,$udomain);
                   7491:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7492: }
                   7493: 
                   7494: # -------------------------------------------------------------- dump interface
                   7495: 
1.1180    droeschl 7496: sub unserialize {
                   7497:     my ($rep, $escapedkeys) = @_;
                   7498: 
                   7499:     return {} if $rep =~ /^error/;
                   7500: 
                   7501:     my %returnhash=();
1.1252    raeburn  7502: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7503: 	    my ($key, $value) = split(/=/, $item, 2);
                   7504: 	    $key = unescape($key) unless $escapedkeys;
                   7505: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7506: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7507: 	}
                   7508:     #return %returnhash;
                   7509:     return \%returnhash;
                   7510: }        
                   7511: 
                   7512: # see Lond::dump_with_regexp
                   7513: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7514: sub dump {
1.1462    raeburn  7515:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7516:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7517:     if (!$uname) { $uname=$env{'user.name'}; }
                   7518:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7519: 
1.1266    raeburn  7520:     if ($regexp) {
                   7521:         $regexp=&escape($regexp);
                   7522:     } else {
                   7523:         $regexp='.';
                   7524:     }
1.1180    droeschl 7525:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7526:         # user is hosted on this machine
1.1266    raeburn  7527:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7528:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7529:         return %{unserialize($reply, $escapedkeys)};
                   7530:     }
1.1462    raeburn  7531:     my $rep;
                   7532:     if ($encrypt) {
                   7533:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463    raeburn  7534:     } else {
1.1462    raeburn  7535:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7536:     }
1.755     albertel 7537:     my @pairs=split(/\&/,$rep);
                   7538:     my %returnhash=();
1.1098    foxr     7539:     if (!($rep =~ /^error/ )) {
                   7540: 	foreach my $item (@pairs) {
                   7541: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7542:         $key = unescape($key) unless $escapedkeys;
                   7543:         #$key = &unescape($key);
1.1098    foxr     7544: 	    next if ($key =~ /^error: 2 /);
                   7545: 	    $returnhash{$key}=&thaw_unescape($value);
                   7546: 	}
1.755     albertel 7547:     }
                   7548:     return %returnhash;
1.407     www      7549: }
                   7550: 
1.1098    foxr     7551: 
1.717     albertel 7552: # --------------------------------------------------------- dumpstore interface
                   7553: 
                   7554: sub dumpstore {
                   7555:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7556:    # same as dump but keys must be escaped. They may contain colon separated
                   7557:    # lists of values that may themself contain colons (e.g. symbs).
                   7558:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7559: }
                   7560: 
1.407     www      7561: # -------------------------------------------------------------- keys interface
                   7562: 
                   7563: sub getkeys {
                   7564:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7565:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7566:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7567:    my $uhome=&homeserver($uname,$udomain);
                   7568:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7569:    my @keyarray=();
1.800     albertel 7570:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7571:       next if ($key =~ /^error: 2 /);
1.800     albertel 7572:       push(@keyarray,&unescape($key));
1.407     www      7573:    }
                   7574:    return @keyarray;
1.318     matthew  7575: }
                   7576: 
1.319     matthew  7577: # --------------------------------------------------------------- currentdump
                   7578: sub currentdump {
1.328     matthew  7579:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7580:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7581:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7582:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7583:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7584:    my $rep;
                   7585: 
                   7586:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7587:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7588:                    $courseid)));
                   7589:    } else {
                   7590:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7591:    }
                   7592: 
1.318     matthew  7593:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7594:    #
1.318     matthew  7595:    my %returnhash=();
1.319     matthew  7596:    #
1.1343    raeburn  7597:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7598:        # an old lond will not know currentdump
                   7599:        # Do a dump and make it look like a currentdump
1.822     albertel 7600:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7601:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7602:        my %hash = @tmp;
                   7603:        @tmp=();
1.424     matthew  7604:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7605:    } else {
                   7606:        my @pairs=split(/\&/,$rep);
1.800     albertel 7607:        foreach my $pair (@pairs) {
                   7608:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7609:            my ($symb,$param) = split(/:/,$key);
                   7610:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7611:                                                         &thaw_unescape($value);
1.319     matthew  7612:        }
1.191     harris41 7613:    }
1.12      www      7614:    return %returnhash;
1.424     matthew  7615: }
                   7616: 
                   7617: sub convert_dump_to_currentdump{
                   7618:     my %hash = %{shift()};
                   7619:     my %returnhash;
                   7620:     # Code ripped from lond, essentially.  The only difference
                   7621:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7622:     # we might run in to problems with parameter names =~ /^v\./
                   7623:     while (my ($key,$value) = each(%hash)) {
                   7624:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7625: 	$symb  = &unescape($symb);
                   7626: 	$param = &unescape($param);
1.424     matthew  7627:         next if ($v eq 'version' || $symb eq 'keys');
                   7628:         next if (exists($returnhash{$symb}) &&
                   7629:                  exists($returnhash{$symb}->{$param}) &&
                   7630:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7631:         $returnhash{$symb}->{$param}=$value;
                   7632:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7633:     }
                   7634:     #
                   7635:     # Remove all of the keys in the hashes which keep track of
                   7636:     # the version of the parameter.
                   7637:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7638:         # use a foreach because we are going to delete from the hash.
                   7639:         foreach my $key (keys(%$param_hash)) {
                   7640:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7641:         }
                   7642:     }
                   7643:     return \%returnhash;
1.12      www      7644: }
                   7645: 
1.627     albertel 7646: # ------------------------------------------------------ critical inc interface
                   7647: 
                   7648: sub cinc {
                   7649:     return &inc(@_,'critical');
                   7650: }
                   7651: 
1.449     matthew  7652: # --------------------------------------------------------------- inc interface
                   7653: 
                   7654: sub inc {
1.627     albertel 7655:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7656:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7657:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7658:     my $uhome=&homeserver($uname,$udomain);
                   7659:     my $items='';
                   7660:     if (! ref($store)) {
                   7661:         # got a single value, so use that instead
                   7662:         $items = &escape($store).'=&';
                   7663:     } elsif (ref($store) eq 'SCALAR') {
                   7664:         $items = &escape($$store).'=&';        
                   7665:     } elsif (ref($store) eq 'ARRAY') {
                   7666:         $items = join('=&',map {&escape($_);} @{$store});
                   7667:     } elsif (ref($store) eq 'HASH') {
                   7668:         while (my($key,$value) = each(%{$store})) {
                   7669:             $items.= &escape($key).'='.&escape($value).'&';
                   7670:         }
                   7671:     }
                   7672:     $items=~s/\&$//;
1.627     albertel 7673:     if ($critical) {
                   7674: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7675:     } else {
                   7676: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7677:     }
1.449     matthew  7678: }
                   7679: 
1.12      www      7680: # --------------------------------------------------------------- put interface
                   7681: 
                   7682: sub put {
1.1462    raeburn  7683:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7684:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7685:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7686:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7687:    my $items='';
1.800     albertel 7688:    foreach my $item (keys(%$storehash)) {
                   7689:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7690:    }
1.12      www      7691:    $items=~s/\&$//;
1.1462    raeburn  7692:    if ($encrypt) {
                   7693:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7694:    } else {
                   7695:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7696:    }
1.47      www      7697: }
                   7698: 
1.631     albertel 7699: # ------------------------------------------------------------ newput interface
                   7700: 
                   7701: sub newput {
                   7702:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7703:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7704:    if (!$uname) { $uname=$env{'user.name'}; }
                   7705:    my $uhome=&homeserver($uname,$udomain);
                   7706:    my $items='';
                   7707:    foreach my $key (keys(%$storehash)) {
                   7708:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7709:    }
                   7710:    $items=~s/\&$//;
                   7711:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7712: }
                   7713: 
                   7714: # ---------------------------------------------------------  putstore interface
                   7715: 
1.524     raeburn  7716: sub putstore {
1.1269    raeburn  7717:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7718:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7719:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7720:    my $uhome=&homeserver($uname,$udomain);
                   7721:    my $items='';
1.715     albertel 7722:    foreach my $key (keys(%$storehash)) {
                   7723:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7724:    }
1.715     albertel 7725:    $items=~s/\&$//;
1.716     albertel 7726:    my $esc_symb=&escape($symb);
                   7727:    my $esc_v=&escape($version);
1.715     albertel 7728:    my $reply =
1.716     albertel 7729:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7730: 	      $uhome);
1.1269    raeburn  7731:    if (($tolog) && ($reply eq 'ok')) {
                   7732:        my $namevalue='';
                   7733:        foreach my $key (keys(%{$storehash})) {
                   7734:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7735:        }
1.1434    raeburn  7736:        my $ip = &get_requestor_ip();
                   7737:        $namevalue .= 'ip='.&escape($ip).
1.1269    raeburn  7738:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7739:                      '&version='.$esc_v.
                   7740:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
1.1494    raeburn  7741:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
1.1269    raeburn  7742:    }
1.715     albertel 7743:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7744:        # gfall back to way things use to be done
1.715     albertel 7745:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7746: 			    $uname);
1.524     raeburn  7747:    }
1.715     albertel 7748:    return $reply;
                   7749: }
                   7750: 
                   7751: sub old_putstore {
1.716     albertel 7752:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7753:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7754:     if (!$uname) { $uname=$env{'user.name'}; }
                   7755:     my $uhome=&homeserver($uname,$udomain);
                   7756:     my %newstorehash;
1.800     albertel 7757:     foreach my $item (keys(%$storehash)) {
                   7758: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7759: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7760:     }
                   7761:     my $items='';
                   7762:     my %allitems = ();
1.800     albertel 7763:     foreach my $item (keys(%newstorehash)) {
                   7764: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7765: 	    my $key = $1.':keys:'.$2;
                   7766: 	    $allitems{$key} .= $3.':';
                   7767: 	}
1.800     albertel 7768: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7769:     }
1.800     albertel 7770:     foreach my $item (keys(%allitems)) {
                   7771: 	$allitems{$item} =~ s/\:$//;
                   7772: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7773:     }
                   7774:     $items=~s/\&$//;
                   7775:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7776: }
                   7777: 
1.47      www      7778: # ------------------------------------------------------ critical put interface
                   7779: 
                   7780: sub cput {
1.134     albertel 7781:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7782:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7783:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7784:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7785:    my $items='';
1.800     albertel 7786:    foreach my $item (keys(%$storehash)) {
                   7787:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7788:    }
1.47      www      7789:    $items=~s/\&$//;
1.134     albertel 7790:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7791: }
                   7792: 
                   7793: # -------------------------------------------------------------- eget interface
                   7794: 
                   7795: sub eget {
1.133     albertel 7796:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7797:    my $items='';
1.800     albertel 7798:    foreach my $item (@$storearr) {
                   7799:        $items.=&escape($item).'&';
1.191     harris41 7800:    }
1.12      www      7801:    $items=~s/\&$//;
1.620     albertel 7802:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7803:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7804:    my $uhome=&homeserver($uname,$udomain);
                   7805:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7806:    my @pairs=split(/\&/,$rep);
                   7807:    my %returnhash=();
1.42      www      7808:    my $i=0;
1.800     albertel 7809:    foreach my $item (@$storearr) {
                   7810:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7811:       $i++;
1.191     harris41 7812:    }
1.12      www      7813:    return %returnhash;
                   7814: }
                   7815: 
1.667     albertel 7816: # ------------------------------------------------------------ tmpput interface
                   7817: sub tmpput {
1.802     raeburn  7818:     my ($storehash,$server,$context)=@_;
1.667     albertel 7819:     my $items='';
1.800     albertel 7820:     foreach my $item (keys(%$storehash)) {
                   7821: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7822:     }
                   7823:     $items=~s/\&$//;
1.802     raeburn  7824:     if (defined($context)) {
                   7825:         $items .= ':'.&escape($context);
                   7826:     }
1.667     albertel 7827:     return &reply("tmpput:$items",$server);
                   7828: }
                   7829: 
                   7830: # ------------------------------------------------------------ tmpget interface
                   7831: sub tmpget {
1.688     albertel 7832:     my ($token,$server)=@_;
                   7833:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7834:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7835:     my %returnhash;
1.1328    raeburn  7836:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7837:         return %returnhash;
                   7838:     }
1.667     albertel 7839:     foreach my $item (split(/\&/,$rep)) {
                   7840: 	my ($key,$value)=split(/=/,$item);
                   7841: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7842:     }
                   7843:     return %returnhash;
                   7844: }
                   7845: 
1.1113    raeburn  7846: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7847: sub tmpdel {
                   7848:     my ($token,$server)=@_;
                   7849:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7850:     return &reply("tmpdel:$token",$server);
                   7851: }
                   7852: 
1.1198    raeburn  7853: # ------------------------------------------------------------ get_timebased_id 
                   7854: 
                   7855: sub get_timebased_id {
                   7856:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7857:         $maxtries) = @_;
                   7858:     my ($newid,$error,$dellock);
                   7859:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7860:         return ('','ok','invalid call to get suffix');
                   7861:     }
                   7862: 
                   7863: # set defaults for any optional args for which values were not supplied
                   7864:     if ($who eq '') {
                   7865:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7866:     }
                   7867:     if (!$locktries) {
                   7868:         $locktries = 3;
                   7869:     }
                   7870:     if (!$maxtries) {
                   7871:         $maxtries = 10;
                   7872:     }
                   7873:     
                   7874:     if (($cdom eq '') || ($cnum eq '')) {
                   7875:         if ($env{'request.course.id'}) {
                   7876:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7877:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7878:         }
                   7879:         if (($cdom eq '') || ($cnum eq '')) {
                   7880:             return ('','ok','call to get suffix not in course context');
                   7881:         }
                   7882:     }
                   7883: 
                   7884: # construct locking item
                   7885:     my $lockhash = {
                   7886:                       $prefix."\0".'locked_'.$keyid => $who,
                   7887:                    };
                   7888:     my $tries = 0;
                   7889: 
                   7890: # attempt to get lock on nohist_$namespace file
1.1494    raeburn  7891:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198    raeburn  7892:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7893:         $tries ++;
                   7894:         sleep 1;
1.1494    raeburn  7895:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198    raeburn  7896:     }
                   7897: 
                   7898: # attempt to get unique identifier, based on current timestamp
                   7899:     if ($gotlock eq 'ok') {
1.1494    raeburn  7900:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
1.1198    raeburn  7901:         my $id = time;
                   7902:         $newid = $id;
1.1268    raeburn  7903:         if ($idtype eq 'addcode') {
                   7904:             $newid .= &sixnum_code();
                   7905:         }
1.1198    raeburn  7906:         my $idtries = 0;
                   7907:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7908:             if ($idtype eq 'concat') {
                   7909:                 $newid = $id.$idtries;
1.1268    raeburn  7910:             } elsif ($idtype eq 'addcode') {
                   7911:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7912:             } else {
                   7913:                 $newid ++;
                   7914:             }
                   7915:             $idtries ++;
                   7916:         }
                   7917:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7918:             my %new_item =  (
                   7919:                               $prefix."\0".$newid => $who,
                   7920:                             );
1.1494    raeburn  7921:             my $putresult = &put('nohist_'.$namespace,\%new_item,
1.1198    raeburn  7922:                                                  $cdom,$cnum);
                   7923:             if ($putresult ne 'ok') {
                   7924:                 undef($newid);
                   7925:                 $error = 'error saving new item: '.$putresult;
                   7926:             }
                   7927:         } else {
1.1268    raeburn  7928:              undef($newid);
1.1198    raeburn  7929:              $error = ('error: no unique suffix available for the new item ');
                   7930:         }
                   7931: #  remove lock
                   7932:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7933:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7934:     } else {
                   7935:         $error = "error: could not obtain lockfile\n";
                   7936:         $dellock = 'ok';
1.1276    raeburn  7937:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7938:             $dellock = 'nolock';
                   7939:         }
1.1198    raeburn  7940:     }
                   7941:     return ($newid,$dellock,$error);
                   7942: }
                   7943: 
1.1268    raeburn  7944: sub sixnum_code {
                   7945:     my $code;
                   7946:     for (0..6) {
                   7947:         $code .= int( rand(9) );
                   7948:     }
                   7949:     return $code;
                   7950: }
                   7951: 
1.765     albertel 7952: # -------------------------------------------------- portfolio access checking
                   7953: 
                   7954: sub portfolio_access {
1.1270    raeburn  7955:     my ($requrl,$clientip) = @_;
1.765     albertel 7956:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7957:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7958:     if ($result) {
                   7959:         my %setters;
                   7960:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473    raeburn  7961:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7962:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7963:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7964:                 return 'B';
                   7965:             }
                   7966:         } else {
1.1473    raeburn  7967:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7968:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7969:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7970:                 return 'B';
                   7971:             }
                   7972:         }
                   7973:     }
1.765     albertel 7974:     if ($result eq 'ok') {
1.766     albertel 7975:        return 'F';
1.765     albertel 7976:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7977:        return 'A';
1.765     albertel 7978:     }
1.766     albertel 7979:     return '';
1.765     albertel 7980: }
                   7981: 
                   7982: sub get_portfolio_access {
1.1270    raeburn  7983:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7984: 
                   7985:     if (!ref($access_hash)) {
                   7986: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7987: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7988: 						   $file_name);
                   7989: 	$access_hash = $access_controls{$file_name};
                   7990:     }
                   7991: 
1.1270    raeburn  7992:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7993:     my $now = time;
                   7994:     if (ref($access_hash) eq 'HASH') {
                   7995:         foreach my $key (keys(%{$access_hash})) {
                   7996:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7997:             if ($start > $now) {
                   7998:                 next;
                   7999:             }
                   8000:             if ($end && $end<$now) {
                   8001:                 next;
                   8002:             }
                   8003:             if ($scope eq 'public') {
                   8004:                 $public = $key;
                   8005:                 last;
                   8006:             } elsif ($scope eq 'guest') {
                   8007:                 $guest = $key;
                   8008:             } elsif ($scope eq 'domains') {
                   8009:                 push(@domains,$key);
                   8010:             } elsif ($scope eq 'users') {
                   8011:                 push(@users,$key);
                   8012:             } elsif ($scope eq 'course') {
                   8013:                 push(@courses,$key);
                   8014:             } elsif ($scope eq 'group') {
                   8015:                 push(@groups,$key);
1.1270    raeburn  8016:             } elsif ($scope eq 'ip') {
                   8017:                 push(@ips,$key);
1.765     albertel 8018:             }
                   8019:         }
                   8020:         if ($public) {
                   8021:             return 'ok';
1.1270    raeburn  8022:         } elsif (@ips > 0) {
                   8023:             my $allowed;
                   8024:             foreach my $ipkey (@ips) {
                   8025:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   8026:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   8027:                         $allowed = 1;
                   8028:                         last; 
                   8029:                     }
                   8030:                 }
                   8031:             }
                   8032:             if ($allowed) {
                   8033:                 return 'ok';
                   8034:             }
1.765     albertel 8035:         }
                   8036:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   8037:             if ($guest) {
                   8038:                 return $guest;
                   8039:             }
                   8040:         } else {
                   8041:             if (@domains > 0) {
                   8042:                 foreach my $domkey (@domains) {
                   8043:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   8044:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   8045:                             return 'ok';
                   8046:                         }
                   8047:                     }
                   8048:                 }
                   8049:             }
                   8050:             if (@users > 0) {
                   8051:                 foreach my $userkey (@users) {
1.865     raeburn  8052:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   8053:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   8054:                             if (ref($item) eq 'HASH') {
                   8055:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   8056:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   8057:                                     return 'ok';
                   8058:                                 }
                   8059:                             }
                   8060:                         }
                   8061:                     } 
1.765     albertel 8062:                 }
                   8063:             }
                   8064:             my %roleshash;
                   8065:             my @courses_and_groups = @courses;
                   8066:             push(@courses_and_groups,@groups); 
                   8067:             if (@courses_and_groups > 0) {
                   8068:                 my (%allgroups,%allroles); 
                   8069:                 my ($start,$end,$role,$sec,$group);
                   8070:                 foreach my $envkey (%env) {
1.1060    raeburn  8071:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 8072:                         my $cid = $2.'_'.$3; 
                   8073:                         if ($1 eq 'gr') {
                   8074:                             $group = $4;
                   8075:                             $allgroups{$cid}{$group} = $env{$envkey};
                   8076:                         } else {
                   8077:                             if ($4 eq '') {
                   8078:                                 $sec = 'none';
                   8079:                             } else {
                   8080:                                 $sec = $4;
                   8081:                             }
                   8082:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   8083:                         }
1.811     albertel 8084:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 8085:                         my $cid = $2.'_'.$3;
                   8086:                         if ($4 eq '') {
                   8087:                             $sec = 'none';
                   8088:                         } else {
                   8089:                             $sec = $4;
                   8090:                         }
                   8091:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   8092:                     }
                   8093:                 }
                   8094:                 if (keys(%allroles) == 0) {
                   8095:                     return;
                   8096:                 }
                   8097:                 foreach my $key (@courses_and_groups) {
                   8098:                     my %content = %{$$access_hash{$key}};
                   8099:                     my $cnum = $content{'number'};
                   8100:                     my $cdom = $content{'domain'};
                   8101:                     my $cid = $cdom.'_'.$cnum;
                   8102:                     if (!exists($allroles{$cid})) {
                   8103:                         next;
                   8104:                     }    
                   8105:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   8106:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   8107:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   8108:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   8109:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   8110:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   8111:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   8112:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   8113:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   8114:                                         if (grep/^all$/,@sections) {
                   8115:                                             return 'ok';
                   8116:                                         } else {
                   8117:                                             if (grep/^$sec$/,@sections) {
                   8118:                                                 return 'ok';
                   8119:                                             }
                   8120:                                         }
                   8121:                                     }
                   8122:                                 }
                   8123:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   8124:                                     if (grep/^none$/,@groups) {
                   8125:                                         return 'ok';
                   8126:                                     }
                   8127:                                 } else {
                   8128:                                     if (grep/^all$/,@groups) {
                   8129:                                         return 'ok';
                   8130:                                     } 
                   8131:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   8132:                                         if (grep/^$group$/,@groups) {
                   8133:                                             return 'ok';
                   8134:                                         }
                   8135:                                     }
                   8136:                                 } 
                   8137:                             }
                   8138:                         }
                   8139:                     }
                   8140:                 }
                   8141:             }
                   8142:             if ($guest) {
                   8143:                 return $guest;
                   8144:             }
                   8145:         }
                   8146:     }
                   8147:     return;
                   8148: }
                   8149: 
                   8150: sub course_group_datechecker {
                   8151:     my ($dates,$now,$status) = @_;
                   8152:     my ($start,$end) = split(/\./,$dates);
                   8153:     if (!$start && !$end) {
                   8154:         return 'ok';
                   8155:     }
                   8156:     if (grep/^active$/,@{$status}) {
                   8157:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   8158:             return 'ok';
                   8159:         }
                   8160:     }
                   8161:     if (grep/^previous$/,@{$status}) {
                   8162:         if ($end > $now ) {
                   8163:             return 'ok';
                   8164:         }
                   8165:     }
                   8166:     if (grep/^future$/,@{$status}) {
                   8167:         if ($start > $now) {
                   8168:             return 'ok';
                   8169:         }
                   8170:     }
                   8171:     return; 
                   8172: }
                   8173: 
                   8174: sub parse_portfolio_url {
                   8175:     my ($url) = @_;
                   8176: 
                   8177:     my ($type,$udom,$unum,$group,$file_name);
                   8178:     
1.823     albertel 8179:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 8180: 	$type = 1;
                   8181:         $udom = $1;
                   8182:         $unum = $2;
                   8183:         $file_name = $3;
1.823     albertel 8184:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 8185: 	$type = 2;
                   8186:         $udom = $1;
                   8187:         $unum = $2;
                   8188:         $group = $3;
                   8189:         $file_name = $3.'/'.$4;
                   8190:     }
                   8191:     if (wantarray) {
                   8192: 	return ($type,$udom,$unum,$file_name,$group);
                   8193:     }
                   8194:     return $type;
                   8195: }
                   8196: 
                   8197: sub is_portfolio_url {
                   8198:     my ($url) = @_;
                   8199:     return scalar(&parse_portfolio_url($url));
                   8200: }
                   8201: 
1.798     raeburn  8202: sub is_portfolio_file {
                   8203:     my ($file) = @_;
1.820     raeburn  8204:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  8205:         return 1;
                   8206:     }
                   8207:     return;
                   8208: }
                   8209: 
1.1504    raeburn  8210: sub is_coursetool_logo {
                   8211:     my ($uri) = @_;
                   8212:     if ($env{'request.course.id'}) {
                   8213:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8214:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
                   8215:             return 1;
                   8216:         }
                   8217:     }
                   8218:     return;
                   8219: }
                   8220: 
1.976     raeburn  8221: sub usertools_access {
1.1084    raeburn  8222:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  8223:     my ($access,%tools);
                   8224:     if ($context eq '') {
                   8225:         $context = 'tools';
                   8226:     }
                   8227:     if ($context eq 'requestcourses') {
                   8228:         %tools = (
                   8229:                       official   => 1,
                   8230:                       unofficial => 1,
1.1006    raeburn  8231:                       community  => 1,
1.1246    raeburn  8232:                       textbook   => 1,
1.1305    raeburn  8233:                       placement  => 1,
1.1368    raeburn  8234:                       lti        => 1,
1.985     raeburn  8235:                  );
1.1183    raeburn  8236:     } elsif ($context eq 'requestauthor') {
                   8237:         %tools = (
                   8238:                       requestauthor => 1,
                   8239:                  );
1.1517  ! raeburn  8240:     } elsif ($context eq 'authordefaults') {
        !          8241:         %tools = (
        !          8242:                       webdav    => 1,
        !          8243:                       editors   => 1,
        !          8244:                  );
1.985     raeburn  8245:     } else {
                   8246:         %tools = (
                   8247:                       aboutme   => 1,
                   8248:                       blog      => 1,
                   8249:                       portfolio => 1,
1.1517  ! raeburn  8250:                       portaccess => 1,
1.1489    raeburn  8251:                       timezone  => 1,
1.985     raeburn  8252:                  );
                   8253:     }
1.976     raeburn  8254:     return if (!defined($tools{$tool}));
                   8255: 
1.1242    raeburn  8256:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  8257:         $udom = $env{'user.domain'};
                   8258:         $uname = $env{'user.name'};
                   8259:     }
                   8260: 
1.978     raeburn  8261:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   8262:         if ($action ne 'reload') {
1.985     raeburn  8263:             if ($context eq 'requestcourses') {
                   8264:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  8265:             } elsif ($context eq 'requestauthor') {
                   8266:                 return $env{'environment.canrequest.author'};
1.1517  ! raeburn  8267:             } elsif ($context eq 'authordefaults') {
        !          8268:                 if ($tool eq 'webdav') {
        !          8269:                     return $env{'environment.availabletools.'.$tool};
        !          8270:                 } elsif ($tool eq 'editors') {
        !          8271:                     return $env{'environment.authoreditors'};
        !          8272:                 }
1.985     raeburn  8273:             } else {
                   8274:                 return $env{'environment.availabletools.'.$tool};
                   8275:             }
                   8276:         }
1.976     raeburn  8277:     }
                   8278: 
1.1183    raeburn  8279:     my ($toolstatus,$inststatus,$envkey);
                   8280:     if ($context eq 'requestauthor') {
1.1517  ! raeburn  8281:         $envkey = $context;
        !          8282:     } elsif ($context eq 'authordefaults') {
        !          8283:         if ($tool eq 'webdav') {
        !          8284:             $envkey = 'tools.'.$tool;
        !          8285:         } elsif ($tool eq 'editors') {
        !          8286:             $envkey = 'author'.$tool;
        !          8287:         }
1.1183    raeburn  8288:     } else {
                   8289:         $envkey = $context.'.'.$tool;
                   8290:     }
1.976     raeburn  8291: 
1.985     raeburn  8292:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8293:          ($action ne 'reload')) {
1.1183    raeburn  8294:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  8295:         $inststatus = $env{'environment.inststatus'};
                   8296:     } else {
1.1084    raeburn  8297:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  8298:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  8299:             $inststatus = $userenvref->{'inststatus'};
                   8300:         } else {
1.1183    raeburn  8301:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   8302:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  8303:             $inststatus = $userenv{'inststatus'};
                   8304:         }
1.976     raeburn  8305:     }
                   8306: 
                   8307:     if ($toolstatus ne '') {
                   8308:         if ($toolstatus) {
                   8309:             $access = 1;
                   8310:         } else {
                   8311:             $access = 0;
                   8312:         }
                   8313:         return $access;
                   8314:     }
                   8315: 
1.1084    raeburn  8316:     my ($is_adv,%domdef);
                   8317:     if (ref($is_advref) eq 'HASH') {
                   8318:         $is_adv = $is_advref->{'is_adv'};
                   8319:     } else {
                   8320:         $is_adv = &is_advanced_user($udom,$uname);
                   8321:     }
                   8322:     if (ref($domdefref) eq 'HASH') {
                   8323:         %domdef = %{$domdefref};
                   8324:     } else {
                   8325:         %domdef = &get_domain_defaults($udom);
                   8326:     }
1.976     raeburn  8327:     if (ref($domdef{$tool}) eq 'HASH') {
                   8328:         if ($is_adv) {
                   8329:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8330:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8331:                     $access = 1;
                   8332:                 } else {
                   8333:                     $access = 0;
                   8334:                 }
                   8335:                 return $access;
                   8336:             }
                   8337:         }
                   8338:         if ($inststatus ne '') {
                   8339:             my ($hasaccess,$hasnoaccess);
                   8340:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8341:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8342:                     if ($domdef{$tool}{$affiliation}) {
                   8343:                         $hasaccess = 1;
                   8344:                     } else {
                   8345:                         $hasnoaccess = 1;
                   8346:                     }
                   8347:                 }
                   8348:             }
                   8349:             if ($hasaccess || $hasnoaccess) {
                   8350:                 if ($hasaccess) {
                   8351:                     $access = 1;
                   8352:                 } elsif ($hasnoaccess) {
                   8353:                     $access = 0; 
                   8354:                 }
                   8355:                 return $access;
                   8356:             }
                   8357:         } else {
                   8358:             if ($domdef{$tool}{'default'} ne '') {
                   8359:                 if ($domdef{$tool}{'default'}) {
                   8360:                     $access = 1;
                   8361:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8362:                     $access = 0;
                   8363:                 }
                   8364:                 return $access;
                   8365:             }
                   8366:         }
                   8367:     } else {
1.1177    raeburn  8368:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8369:             $access = 1;
                   8370:         } else {
                   8371:             $access = 0;
                   8372:         }
1.976     raeburn  8373:         return $access;
                   8374:     }
                   8375: }
                   8376: 
1.1050    raeburn  8377: sub is_course_owner {
                   8378:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8379:     if (($udom eq '') || ($uname eq '')) {
                   8380:         $udom = $env{'user.domain'};
                   8381:         $uname = $env{'user.name'};
                   8382:     }
                   8383:     unless (($udom eq '') || ($uname eq '')) {
                   8384:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8385:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8386:                 return 1;
                   8387:             } else {
1.1494    raeburn  8388:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
1.1050    raeburn  8389:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8390:                     return 1;
                   8391:                 }
                   8392:             }
                   8393:         }
                   8394:     }
                   8395:     return;
                   8396: }
                   8397: 
1.976     raeburn  8398: sub is_advanced_user {
1.1512    raeburn  8399:     my ($udom,$uname,$nocache) = @_;
                   8400:     my ($is_adv,$is_author,$use_cache,$hashid);
1.1085    raeburn  8401:     if ($udom ne '' && $uname ne '') {
                   8402:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8403:             if (wantarray) {
                   8404:                 return ($env{'user.adv'},$env{'user.author'});
                   8405:             } else {
                   8406:                 return $env{'user.adv'};
                   8407:             }
1.1512    raeburn  8408:         } elsif (!$nocache) {
                   8409:             $use_cache = 1;
                   8410:             $hashid = "$udom:$uname";  
                   8411:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
                   8412:             if ($cached) {
                   8413:                 ($is_adv,$is_author) = split(/:/,$info);
                   8414:                 if (wantarray) {
                   8415:                     return ($is_adv,$is_author);
                   8416:                 }
                   8417:                 return $is_adv; 
                   8418:             }
1.1085    raeburn  8419:         }
                   8420:     }
1.976     raeburn  8421:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8422:     my %allroles;
                   8423:     foreach my $role (keys(%roleshash)) {
                   8424:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8425:         my $area = '/'.$tdomain.'/'.$trest;
                   8426:         if ($sec ne '') {
                   8427:             $area .= '/'.$sec;
                   8428:         }
                   8429:         if (($area ne '') && ($trole ne '')) {
                   8430:             my $spec=$trole.'.'.$area;
                   8431:             if ($trole =~ /^cr\//) {
                   8432:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8433:             } elsif ($trole ne 'gr') {
                   8434:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8435:             }
1.1128    raeburn  8436:             if ($trole eq 'au') {
                   8437:                 $is_author = 1;
                   8438:             }
1.976     raeburn  8439:         }
                   8440:     }
                   8441:     foreach my $role (keys(%allroles)) {
                   8442:         last if ($is_adv);
                   8443:         foreach my $item (split(/:/,$allroles{$role})) {
                   8444:             if ($item ne '') {
                   8445:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8446:                 if ($privilege eq 'adv') {
                   8447:                     $is_adv = 1;
                   8448:                     last;
                   8449:                 }
                   8450:             }
                   8451:         }
                   8452:     }
1.1512    raeburn  8453:     if ($use_cache) {
                   8454:         my $cachetime = 600;
                   8455:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
                   8456:     }
1.1128    raeburn  8457:     if (wantarray) {
                   8458:         return ($is_adv,$is_author);
                   8459:     }
1.976     raeburn  8460:     return $is_adv;
                   8461: }
1.798     raeburn  8462: 
1.1035    raeburn  8463: sub check_can_request {
1.1368    raeburn  8464:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8465:     my $canreq = 0;
1.1368    raeburn  8466:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8467:         $uname = $env{'user.name'};
                   8468:         $udom = $env{'user.domain'};
                   8469:     }
1.1035    raeburn  8470:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8471:     my @options = ('approval','validate','autolimit');
                   8472:     my $optregex = join('|',@options);
                   8473:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486    raeburn  8474:         my %willtrust;
1.1035    raeburn  8475:         foreach my $type (@{$types}) {
1.1368    raeburn  8476:             if (&usertools_access($uname,$udom,$type,undef,
                   8477:                                   'requestcourses')) {
1.1035    raeburn  8478:                 $canreq ++;
1.1036    raeburn  8479:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  8480:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8481:                 }
1.1368    raeburn  8482:                 if ($dom eq $udom) {
1.1035    raeburn  8483:                     $can_request->{$type} = 1;
                   8484:                 }
                   8485:             }
1.1368    raeburn  8486:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8487:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8488:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8489:                 if (@curr > 0) {
1.1036    raeburn  8490:                     foreach my $item (@curr) {
                   8491:                         if (ref($request_domains) eq 'HASH') {
                   8492:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8493:                             if ($otherdom ne '') {
1.1486    raeburn  8494:                                 unless (exists($willtrust{$otherdom})) {
                   8495:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
                   8496:                                 }
                   8497:                                 if ($willtrust{$otherdom}) {
                   8498:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8499:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8500:                                             push(@{$request_domains->{$type}},$otherdom);
                   8501:                                         }
                   8502:                                     } else {
1.1036    raeburn  8503:                                         push(@{$request_domains->{$type}},$otherdom);
                   8504:                                     }
                   8505:                                 }
                   8506:                             }
                   8507:                         }
                   8508:                     }
1.1368    raeburn  8509:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8510:                         $canreq ++;
1.1035    raeburn  8511:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8512:                             $can_request->{$type} = 1;
                   8513:                         }
                   8514:                     }
                   8515:                 }
                   8516:             }
                   8517:         }
                   8518:     }
                   8519:     return $canreq;
                   8520: }
                   8521: 
1.341     www      8522: # ---------------------------------------------- Custom access rule evaluation
                   8523: 
                   8524: sub customaccess {
                   8525:     my ($priv,$uri)=@_;
1.807     albertel 8526:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8527:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8528:     $udom = &LONCAPA::clean_domain($udom);
                   8529:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8530:     my $access=0;
1.800     albertel 8531:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8532: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8533: 	if ($type eq 'user') {
                   8534: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8535: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8536: 		if ($tdom) {
                   8537: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8538: 		}
1.896     albertel 8539: 		if ($tuname) {
                   8540: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8541: 		}
                   8542: 		$access=($effect eq 'allow');
                   8543: 		last;
                   8544: 	    }
                   8545: 	} else {
                   8546: 	    if ($role) {
                   8547: 		if ($role ne $urole) { next; }
                   8548: 	    }
                   8549: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8550: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8551: 		if ($tdom) {
                   8552: 		    if ($tdom ne $udom) { next; }
                   8553: 		}
                   8554: 		if ($tcrs) {
                   8555: 		    if ($tcrs ne $ucrs) { next; }
                   8556: 		}
                   8557: 		if ($tsec) {
                   8558: 		    if ($tsec ne $usec) { next; }
                   8559: 		}
                   8560: 		$access=($effect eq 'allow');
                   8561: 		last;
                   8562: 	    }
                   8563: 	    if ($realm eq '' && $role eq '') {
                   8564: 		$access=($effect eq 'allow');
                   8565: 	    }
1.402     bowersj2 8566: 	}
1.341     www      8567:     }
                   8568:     return $access;
                   8569: }
                   8570: 
1.103     harris41 8571: # ------------------------------------------------- Check for a user privilege
1.12      www      8572: 
                   8573: sub allowed {
1.1461    raeburn  8574:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8575:     my $ver_orguri=$uri;
1.439     www      8576:     $uri=&deversion($uri);
1.152     www      8577:     my $orguri=$uri;
1.52      www      8578:     $uri=&declutter($uri);
1.809     raeburn  8579: 
1.810     raeburn  8580:     if ($priv eq 'evb') {
1.1478    raeburn  8581: # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8582:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8583:             return $1;
                   8584:         } else {
                   8585:             return;
                   8586:         }
                   8587:     }
                   8588: 
1.620     albertel 8589:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8590: # Free bre access to adm and meta resources
1.1436    raeburn  8591:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8592: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8593: 	&& ($priv eq 'bre')) {
1.14      www      8594: 	return 'F';
1.159     www      8595:     }
                   8596: 
1.545     banghart 8597: # Free bre access to user's own portfolio contents
1.714     raeburn  8598:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8599:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8600: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8601:         my %setters;
1.1473    raeburn  8602:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8603:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8604:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8605:             return 'B';
                   8606:         } else {
                   8607:             return 'F';
                   8608:         }
1.545     banghart 8609:     }
                   8610: 
1.762     raeburn  8611: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8612:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8613:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8614:         if (exists($env{'request.course.id'})) {
                   8615:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8616:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8617:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8618:                 my $courseprivid=$env{'request.course.id'};
                   8619:                 $courseprivid=~s/\_/\//;
                   8620:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8621:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8622:                     return $1; 
1.762     raeburn  8623:                 } else {
                   8624:                     if ($env{'request.course.sec'}) {
                   8625:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8626:                     }
                   8627:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8628:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8629:                         return $2;
                   8630:                     }
1.714     raeburn  8631:                 }
                   8632:             }
                   8633:         }
                   8634:     }
                   8635: 
1.159     www      8636: # Free bre to public access
                   8637: 
                   8638:     if ($priv eq 'bre') {
1.1362    raeburn  8639:         my $copyright;
                   8640:         unless ($uri =~ /ext\.tool/) {
                   8641:             $copyright=&metadata($uri,'copyright');
                   8642:         }
1.620     albertel 8643: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8644:            return 'F'; 
                   8645:         }
1.238     www      8646:         if ($copyright eq 'priv') {
                   8647:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8648: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8649: 		return '';
                   8650:             }
                   8651:         }
                   8652:         if ($copyright eq 'domain') {
                   8653:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8654: 	    unless (($env{'user.domain'} eq $1) ||
                   8655:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8656: 		return '';
                   8657:             }
1.262     matthew  8658:         }
1.620     albertel 8659:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8660:             # Library role, so allow browsing of resources in this domain.
                   8661:             return 'F';
1.238     www      8662:         }
1.341     www      8663:         if ($copyright eq 'custom') {
                   8664: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8665:         }
1.14      www      8666:     }
1.264     matthew  8667:     # Domain coordinator is trying to create a course
1.620     albertel 8668:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8669:         # uri is the requested domain in this case.
                   8670:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8671:         # a role of dc for the domain in question.
1.620     albertel 8672:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8673:     }
1.29      www      8674: 
1.52      www      8675:     my $thisallowed='';
                   8676:     my $statecond=0;
                   8677:     my $courseprivid='';
                   8678: 
1.1039    raeburn  8679:     my $ownaccess;
1.1043    raeburn  8680:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8681:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8682:         if ($uri eq '') {
                   8683:             $ownaccess = 1;
                   8684:         } else {
                   8685:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8686:                 my $udom = $env{'user.domain'};
                   8687:                 my $uname = $env{'user.name'};
                   8688:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8689:                     $ownaccess = 1;
1.1040    raeburn  8690:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8691:                     unless ($uri =~ m{\.\./}) {
                   8692:                         $ownaccess = 1;
                   8693:                     }
                   8694:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8695:                     my $now = time;
                   8696:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8697:                         my $adom = $1;
                   8698:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8699:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452    raeburn  8700:                                 my ($start,$end) = split(/\./,$env{$key});
                   8701:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8702:                                     $ownaccess = 1;
                   8703:                                     last;
                   8704:                                 }
                   8705:                             }
                   8706:                         }
                   8707:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8708:                         my $adom = $1;
                   8709:                         my $aname = $2;
1.1042    raeburn  8710:                         foreach my $role ('ca','aa') { 
                   8711:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8712:                                 my ($start,$end) =
1.1452    raeburn  8713:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8714:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8715:                                     $ownaccess = 1;
                   8716:                                     last;
                   8717:                                 }
1.1039    raeburn  8718:                             }
                   8719:                         }
                   8720:                     }
                   8721:                 }
                   8722:             }
                   8723:         }
                   8724:     }
                   8725: 
1.52      www      8726: # Course
                   8727: 
1.620     albertel 8728:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8729:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8730:             $thisallowed.=$1;
                   8731:         }
1.52      www      8732:     }
1.29      www      8733: 
1.52      www      8734: # Domain
                   8735: 
1.620     albertel 8736:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8737:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8738:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8739:             $thisallowed.=$1;
                   8740:         }
1.12      www      8741:     }
1.52      www      8742: 
1.1141    raeburn  8743: # User who is not author or co-author might still be able to edit
                   8744: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8745:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8746:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8747:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8748:             $thisallowed.=$1;
                   8749:         }
                   8750:     }
                   8751: 
1.52      www      8752: # Course: uri itself is a course
1.66      www      8753:     my $courseuri=$uri;
                   8754:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8755:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8756: 
1.620     albertel 8757:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8758:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8759:         if ($priv eq 'mip') {
                   8760:             my $rem = $1;
                   8761:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8762:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8763:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8764:                 if ($cdom ne '') {
1.1410    raeburn  8765:                     my %passwdconf = &get_passwdconf($cdom);
                   8766:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8767:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8768:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8769:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8770:                                 unless (@inststatuses) {
                   8771:                                     @inststatuses = ('default');
                   8772:                                 }
                   8773:                                 foreach my $status (@inststatuses) {
                   8774:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8775:                                         $thisallowed.=$rem;
                   8776:                                     }
                   8777:                                 }
                   8778:                             }
                   8779:                         }
1.1409    raeburn  8780:                     }
                   8781:                 }
                   8782:             }
                   8783:         } else {
                   8784:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8785:                 $thisallowed.=$1;
                   8786:             }
1.1039    raeburn  8787:         }
1.12      www      8788:     }
1.29      www      8789: 
1.665     albertel 8790: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8791: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8792:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8793: 	$thisallowed='';
1.671     raeburn  8794:         my ($match)=&is_on_map($uri);
                   8795:         if ($match) {
                   8796:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8797:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8798:                 my $value = $1;
1.1461    raeburn  8799:                 my $deeplinkblock;
                   8800:                 unless ($nodeeplinkcheck) {
                   8801:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8802:                 }
1.1402    raeburn  8803:                 if ($deeplinkblock) {
                   8804:                     $thisallowed='D';
                   8805:                 } elsif ($noblockcheck) {
1.1281    raeburn  8806:                     $thisallowed.=$value;
1.1162    raeburn  8807:                 } else {
1.1424    raeburn  8808:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8809:                     if (@blockers > 0) {
                   8810:                         $thisallowed = 'B';
                   8811:                     } else {
                   8812:                         $thisallowed.=$value;
                   8813:                     }
1.1162    raeburn  8814:                 }
1.671     raeburn  8815:             }
                   8816:         } else {
1.705     albertel 8817:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8818:             if ($refuri) {
                   8819:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8820:                     $thisallowed='F';
1.671     raeburn  8821:                 } else {
                   8822:                     $refuri=&declutter($refuri);
                   8823:                     my ($match) = &is_on_map($refuri);
                   8824:                     if ($match) {
1.1461    raeburn  8825:                         my $deeplinkblock;
                   8826:                         unless ($nodeeplinkcheck) {
                   8827:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8828:                         }
1.1402    raeburn  8829:                         if ($deeplinkblock) {
                   8830:                             $thisallowed='D';
                   8831:                         } elsif ($noblockcheck) {
1.1281    raeburn  8832:                             $thisallowed='F';
1.1162    raeburn  8833:                         } else {
1.1426    raeburn  8834:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8835:                             if (@blockers > 0) {
                   8836:                                 $thisallowed = 'B';
                   8837:                             } else {
                   8838:                                 $thisallowed='F';
                   8839:                             }
1.1162    raeburn  8840:                         }
1.671     raeburn  8841:                     }
1.669     raeburn  8842:                 }
1.671     raeburn  8843:             }
                   8844:         }
1.314     www      8845:     }
1.492     albertel 8846: 
1.766     albertel 8847:     if ($priv eq 'bre'
                   8848: 	&& $thisallowed ne 'F' 
                   8849: 	&& $thisallowed ne '2'
                   8850: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8851: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8852:     }
1.1250    raeburn  8853: 
1.52      www      8854: # Full access at system, domain or course-wide level? Exit.
1.29      www      8855:     if ($thisallowed=~/F/) {
                   8856: 	return 'F';
                   8857:     }
                   8858: 
1.52      www      8859: # If this is generating or modifying users, exit with special codes
1.29      www      8860: 
1.1517  ! raeburn  8861:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
1.643     www      8862: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8863: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8864: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8865: 	    unless ($auname) { return $thisallowed; }
                   8866: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8867: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8868: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8869: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
1.1517  ! raeburn  8870: 	} elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
        !          8871:             my ($audom,$auname)=split('/',$uri);
        !          8872:             unless ($auname) { return $thisallowed; }
        !          8873:             unless (($env{'request.role'} eq "dc./$audom") ||
        !          8874:                     ($env{'request.role'} eq "ca./$uri")) {
        !          8875:                 return '';
        !          8876:             }
1.642     albertel 8877: 	}
1.52      www      8878: 	return $thisallowed;
                   8879:     }
                   8880: #
1.103     harris41 8881: # Gathered so far: system, domain and course wide privileges
1.52      www      8882: #
                   8883: # Course: See if uri or referer is an individual resource that is part of 
                   8884: # the course
                   8885: 
1.620     albertel 8886:     if ($env{'request.course.id'}) {
1.232     www      8887: 
1.1504    raeburn  8888:         if ($priv eq 'bre') {
                   8889:             if (&is_coursetool_logo($uri)) {
                   8890:                 return 'F';
                   8891:             }
                   8892:         }
                   8893: 
1.1409    raeburn  8894: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8895: 
                   8896:         if ($priv eq 'mip') {
                   8897:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8898:                 return $thisallowed;
                   8899:             } else {
                   8900:                 return '';
                   8901:             }
                   8902:         }
                   8903: 
1.620     albertel 8904:        $courseprivid=$env{'request.course.id'};
                   8905:        if ($env{'request.course.sec'}) {
                   8906:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8907:        }
                   8908:        $courseprivid=~s/\_/\//;
                   8909:        my $checkreferer=1;
1.232     www      8910:        my ($match,$cond)=&is_on_map($uri);
                   8911:        if ($match) {
                   8912:            $statecond=$cond;
1.620     albertel 8913:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8914:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8915:                my $value = $1;
                   8916:                if ($priv eq 'bre') {
1.1461    raeburn  8917:                    my $deeplinkblock;
                   8918:                    unless ($nodeeplinkcheck) {
                   8919:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8920:                    }
1.1458    raeburn  8921:                    if ($deeplinkblock) {
                   8922:                        $thisallowed = 'D';
                   8923:                    } elsif ($noblockcheck) {
1.1281    raeburn  8924:                        $thisallowed.=$value;
1.1162    raeburn  8925:                    } else {
1.1424    raeburn  8926:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8927:                        if (@blockers > 0) {
                   8928:                            $thisallowed = 'B';
                   8929:                        } else {
                   8930:                            $thisallowed.=$value;
                   8931:                        }
1.1162    raeburn  8932:                    }
                   8933:                } else {
                   8934:                    $thisallowed.=$value;
                   8935:                }
1.52      www      8936:                $checkreferer=0;
                   8937:            }
1.29      www      8938:        }
1.1424    raeburn  8939: 
1.148     www      8940:        if ($checkreferer) {
1.620     albertel 8941: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8942:             unless ($refuri) {
1.800     albertel 8943:                 foreach my $key (keys(%env)) {
                   8944: 		    if ($key=~/^httpref\..*\*/) {
                   8945: 			my $pattern=$key;
1.156     www      8946:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8947:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8948:                         $pattern=~s/\//\\\//g;
1.152     www      8949:                         if ($orguri=~/$pattern/) {
1.800     albertel 8950: 			    $refuri=$env{$key};
1.148     www      8951:                         }
                   8952:                     }
1.191     harris41 8953:                 }
1.148     www      8954:             }
1.232     www      8955: 
1.148     www      8956:          if ($refuri) { 
1.152     www      8957: 	  $refuri=&declutter($refuri);
1.232     www      8958:           my ($match,$cond)=&is_on_map($refuri);
                   8959:             if ($match) {
                   8960:               my $refstatecond=$cond;
1.620     albertel 8961:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8962:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8963:                   my $value = $1;
                   8964:                   if ($priv eq 'bre') {
1.1461    raeburn  8965:                       my $deeplinkblock;
                   8966:                       unless ($nodeeplinkcheck) {
                   8967:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8968:                       }
1.1402    raeburn  8969:                       if ($deeplinkblock) {
                   8970:                           $thisallowed = 'D';
                   8971:                       } elsif ($noblockcheck) {
1.1281    raeburn  8972:                           $thisallowed.=$value;
1.1162    raeburn  8973:                       } else {
1.1426    raeburn  8974:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8975:                           if (@blockers > 0) {
                   8976:                               $thisallowed = 'B';
                   8977:                           } else {
                   8978:                               $thisallowed.=$value;
                   8979:                           }
1.1162    raeburn  8980:                       }
                   8981:                   } else {
                   8982:                       $thisallowed.=$value;
                   8983:                   }
1.53      www      8984:                   $uri=$refuri;
                   8985:                   $statecond=$refstatecond;
1.52      www      8986:               }
                   8987:           }
1.148     www      8988:         }
1.29      www      8989:        }
1.52      www      8990:    }
1.29      www      8991: 
1.52      www      8992: #
1.103     harris41 8993: # Gathered now: all privileges that could apply, and condition number
1.52      www      8994: # 
                   8995: #
                   8996: # Full or no access?
                   8997: #
1.29      www      8998: 
1.52      www      8999:     if ($thisallowed=~/F/) {
                   9000: 	return 'F';
                   9001:     }
1.29      www      9002: 
1.52      www      9003:     unless ($thisallowed) {
                   9004:         return '';
                   9005:     }
1.29      www      9006: 
1.52      www      9007: # Restrictions exist, deal with them
                   9008: #
                   9009: #   C:according to course preferences
                   9010: #   R:according to resource settings
                   9011: #   L:unless locked
                   9012: #   X:according to user session state
                   9013: #
                   9014: 
                   9015: # Possibly locked functionality, check all courses
1.1454    raeburn  9016: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      9017: # Locks might take effect only after 10 minutes cache expiration for other
1.1454    raeburn  9018: # courses, and 2 minutes for current course, in which user has st or ta role
                   9019: # which is neither expired nor a future role (unless current course).
1.52      www      9020: 
1.1454    raeburn  9021:     my ($needlockcheck,$now,$crsonly);
1.52      www      9022:     if ($thisallowed=~/L/) {
1.1454    raeburn  9023:         $now = time;
                   9024:         if ($priv eq 'bre') {
                   9025:             if ($uri ne '') {
                   9026:                 if ($orguri =~ m{^/+res/}) {
                   9027:                     if ($uri =~ m{^lib/templates/}) {
                   9028:                         if ($env{'request.course.id'}) {
                   9029:                             $crsonly = 1;
                   9030:                             $needlockcheck = 1;
                   9031:                         }
                   9032:                     } else {
                   9033:                         $needlockcheck = 1;
                   9034:                     }
                   9035:                 } elsif ($env{'request.course.id'}) {
                   9036:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   9037:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   9038:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   9039:                         $crsonly = 1;
                   9040:                     }
                   9041:                     $needlockcheck = 1;
                   9042:                 }
                   9043:             }
                   9044:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   9045:             $needlockcheck = 1;
                   9046:         }
                   9047:     }
                   9048:     if ($needlockcheck) {
1.1453    raeburn  9049:         foreach my $envkey (keys(%env)) {
1.54      www      9050:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   9051:                my $courseid=$2;
                   9052:                my $roleid=$1.'.'.$2;
1.92      www      9053:                $courseid=~s/^\///;
1.1453    raeburn  9054:                unless ($env{'request.role'} eq $roleid) {
                   9055:                    my ($start,$end) = split(/\./,$env{$envkey});
                   9056:                    next unless (($now >= $start) && (!$end || $end > $now));
                   9057:                }
1.54      www      9058:                my $expiretime=600;
1.620     albertel 9059:                if ($env{'request.role'} eq $roleid) {
1.54      www      9060: 		  $expiretime=120;
                   9061:                }
                   9062: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   9063:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 9064:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 9065: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      9066:                }
1.620     albertel 9067:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   9068:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   9069: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   9070:                        &log($env{'user.domain'},$env{'user.name'},
                   9071:                             $env{'user.home'},
1.57      www      9072:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      9073:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 9074:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      9075: 		       return '';
                   9076:                    }
                   9077:                }
1.620     albertel 9078:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   9079:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455    raeburn  9080: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 9081:                        &log($env{'user.domain'},$env{'user.name'},
                   9082:                             $env{'user.home'},
1.57      www      9083:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      9084:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 9085:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      9086: 		       return '';
                   9087:                    }
                   9088:                }
                   9089: 	   }
1.29      www      9090:        }
1.52      www      9091:     }
1.1424    raeburn  9092: 
1.52      www      9093: #
                   9094: # Rest of the restrictions depend on selected course
                   9095: #
                   9096: 
1.620     albertel 9097:     unless ($env{'request.course.id'}) {
1.766     albertel 9098: 	if ($thisallowed eq 'A') {
                   9099: 	    return 'A';
1.814     raeburn  9100:         } elsif ($thisallowed eq 'B') {
                   9101:             return 'B';
1.766     albertel 9102: 	} else {
                   9103: 	    return '1';
                   9104: 	}
1.52      www      9105:     }
1.29      www      9106: 
1.52      www      9107: #
                   9108: # Now user is definitely in a course
                   9109: #
1.53      www      9110: 
                   9111: 
                   9112: # Course preferences
                   9113: 
                   9114:    if ($thisallowed=~/C/) {
1.620     albertel 9115:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   9116:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   9117:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 9118: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  9119: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 9120: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   9121: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   9122: 			$env{'request.course.id'});
                   9123: 	   }
1.237     www      9124:            return '';
                   9125:        }
                   9126: 
1.620     albertel 9127:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 9128: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  9129: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 9130: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   9131: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   9132: 			$env{'request.course.id'});
                   9133: 	   }
1.54      www      9134:            return '';
                   9135:        }
1.53      www      9136:    }
                   9137: 
                   9138: # Resource preferences
                   9139: 
                   9140:    if ($thisallowed=~/R/) {
1.620     albertel 9141:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 9142:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  9143: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 9144: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   9145: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   9146: 	   }
                   9147: 	   return '';
1.54      www      9148:        }
1.53      www      9149:    }
1.30      www      9150: 
1.1461    raeburn  9151: # Restricted for deeplinked session?
                   9152: 
                   9153:     if ($env{'request.deeplink.login'}) {
                   9154:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   9155:             if (!$symb) { $symb=&symbread($uri,1); }
                   9156:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   9157:                 return '';
                   9158:             }
                   9159:         }
                   9160:     }
                   9161: 
1.246     www      9162: # Restricted by state or randomout?
1.30      www      9163: 
1.52      www      9164:    if ($thisallowed=~/X/) {
1.620     albertel 9165:       if ($env{'acc.randomout'}) {
1.579     albertel 9166: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 9167:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      9168:             return ''; 
                   9169:          }
1.247     www      9170:       }
                   9171:       if (&condval($statecond)) {
1.52      www      9172: 	 return '2';
                   9173:       } else {
                   9174:          return '';
                   9175:       }
                   9176:    }
1.30      www      9177: 
1.766     albertel 9178:     if ($thisallowed eq 'A') {
                   9179: 	return 'A';
1.814     raeburn  9180:     } elsif ($thisallowed eq 'B') {
                   9181:         return 'B';
1.1402    raeburn  9182:     } elsif ($thisallowed eq 'D') {
                   9183:         return 'D';
1.766     albertel 9184:     }
1.52      www      9185:    return 'F';
1.232     www      9186: }
1.1162    raeburn  9187: 
1.1192    raeburn  9188: # ------------------------------------------- Check construction space access
                   9189: 
                   9190: sub constructaccess {
                   9191:     my ($url,$setpriv)=@_;
                   9192: 
                   9193: # We do not allow editing of previous versions of files
                   9194:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   9195: 
                   9196: # Get username and domain from URL
                   9197:     my ($ownername,$ownerdomain,$ownerhome);
                   9198: 
                   9199:     ($ownerdomain,$ownername) =
1.1325    raeburn  9200:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  9201: 
                   9202: # The URL does not really point to any authorspace, forget it
                   9203:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   9204: 
                   9205: # Now we need to see if the user has access to the authorspace of
                   9206: # $ownername at $ownerdomain
                   9207: 
                   9208:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   9209: # Real author for this?
                   9210:        $ownerhome = $env{'user.home'};
                   9211:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   9212:           return ($ownername,$ownerdomain,$ownerhome);
                   9213:        }
1.1506    raeburn  9214:     } elsif (&is_course($ownerdomain,$ownername)) {
                   9215: # Course Authoring Space?
1.1312    raeburn  9216:         if ($env{'request.course.id'}) {
                   9217:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   9218:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   9219:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   9220:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   9221:                     return ($ownername,$ownerdomain,$ownerhome);
                   9222:                 }
                   9223:             }
                   9224:         }
1.1506    raeburn  9225:         return '';
                   9226:     } else {
                   9227: # Co-author for this?
                   9228:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   9229:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   9230:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   9231:             return ($ownername,$ownerdomain,$ownerhome);
                   9232:         }
1.1192    raeburn  9233:     }
                   9234: 
                   9235: # We don't have any access right now. If we are not possibly going to do anything about this,
                   9236: # we might as well leave
                   9237:    unless ($setpriv) { return ''; }
                   9238: 
                   9239: # Backdoor access?
                   9240:     my $allowed=&allowed('eco',$ownerdomain);
                   9241: # Nope
                   9242:     unless ($allowed) { return ''; }
                   9243: # Looks like we may have access, but could be locked by the owner of the construction space
                   9244:     if ($allowed eq 'U') {
                   9245:         my %blocked=&get('environment',['domcoord.author'],
                   9246:                          $ownerdomain,$ownername);
                   9247: # Is blocked by owner
                   9248:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   9249:     }
                   9250:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   9251: # Grant temporary access
                   9252:         my $then=$env{'user.login.time'};
1.1209    raeburn  9253:         my $update=$env{'user.update.time'};
1.1192    raeburn  9254:         if (!$update) { $update = $then; }
                   9255:         my $refresh=$env{'user.refresh.time'};
                   9256:         if (!$refresh) { $refresh = $update; }
                   9257:         my $now = time;
                   9258:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   9259:                            $now,'ca','constructaccess');
                   9260:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   9261:         return($ownername,$ownerdomain,$ownerhome);
                   9262:     }
                   9263: # No business here
                   9264:     return '';
                   9265: }
                   9266: 
1.1282    raeburn  9267: # ----------------------------------------------------------- Content Blocking
                   9268: 
                   9269: {
                   9270: # Caches for faster Course Contents display where content blocking
                   9271: # is in operation (i.e., interval param set) for timed quiz.
                   9272: #
                   9273: # User for whom data are being temporarily cached.
                   9274: my $cacheduser='';
1.1424    raeburn  9275: # Course for which data are being temporarily cached.
                   9276: my $cachedcid='';
1.1282    raeburn  9277: # Cached blockers for this user (a hash of blocking items). 
                   9278: my %cachedblockers=();
                   9279: # When the data were last cached.
                   9280: my $cachedlast='';
                   9281: 
                   9282: sub load_all_blockers {
1.1427    raeburn  9283:     my ($uname,$udom)=@_;
1.1282    raeburn  9284:     if (($uname ne '') && ($udom ne '')) { 
                   9285:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  9286:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  9287:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  9288:             return;
                   9289:         }
                   9290:     }
                   9291:     $cachedlast=time;
                   9292:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  9293:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  9294:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  9295:     return;
1.1282    raeburn  9296: }
                   9297: 
1.1162    raeburn  9298: sub get_comm_blocks {
                   9299:     my ($cdom,$cnum) = @_;
                   9300:     if ($cdom eq '' || $cnum eq '') {
                   9301:         return unless ($env{'request.course.id'});
                   9302:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9303:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9304:     }
                   9305:     my %commblocks;
                   9306:     my $hashid=$cdom.'_'.$cnum;
                   9307:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   9308:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   9309:         %commblocks = %{$blocksref};
                   9310:     } else {
1.1494    raeburn  9311:         %commblocks = &dump('comm_block',$cdom,$cnum);
1.1162    raeburn  9312:         my $cachetime = 600;
                   9313:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   9314:     }
                   9315:     return %commblocks;
                   9316: }
                   9317: 
1.1282    raeburn  9318: sub get_commblock_resources {
                   9319:     my ($blocks) = @_;
                   9320:     my %blockers = ();
                   9321:     return %blockers unless ($env{'request.course.id'});
1.1470    raeburn  9322:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9323:     if ($env{'request.course.sec'}) {
                   9324:         $courseurl .= '/'.$env{'request.course.sec'};
                   9325:     }
                   9326:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  9327:     my %commblocks;
                   9328:     if (ref($blocks) eq 'HASH') {
                   9329:         %commblocks = %{$blocks};
                   9330:     } else {
                   9331:         %commblocks = &get_comm_blocks();
                   9332:     }
1.1282    raeburn  9333:     return %blockers unless (keys(%commblocks) > 0); 
                   9334:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9335:     return %blockers unless (ref($navmap));
1.1162    raeburn  9336:     my $now = time;
                   9337:     foreach my $block (keys(%commblocks)) {
                   9338:         if ($block =~ /^(\d+)____(\d+)$/) {
                   9339:             my ($start,$end) = ($1,$2);
                   9340:             if ($start <= $now && $end >= $now) {
                   9341:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9342:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   9343:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  9344:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9345:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  9346:                             }
                   9347:                         }
                   9348:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  9349:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9350:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  9351:                             }
                   9352:                         }
                   9353:                     }
                   9354:                 }
                   9355:             }
                   9356:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   9357:             my $item = $1;
                   9358:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9359:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471    raeburn  9360:                     my (@interval,$mapname);
1.1282    raeburn  9361:                     my $type = 'map';
                   9362:                     if ($item eq 'course') {
                   9363:                         $type = 'course';
                   9364:                         @interval=&EXT("resource.0.interval");
                   9365:                     } else {
                   9366:                         if ($item =~ /___\d+___/) {
                   9367:                             $type = 'resource';
                   9368:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  9369:                         } else {
1.1471    raeburn  9370:                             $mapname = &deversion($item);
                   9371:                             if (ref($navmap)) {
                   9372:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9373:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9374:                             }
                   9375:                         }
1.1282    raeburn  9376:                     }
1.1310    raeburn  9377:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  9378:                         my $timelimit = $1; 
1.1282    raeburn  9379:                         my $first_access;
                   9380:                         if ($type eq 'resource') {
                   9381:                             $first_access=&get_first_access($interval[1],$item);
                   9382:                         } elsif ($type eq 'map') {
                   9383:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9384:                         } else {
                   9385:                             $first_access=&get_first_access($interval[1]);
                   9386:                         }
                   9387:                         if ($first_access) {
1.1292    raeburn  9388:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  9389:                             if ($timesup > $now) {
                   9390:                                 my $activeblock;
1.1471    raeburn  9391:                                 if ($type eq 'resource') {
                   9392:                                     if (ref($navmap)) {
                   9393:                                         my $res = $navmap->getBySymb($item);
                   9394:                                         if ($res->answerable()) {
                   9395:                                             $activeblock = 1;
                   9396:                                         }
                   9397:                                     }
                   9398:                                 } elsif ($type eq 'map') {
                   9399:                                     my $mapsymb = &symbread($mapname,1);
                   9400:                                     if (($mapsymb) && (ref($navmap))) {
                   9401:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9402:                                         if (ref($mapres)) {
                   9403:                                             my $first = $mapres->map_start();
                   9404:                                             my $finish = $mapres->map_finish();
                   9405:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9406:                                             if (ref($it)) {
                   9407:                                                 my $res;
                   9408:                                                 while ($res = $it->next(undef,1)) {
                   9409:                                                     next unless (ref($res));
                   9410:                                                     my $symb = $res->symb();
                   9411:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9412:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9413:                                                     if ($interval[1] eq 'map') {
                   9414:                                                         if ($res->answerable()) {
                   9415:                                                             $activeblock = 1;
                   9416:                                                             last;
                   9417:                                                         }
                   9418:                                                     }
                   9419:                                                 }
                   9420:                                             }
                   9421:                                         }
1.1282    raeburn  9422:                                     }
                   9423:                                 }
                   9424:                                 if ($activeblock) {
                   9425:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9426:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9427:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9428:                                          }
                   9429:                                     }
                   9430:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9431:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9432:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9433:                                         }
1.1162    raeburn  9434:                                     }
                   9435:                                 }
                   9436:                             }
                   9437:                         }
                   9438:                     }
                   9439:                 }
                   9440:             }
                   9441:         }
                   9442:     }
1.1282    raeburn  9443:     return %blockers;
1.1162    raeburn  9444: }
                   9445: 
1.1282    raeburn  9446: sub has_comm_blocking {
1.1427    raeburn  9447:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  9448:     my @blockers;
                   9449:     return unless ($env{'request.course.id'});
                   9450:     return unless ($priv eq 'bre');
                   9451:     return if ($env{'request.state'} eq 'construct');
1.1470    raeburn  9452:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9453:     if ($env{'request.course.sec'}) {
                   9454:         $courseurl .= '/'.$env{'request.course.sec'};
                   9455:     }
                   9456:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427    raeburn  9457:     my %blockinfo;
                   9458:     if (ref($blocks) eq 'HASH') {
                   9459:         %blockinfo = &get_commblock_resources($blocks);
                   9460:     } else {
                   9461:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9462:         %blockinfo = %cachedblockers;
                   9463:     }
                   9464:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  9465:     my (%possibles,@symbs);
                   9466:     if (!$symb) {
1.1427    raeburn  9467:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9468:     }
1.1282    raeburn  9469:     if ($symb) {
                   9470:         @symbs = ($symb);
                   9471:     } elsif (keys(%possibles)) { 
                   9472:         @symbs = keys(%possibles);
                   9473:     }
                   9474:     my $noblock;
                   9475:     foreach my $symb (@symbs) {
                   9476:         last if ($noblock);
                   9477:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  9478:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  9479:             if ($block =~ /^firstaccess____(.+)$/) {
                   9480:                 my $item = $1;
1.1424    raeburn  9481:                 unless ($blocked) {
                   9482:                     if (($item eq $map) || ($item eq $symb)) {
                   9483:                         $noblock = 1;
                   9484:                         last;
                   9485:                     }
1.1282    raeburn  9486:                 }
                   9487:             }
1.1427    raeburn  9488:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9489:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9490:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  9491:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9492:                             push(@blockers,$block);
                   9493:                         }
                   9494:                     }
                   9495:                 }
1.1427    raeburn  9496:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9497:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  9498:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9499:                             push(@blockers,$block);
                   9500:                         }
1.1282    raeburn  9501:                     }
                   9502:                 }
1.1162    raeburn  9503:             }
                   9504:         }
                   9505:     }
1.1424    raeburn  9506:     unless ($noblock) { 
                   9507:         return @blockers;
                   9508:     }
                   9509:     return;
1.1282    raeburn  9510: }
1.1162    raeburn  9511: }
                   9512: 
1.1402    raeburn  9513: sub deeplink_check {
                   9514:     my ($priv,$symb,$uri) = @_;
                   9515:     return unless ($env{'request.course.id'});
                   9516:     return unless ($priv eq 'bre');
                   9517:     return if ($env{'request.state'} eq 'construct');
                   9518:     return if ($env{'request.role.adv'});
                   9519:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9520:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9521:     my (%possibles,@symbs);
                   9522:     if (!$symb) {
                   9523:         $symb = &symbread($uri,1,1,1,\%possibles);
                   9524:     }
                   9525:     if ($symb) {
                   9526:         @symbs = ($symb);
                   9527:     } elsif (keys(%possibles)) {
                   9528:         @symbs = keys(%possibles);
                   9529:     }
                   9530: 
1.1461    raeburn  9531:     my ($deeplink_symb,$allow);
                   9532:     if ($env{'request.deeplink.login'}) {
                   9533:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402    raeburn  9534:     }
                   9535:     foreach my $symb (@symbs) {
                   9536:         last if ($allow);
                   9537:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9538:         if ($deeplink eq '') {
                   9539:             $allow = 1;
                   9540:         } else {
1.1463    raeburn  9541:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9542:             if ($state ne 'only') {
1.1402    raeburn  9543:                 $allow = 1;
1.1463    raeburn  9544:             } else {
                   9545:                 my $check_deeplink_entry;
                   9546:                 if ($protect ne 'none') {
                   9547:                     my ($acctype,$item) = split(/:/,$protect);
                   9548:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9549:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9550:                             $check_deeplink_entry = 1
                   9551:                         }
                   9552:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9553:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9554:                             $check_deeplink_entry = 1;
                   9555:                         }
                   9556:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9557:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9558:                             $check_deeplink_entry = 1;
                   9559:                         }
                   9560:                     }
                   9561:                 }
                   9562:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402    raeburn  9563:                     if ($scope eq 'res') {
1.1461    raeburn  9564:                         if ($symb eq $deeplink_symb) {
1.1402    raeburn  9565:                             $allow = 1;
                   9566:                         }
1.1459    raeburn  9567:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463    raeburn  9568:                         my ($map_from_symb,$map_from_login);
1.1461    raeburn  9569:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9570:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9571:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9572:                         } else {
                   9573:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9574:                         }
1.1459    raeburn  9575:                         if (($map_from_symb) && ($map_from_login)) {
                   9576:                             if ($map_from_symb eq $map_from_login) {
                   9577:                                 $allow = 1;
                   9578:                             } elsif ($scope eq 'rec') {
                   9579:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9580:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9581:                                     $allow = 1;
                   9582:                                 }
                   9583:                             }
                   9584:                         }
1.1402    raeburn  9585:                     }
                   9586:                 }
                   9587:             }
                   9588:         }
                   9589:     }
                   9590:     return if ($allow);
                   9591:     return 1;
                   9592: }
                   9593: 
1.1282    raeburn  9594: # -------------------------------- Deversion and split uri into path an filename   
                   9595: 
1.1133    foxr     9596: #
1.1282    raeburn  9597: #   Removes the version from a URI and
1.1133    foxr     9598: #   splits it in to its filename and path to the filename.
                   9599: #   Seems like File::Basename could have done this more clearly.
                   9600: #   Parameters:
                   9601: #      $uri   - input URI
                   9602: #   Returns:
                   9603: #     Two element list consisting of 
                   9604: #     $pathname  - the URI up to and excluding the trailing /
                   9605: #     $filename  - The part of the URI following the last /
                   9606: #  NOTE:
                   9607: #    Another realization of this is simply:
                   9608: #    use File::Basename;
                   9609: #    ...
                   9610: #    $uri = shift;
                   9611: #    $filename = basename($uri);
                   9612: #    $path     = dirname($uri);
                   9613: #    return ($filename, $path);
                   9614: #
                   9615: #     The implementation below is probably faster however.
                   9616: #
1.710     albertel 9617: sub split_uri_for_cond {
                   9618:     my $uri=&deversion(&declutter(shift));
                   9619:     my @uriparts=split(/\//,$uri);
                   9620:     my $filename=pop(@uriparts);
                   9621:     my $pathname=join('/',@uriparts);
                   9622:     return ($pathname,$filename);
                   9623: }
1.232     www      9624: # --------------------------------------------------- Is a resource on the map?
                   9625: 
                   9626: sub is_on_map {
1.710     albertel 9627:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9628:     #Trying to find the conditional for the file
1.620     albertel 9629:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9630: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9631:     if ($match) {
1.289     bowersj2 9632: 	return (1,$1);
                   9633:     } else {
1.434     www      9634: 	return (0,0);
1.289     bowersj2 9635:     }
1.12      www      9636: }
                   9637: 
1.427     www      9638: # --------------------------------------------------------- Get symb from alias
                   9639: 
                   9640: sub get_symb_from_alias {
                   9641:     my $symb=shift;
                   9642:     my ($map,$resid,$url)=&decode_symb($symb);
                   9643: # Already is a symb
                   9644:     if ($url) { return $symb; }
                   9645: # Must be an alias
                   9646:     my $aliassymb='';
                   9647:     my %bighash;
1.620     albertel 9648:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9649:                             &GDBM_READER(),0640)) {
                   9650:         my $rid=$bighash{'mapalias_'.$symb};
                   9651: 	if ($rid) {
                   9652: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9653: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9654: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9655: 	}
                   9656:         untie %bighash;
                   9657:     }
                   9658:     return $aliassymb;
                   9659: }
                   9660: 
1.12      www      9661: # ----------------------------------------------------------------- Define Role
                   9662: 
                   9663: sub definerole {
                   9664:   if (allowed('mcr','/')) {
1.1326    raeburn  9665:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9666:     foreach my $role (split(':',$sysrole)) {
                   9667: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9668:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9669:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9670: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9671:                return "refused:s:$crole&$cqual"; 
                   9672:             }
                   9673:         }
1.191     harris41 9674:     }
1.800     albertel 9675:     foreach my $role (split(':',$domrole)) {
                   9676: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9677:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9678:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9679: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9680:                return "refused:d:$crole&$cqual"; 
                   9681:             }
                   9682:         }
1.191     harris41 9683:     }
1.800     albertel 9684:     foreach my $role (split(':',$courole)) {
                   9685: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9686:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9687:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9688: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9689:                return "refused:c:$crole&$cqual"; 
                   9690:             }
                   9691:         }
1.191     harris41 9692:     }
1.1326    raeburn  9693:     my $uhome;
                   9694:     if (($uname ne '') && ($udom ne '')) {
                   9695:         $uhome = &homeserver($uname,$udom);
                   9696:         return $uhome if ($uhome eq 'no_host');
                   9697:     } else {
                   9698:         $uname = $env{'user.name'};
                   9699:         $udom = $env{'user.domain'};
                   9700:         $uhome = $env{'user.home'};
                   9701:     }
1.620     albertel 9702:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9703:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9704:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9705:     return reply($command,$uhome);
1.12      www      9706:   } else {
                   9707:     return 'refused';
                   9708:   }
1.105     harris41 9709: }
                   9710: 
                   9711: # ---------------- Make a metadata query against the network of library servers
                   9712: 
                   9713: sub metadata_query {
1.1237    raeburn  9714:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9715:     my %rhash;
1.845     albertel 9716:     my %libserv = &all_library();
1.244     matthew  9717:     my @server_list = (defined($server_array) ? @$server_array
                   9718:                                               : keys(%libserv) );
                   9719:     for my $server (@server_list) {
1.1237    raeburn  9720:         my $domains = ''; 
                   9721:         if (ref($domains_hash) eq 'HASH') {
                   9722:             $domains = $domains_hash->{$server}; 
                   9723:         }
1.118     harris41 9724: 	unless ($custom or $customshow) {
1.1237    raeburn  9725: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9726: 	    $rhash{$server}=$reply;
                   9727: 	}
                   9728: 	else {
                   9729: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9730: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9731: 			     $server);
                   9732: 	    $rhash{$server}=$reply;
                   9733: 	}
1.112     harris41 9734:     }
1.118     harris41 9735:     return \%rhash;
1.240     www      9736: }
                   9737: 
                   9738: # ----------------------------------------- Send log queries and wait for reply
                   9739: 
                   9740: sub log_query {
                   9741:     my ($uname,$udom,$query,%filters)=@_;
                   9742:     my $uhome=&homeserver($uname,$udom);
                   9743:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9744:     my $uhost=&hostname($uhome);
1.800     albertel 9745:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9746:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9747:                        $uhome);
1.479     albertel 9748:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9749:     return get_query_reply($queryid);
                   9750: }
                   9751: 
1.818     raeburn  9752: # -------------------------- Update MySQL table for portfolio file
                   9753: 
                   9754: sub update_portfolio_table {
1.821     raeburn  9755:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9756:     if ($group ne '') {
                   9757:         $file_name =~s /^\Q$group\E//;
                   9758:     }
1.818     raeburn  9759:     my $homeserver = &homeserver($uname,$udom);
                   9760:     my $queryid=
1.821     raeburn  9761:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9762:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9763:     my $reply = &get_query_reply($queryid);
                   9764:     return $reply;
                   9765: }
                   9766: 
1.899     raeburn  9767: # -------------------------- Update MySQL allusers table
                   9768: 
                   9769: sub update_allusers_table {
                   9770:     my ($uname,$udom,$names) = @_;
                   9771:     my $homeserver = &homeserver($uname,$udom);
                   9772:     my $queryid=
                   9773:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9774:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9775:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9776:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9777:                'generation='.&escape($names->{'generation'}).'%%'.
                   9778:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9779:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9780:     return;
1.899     raeburn  9781: }
                   9782: 
1.508     raeburn  9783: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9784: 
                   9785: sub fetch_enrollment_query {
1.511     raeburn  9786:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9787:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9788:     my $maxtries = 1;
1.508     raeburn  9789:     if ($context eq 'automated') {
                   9790:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9791:         $sleep = 2;
                   9792:         $loopmax = 100;
1.547     raeburn  9793:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9794:     } else {
                   9795:         $homeserver = &homeserver($cnum,$dom);
                   9796:     }
1.838     albertel 9797:     my $host=&hostname($homeserver);
1.506     raeburn  9798:     my $cmd = '';
1.1000    raeburn  9799:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9800:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9801:     }
                   9802:     $cmd =~ s/%%$//;
                   9803:     $cmd = &escape($cmd);
                   9804:     my $query = 'fetchenrollment';
1.620     albertel 9805:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9806:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9807:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9808:         return 'error: '.$queryid;
                   9809:     }
1.1317    raeburn  9810:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9811:     my $tries = 1;
                   9812:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9813:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9814:         $tries ++;
                   9815:     }
1.526     raeburn  9816:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9817:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9818:     } else {
1.901     albertel 9819:         my @responses = split(/:/,$reply);
1.1322    raeburn  9820:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9821:             foreach my $line (@responses) {
                   9822:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9823:                 $$replyref{$key} = $value;
                   9824:             }
                   9825:         } else {
1.1117    foxr     9826:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9827:             foreach my $line (@responses) {
                   9828:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9829:                 $$replyref{$key} = $value;
                   9830:                 if ($value > 0) {
1.800     albertel 9831:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9832:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9833:                         my $destname = $pathname.'/'.$filename;
                   9834:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9835:                         if ($xml_classlist =~ /^error/) {
                   9836:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9837:                         } else {
1.1359    raeburn  9838:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9839:                                 print FILE &unescape($xml_classlist);
                   9840:                                 close(FILE);
1.526     raeburn  9841:                             } else {
                   9842:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9843:                             }
                   9844:                         }
                   9845:                     }
                   9846:                 }
                   9847:             }
                   9848:         }
                   9849:         return 'ok';
                   9850:     }
                   9851:     return 'error';
                   9852: }
                   9853: 
1.242     www      9854: sub get_query_reply {
1.1471    raeburn  9855:     my ($queryid,$sleep,$loopmax) = @_;
1.1317    raeburn  9856:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9857:         $sleep = 0.2;
                   9858:     }
                   9859:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9860:         $loopmax = 100;
                   9861:     }
1.1117    foxr     9862:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9863:     my $reply='';
1.1317    raeburn  9864:     for (1..$loopmax) {
                   9865: 	sleep($sleep);
1.240     www      9866:         if (-e $replyfile.'.end') {
1.1359    raeburn  9867: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9868: 		$reply = join('',<$fh>);
                   9869: 		close($fh);
1.240     www      9870: 	   } else { return 'error: reply_file_error'; }
1.242     www      9871:            return &unescape($reply);
                   9872: 	}
1.240     www      9873:     }
1.242     www      9874:     return 'timeout:'.$queryid;
1.240     www      9875: }
                   9876: 
                   9877: sub courselog_query {
1.241     www      9878: #
                   9879: # possible filters:
                   9880: # url: url or symb
                   9881: # username
                   9882: # domain
                   9883: # action: view, submit, grade
                   9884: # start: timestamp
                   9885: # end: timestamp
                   9886: #
1.240     www      9887:     my (%filters)=@_;
1.620     albertel 9888:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9889:     if ($filters{'url'}) {
                   9890: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9891:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9892:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9893:     }
1.620     albertel 9894:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9895:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9896:     return &log_query($cname,$cdom,'courselog',%filters);
                   9897: }
                   9898: 
                   9899: sub userlog_query {
1.858     raeburn  9900: #
                   9901: # possible filters:
                   9902: # action: log check role
                   9903: # start: timestamp
                   9904: # end: timestamp
                   9905: #
1.240     www      9906:     my ($uname,$udom,%filters)=@_;
                   9907:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9908: }
                   9909: 
1.506     raeburn  9910: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9911: 
                   9912: sub auto_run {
1.508     raeburn  9913:     my ($cnum,$cdom) = @_;
1.876     raeburn  9914:     my $response = 0;
                   9915:     my $settings;
                   9916:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9917:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9918:         $settings = $domconfig{'autoenroll'};
                   9919:         if ($settings->{'run'} eq '1') {
                   9920:             $response = 1;
                   9921:         }
                   9922:     } else {
1.934     raeburn  9923:         my $homeserver;
                   9924:         if (&is_course($cdom,$cnum)) {
                   9925:             $homeserver = &homeserver($cnum,$cdom);
                   9926:         } else {
                   9927:             $homeserver = &domain($cdom,'primary');
                   9928:         }
                   9929:         if ($homeserver ne 'no_host') {
                   9930:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9931:         }
1.876     raeburn  9932:     }
1.506     raeburn  9933:     return $response;
                   9934: }
1.776     albertel 9935: 
1.506     raeburn  9936: sub auto_get_sections {
1.508     raeburn  9937:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9938:     my $homeserver;
                   9939:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9940:         $homeserver = &homeserver($cnum,$cdom);
                   9941:     }
                   9942:     if (!defined($homeserver)) { 
                   9943:         if ($cdom =~ /^$match_domain$/) {
                   9944:             $homeserver = &domain($cdom,'primary');
                   9945:         }
                   9946:     }
                   9947:     my @secs;
                   9948:     if (defined($homeserver)) {
                   9949:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9950:         unless ($response eq 'refused') {
                   9951:             @secs = split(/:/,$response);
                   9952:         }
1.506     raeburn  9953:     }
                   9954:     return @secs;
                   9955: }
1.776     albertel 9956: 
1.506     raeburn  9957: sub auto_new_course {
1.1099    raeburn  9958:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9959:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9960:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9961:     return $response;
                   9962: }
1.776     albertel 9963: 
1.506     raeburn  9964: sub auto_validate_courseID {
1.508     raeburn  9965:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9966:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9967:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9968:     return $response;
                   9969: }
1.776     albertel 9970: 
1.1007    raeburn  9971: sub auto_validate_instcode {
1.1020    raeburn  9972:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9973:     my ($homeserver,$response);
                   9974:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9975:         $homeserver = &homeserver($cnum,$cdom);
                   9976:     }
                   9977:     if (!defined($homeserver)) {
                   9978:         if ($cdom =~ /^$match_domain$/) {
                   9979:             $homeserver = &domain($cdom,'primary');
                   9980:         }
                   9981:     }
1.1065    raeburn  9982:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9983:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9984:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9985:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9986: }
                   9987: 
1.1444    raeburn  9988: sub auto_validate_inst_crosslist {
                   9989:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9990:     my ($homeserver,$response);
                   9991:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9992:         $homeserver = &homeserver($cnum,$cdom);
                   9993:     }
                   9994:     if (!defined($homeserver)) {
                   9995:         if ($cdom =~ /^$match_domain$/) {
                   9996:             $homeserver = &domain($cdom,'primary');
                   9997:         }
                   9998:     }
                   9999:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   10000:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   10001:                          &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445    raeburn  10002:                          &escape($coowner),$homeserver);
1.1444    raeburn  10003:     }
                   10004:     return $response;
                   10005: }
                   10006: 
1.506     raeburn  10007: sub auto_create_password {
1.873     raeburn  10008:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   10009:     my ($homeserver,$response);
1.506     raeburn  10010:     my $create_passwd = 0;
                   10011:     my $authchk = '';
1.873     raeburn  10012:     if ($udom =~ /^$match_domain$/) {
                   10013:         $homeserver = &domain($udom,'primary');
                   10014:     }
                   10015:     if ($homeserver eq '') {
                   10016:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   10017:             $homeserver = &homeserver($cnum,$cdom);
                   10018:         }
                   10019:     }
                   10020:     if ($homeserver eq '') {
                   10021:         $authchk = 'nodomain';
1.506     raeburn  10022:     } else {
1.873     raeburn  10023:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   10024:         if ($response eq 'refused') {
                   10025:             $authchk = 'refused';
                   10026:         } else {
1.901     albertel 10027:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  10028:         }
1.506     raeburn  10029:     }
                   10030:     return ($authparam,$create_passwd,$authchk);
                   10031: }
                   10032: 
1.706     raeburn  10033: sub auto_photo_permission {
                   10034:     my ($cnum,$cdom,$students) = @_;
                   10035:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 10036:     my ($outcome,$perm_reqd,$conditions) = 
                   10037: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 10038:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   10039: 	return (undef,undef);
                   10040:     }
1.706     raeburn  10041:     return ($outcome,$perm_reqd,$conditions);
                   10042: }
                   10043: 
                   10044: sub auto_checkphotos {
                   10045:     my ($uname,$udom,$pid) = @_;
                   10046:     my $homeserver = &homeserver($uname,$udom);
                   10047:     my ($result,$resulttype);
                   10048:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 10049: 				   &escape($uname).':'.&escape($pid),
                   10050: 				   $homeserver));
1.709     albertel 10051:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   10052: 	return (undef,undef);
                   10053:     }
1.706     raeburn  10054:     if ($outcome) {
                   10055:         ($result,$resulttype) = split(/:/,$outcome);
                   10056:     } 
                   10057:     return ($result,$resulttype);
                   10058: }
                   10059: 
                   10060: sub auto_photochoice {
                   10061:     my ($cnum,$cdom) = @_;
                   10062:     my $homeserver = &homeserver($cnum,$cdom);
                   10063:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 10064: 						       &escape($cdom),
                   10065: 						       $homeserver)));
1.709     albertel 10066:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   10067: 	return (undef,undef);
                   10068:     }
1.706     raeburn  10069:     return ($update,$comment);
                   10070: }
                   10071: 
                   10072: sub auto_photoupdate {
                   10073:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   10074:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 10075:     my $host=&hostname($homeserver);
1.706     raeburn  10076:     my $cmd = '';
                   10077:     my $maxtries = 1;
1.800     albertel 10078:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   10079:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  10080:     }
                   10081:     $cmd =~ s/%%$//;
                   10082:     $cmd = &escape($cmd);
                   10083:     my $query = 'institutionalphotos';
                   10084:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   10085:     unless ($queryid=~/^\Q$host\E\_/) {
                   10086:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   10087:         return 'error: '.$queryid;
                   10088:     }
                   10089:     my $reply = &get_query_reply($queryid);
                   10090:     my $tries = 1;
                   10091:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   10092:         $reply = &get_query_reply($queryid);
                   10093:         $tries ++;
                   10094:     }
                   10095:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   10096:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   10097:     } else {
                   10098:         my @responses = split(/:/,$reply);
                   10099:         my $outcome = shift(@responses); 
                   10100:         foreach my $item (@responses) {
                   10101:             my ($key,$value) = split(/=/,$item);
                   10102:             $$photo{$key} = $value;
                   10103:         }
                   10104:         return $outcome;
                   10105:     }
                   10106:     return 'error';
                   10107: }
                   10108: 
1.521     raeburn  10109: sub auto_instcode_format {
1.793     albertel 10110:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   10111: 	$cat_order) = @_;
1.521     raeburn  10112:     my $courses = '';
1.772     raeburn  10113:     my @homeservers;
1.521     raeburn  10114:     if ($caller eq 'global') {
1.841     albertel 10115: 	my %servers = &get_servers($codedom,'library');
                   10116: 	foreach my $tryserver (keys(%servers)) {
                   10117: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10118: 		push(@homeservers,$tryserver);
                   10119: 	    }
1.584     raeburn  10120:         }
1.1022    raeburn  10121:     } elsif ($caller eq 'requests') {
                   10122:         if ($codedom =~ /^$match_domain$/) {
                   10123:             my $chome = &domain($codedom,'primary');
                   10124:             unless ($chome eq 'no_host') {
                   10125:                 push(@homeservers,$chome);
                   10126:             }
                   10127:         }
1.521     raeburn  10128:     } else {
1.772     raeburn  10129:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  10130:     }
1.793     albertel 10131:     foreach my $code (keys(%{$instcodes})) {
                   10132:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  10133:     }
                   10134:     chop($courses);
1.772     raeburn  10135:     my $ok_response = 0;
                   10136:     my $response;
                   10137:     while (@homeservers > 0 && $ok_response == 0) {
                   10138:         my $server = shift(@homeservers); 
                   10139:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   10140:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   10141:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 10142: 		split(/:/,$response);
1.772     raeburn  10143:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   10144:             push(@{$codetitles},&str2array($codetitles_str));
                   10145:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   10146:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   10147:             $ok_response = 1;
                   10148:         }
                   10149:     }
                   10150:     if ($ok_response) {
1.521     raeburn  10151:         return 'ok';
1.772     raeburn  10152:     } else {
                   10153:         return $response;
1.521     raeburn  10154:     }
                   10155: }
                   10156: 
1.792     raeburn  10157: sub auto_instcode_defaults {
                   10158:     my ($domain,$returnhash,$code_order) = @_;
                   10159:     my @homeservers;
1.841     albertel 10160: 
                   10161:     my %servers = &get_servers($domain,'library');
                   10162:     foreach my $tryserver (keys(%servers)) {
                   10163: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10164: 	    push(@homeservers,$tryserver);
                   10165: 	}
1.792     raeburn  10166:     }
1.841     albertel 10167: 
1.792     raeburn  10168:     my $response;
1.841     albertel 10169:     foreach my $server (@homeservers) {
1.792     raeburn  10170:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 10171:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   10172: 	
                   10173: 	foreach my $pair (split(/\&/,$response)) {
                   10174: 	    my ($name,$value)=split(/\=/,$pair);
                   10175: 	    if ($name eq 'code_order') {
                   10176: 		@{$code_order} = split(/\&/,&unescape($value));
                   10177: 	    } else {
                   10178: 		$returnhash->{&unescape($name)}=&unescape($value);
                   10179: 	    }
                   10180: 	}
                   10181: 	return 'ok';
1.792     raeburn  10182:     }
1.841     albertel 10183: 
                   10184:     return $response;
1.1003    raeburn  10185: }
                   10186: 
                   10187: sub auto_possible_instcodes {
1.1007    raeburn  10188:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   10189:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   10190:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10191:         return;
                   10192:     }
1.1003    raeburn  10193:     my (@homeservers,$uhome);
                   10194:     if (defined(&domain($domain,'primary'))) {
                   10195:         $uhome=&domain($domain,'primary');
                   10196:         push(@homeservers,&domain($domain,'primary'));
                   10197:     } else {
                   10198:         my %servers = &get_servers($domain,'library');
                   10199:         foreach my $tryserver (keys(%servers)) {
                   10200:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10201:                 push(@homeservers,$tryserver);
                   10202:             }
                   10203:         }
                   10204:     }
                   10205:     my $response;
                   10206:     foreach my $server (@homeservers) {
                   10207:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   10208:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  10209:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   10210:             split(':',$response);
                   10211:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   10212:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  10213:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  10214:             my ($name,$value)=split('=',$item);
                   10215:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  10216:         }
                   10217:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  10218:             my ($name,$value)=split('=',$item);
                   10219:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  10220:         }
                   10221:         return 'ok';
                   10222:     }
                   10223:     return $response;
                   10224: }
1.792     raeburn  10225: 
1.1010    raeburn  10226: sub auto_courserequest_checks {
                   10227:     my ($dom) = @_;
1.1020    raeburn  10228:     my ($homeserver,%validations);
                   10229:     if ($dom =~ /^$match_domain$/) {
                   10230:         $homeserver = &domain($dom,'primary');
                   10231:     }
                   10232:     unless ($homeserver eq 'no_host') {
                   10233:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   10234:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10235:             my @items = split(/&/,$response);
                   10236:             foreach my $item (@items) {
                   10237:                 my ($key,$value) = split('=',$item);
                   10238:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   10239:             }
                   10240:         }
                   10241:     }
1.1010    raeburn  10242:     return %validations; 
                   10243: }
                   10244: 
1.1020    raeburn  10245: sub auto_courserequest_validation {
1.1255    raeburn  10246:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  10247:     my ($homeserver,$response);
                   10248:     if ($dom =~ /^$match_domain$/) {
                   10249:         $homeserver = &domain($dom,'primary');
                   10250:     }
1.1255    raeburn  10251:     unless ($homeserver eq 'no_host') {
                   10252:         my $customdata;
                   10253:         if (ref($custominfo) eq 'HASH') {
                   10254:             $customdata = &freeze_escape($custominfo);
                   10255:         }
1.1020    raeburn  10256:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  10257:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  10258:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   10259:                                     $customdata,$homeserver));
1.1020    raeburn  10260:     }
                   10261:     return $response;
                   10262: }
                   10263: 
1.777     albertel 10264: sub auto_validate_class_sec {
1.918     raeburn  10265:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  10266:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  10267:     my $ownerlist;
                   10268:     if (ref($owners) eq 'ARRAY') {
                   10269:         $ownerlist = join(',',@{$owners});
                   10270:     } else {
                   10271:         $ownerlist = $owners;
                   10272:     }
1.773     raeburn  10273:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  10274:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  10275:     return $response;
                   10276: }
                   10277: 
1.1460    raeburn  10278: sub auto_instsec_reformat {
                   10279:     my ($cdom,$action,$instsecref) = @_;
                   10280:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   10281:     my @homeservers;
                   10282:     if (defined(&domain($cdom,'primary'))) {
                   10283:         push(@homeservers,&domain($cdom,'primary'));
                   10284:     } else {
                   10285:         my %servers = &get_servers($cdom,'library');
                   10286:         foreach my $tryserver (keys(%servers)) {
                   10287:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10288:                 push(@homeservers,$tryserver);
                   10289:             }
                   10290:         }
                   10291:     }
                   10292:     my $response;
                   10293:     my %reformatted = %{$instsecref};
                   10294:     foreach my $server (@homeservers) {
                   10295:         if (ref($instsecref) eq 'HASH') {
                   10296:             my $info = &freeze_escape($instsecref);
                   10297:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   10298:                                 $action.':'.$info,$server);
                   10299:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   10300:             my @items = split(/&/,$response);
                   10301:             foreach my $item (@items) {
                   10302:                 my ($key,$value) = split(/=/,$item);
                   10303:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   10304:             }
                   10305:         }
                   10306:     }
                   10307:     return %reformatted;
                   10308: }
                   10309: 
1.1367    raeburn  10310: sub auto_validate_instclasses {
                   10311:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   10312:     my ($homeserver,%validations);
                   10313:     $homeserver = &homeserver($cnum,$cdom);
                   10314:     unless ($homeserver eq 'no_host') {
                   10315:         my $ownerlist;
                   10316:         if (ref($owners) eq 'ARRAY') {
                   10317:             $ownerlist = join(',',@{$owners});
                   10318:         } else {
                   10319:             $ownerlist = $owners;
                   10320:         }
                   10321:         if (ref($classesref) eq 'HASH') {
                   10322:             my $classes = &freeze_escape($classesref);
                   10323:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   10324:                                 ':'.$cdom.':'.$classes,$homeserver);
                   10325:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10326:                 my @items = split(/&/,$response);
                   10327:                 foreach my $item (@items) {
                   10328:                     my ($key,$value) = split('=',$item);
                   10329:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   10330:                 }
                   10331:             }
                   10332:         }
                   10333:     }
                   10334:     return %validations;
                   10335: }
                   10336: 
1.1248    raeburn  10337: sub auto_crsreq_update {
                   10338:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  10339:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  10340:     my ($homeserver,%crsreqresponse);
                   10341:     if ($cdom =~ /^$match_domain$/) {
                   10342:         $homeserver = &domain($cdom,'primary');
                   10343:     }
                   10344:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10345:         my $info;
                   10346:         if (ref($inbound) eq 'HASH') {
                   10347:             $info = &freeze_escape($inbound);
                   10348:         }
                   10349:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   10350:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   10351:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  10352:                             &escape($title).':'.&escape($code).':'.
                   10353:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   10354:                             $homeserver);
1.1248    raeburn  10355:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10356:             my @items = split(/&/,$response);
                   10357:             foreach my $item (@items) {
                   10358:                 my ($key,$value) = split('=',$item);
                   10359:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   10360:             }
                   10361:         }
                   10362:     }
                   10363:     return \%crsreqresponse;
                   10364: }
                   10365: 
1.1305    raeburn  10366: sub auto_export_grades {
1.1309    raeburn  10367:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   10368:     my ($homeserver,%exportresponse);
                   10369:     if ($cdom =~ /^$match_domain$/) {
                   10370:         $homeserver = &domain($cdom,'primary');
                   10371:     }
                   10372:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10373:         my $info;
                   10374:         if (ref($inforef) eq 'HASH') {
                   10375:             $info = &freeze_escape($inforef);
                   10376:         }
                   10377:         if (ref($gradesref) eq 'HASH') {
                   10378:             my $grades = &freeze_escape($gradesref);
                   10379:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10380:                                 $info.':'.$grades,$homeserver);
                   10381:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10382:                 my @items = split(/&/,$response);
                   10383:                 foreach my $item (@items) {
                   10384:                     my ($key,$value) = split('=',$item);
                   10385:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10386:                 }
                   10387:             }
                   10388:         }
                   10389:     }
                   10390:     return \%exportresponse;
1.1305    raeburn  10391: }
                   10392: 
1.1287    raeburn  10393: sub check_instcode_cloning {
                   10394:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10395:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10396:         return;
                   10397:     }
                   10398:     my $canclone;
                   10399:     if (@{$code_order} > 0) {
                   10400:         my $instcoderegexp ='^';
                   10401:         my @clonecodes = split(/\&/,$cloner);
                   10402:         foreach my $item (@{$code_order}) {
                   10403:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10404:                 foreach my $pair (@clonecodes) {
                   10405:                     my ($key,$val) = split(/\=/,$pair,2);
                   10406:                     $val = &unescape($val);
                   10407:                     if ($key eq $item) {
                   10408:                         $instcoderegexp .= '('.$val.')';
                   10409:                         last;
                   10410:                     }
                   10411:                 }
                   10412:             } else {
                   10413:                 $instcoderegexp .= $codedefaults->{$item};
                   10414:             }
                   10415:         }
                   10416:         $instcoderegexp .= '$';
                   10417:         my (@from,@to);
                   10418:         eval {
                   10419:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10420:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10421:         };
                   10422:         if ((@from > 0) && (@to > 0)) {
                   10423:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10424:             if (!@diffs) {
                   10425:                 $canclone = 1;
                   10426:             }
                   10427:         }
                   10428:     }
                   10429:     return $canclone;
                   10430: }
                   10431: 
                   10432: sub default_instcode_cloning {
                   10433:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10434:     my (%codedefaults,@code_order,$canclone);
                   10435:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10436:         %codedefaults = %{$codedefaultsref};
                   10437:         @code_order = @{$codeorderref};
                   10438:     } elsif ($clonedom) {
                   10439:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10440:     }
                   10441:     if (($domdefclone) && (@code_order)) {
                   10442:         my @clonecodes = split(/\+/,$domdefclone);
                   10443:         my $instcoderegexp ='^';
                   10444:         foreach my $item (@code_order) {
                   10445:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10446:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10447:             } else {
                   10448:                 $instcoderegexp .= $codedefaults{$item};
                   10449:             }
                   10450:         }
                   10451:         $instcoderegexp .= '$';
                   10452:         my (@from,@to);
                   10453:         eval {
                   10454:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10455:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10456:         };
                   10457:         if ((@from > 0) && (@to > 0)) {
                   10458:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10459:             if (!@diffs) {
                   10460:                 $canclone = 1;
                   10461:             }
                   10462:         }
                   10463:     }
                   10464:     return $canclone;
                   10465: }
                   10466: 
1.679     raeburn  10467: # ------------------------------------------------------- Course Group routines
                   10468: 
                   10469: sub get_coursegroups {
1.809     raeburn  10470:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10471:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10472: }
                   10473: 
1.679     raeburn  10474: sub modify_coursegroup {
                   10475:     my ($cdom,$cnum,$groupsettings) = @_;
                   10476:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10477: }
                   10478: 
1.809     raeburn  10479: sub toggle_coursegroup_status {
                   10480:     my ($cdom,$cnum,$group,$action) = @_;
                   10481:     my ($from_namespace,$to_namespace);
                   10482:     if ($action eq 'delete') {
                   10483:         $from_namespace = 'coursegroups';
                   10484:         $to_namespace = 'deleted_groups';
                   10485:     } else {
                   10486:         $from_namespace = 'deleted_groups';
                   10487:         $to_namespace = 'coursegroups';
                   10488:     }
                   10489:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10490:     if (my $tmp = &error(%curr_group)) {
                   10491:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10492:         return ('read error',$tmp);
                   10493:     } else {
                   10494:         my %savedsettings = %curr_group; 
1.809     raeburn  10495:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10496:         my $deloutcome;
                   10497:         if ($result eq 'ok') {
1.809     raeburn  10498:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10499:         } else {
                   10500:             return ('write error',$result);
                   10501:         }
                   10502:         if ($deloutcome eq 'ok') {
                   10503:             return 'ok';
                   10504:         } else {
                   10505:             return ('delete error',$deloutcome);
                   10506:         }
                   10507:     }
                   10508: }
                   10509: 
1.679     raeburn  10510: sub modify_group_roles {
1.1512    raeburn  10511:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
                   10512:         $othdomby,$requester) = @_;
1.679     raeburn  10513:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10514:     my $role = 'gr/'.&escape($userprivs);
                   10515:     my ($uname,$udom) = split(/:/,$user);
1.1512    raeburn  10516:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
                   10517:                              $othdomby,$requester);
1.684     raeburn  10518:     if ($result eq 'ok') {
                   10519:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10520:     }
1.679     raeburn  10521:     return $result;
                   10522: }
                   10523: 
                   10524: sub modify_coursegroup_membership {
                   10525:     my ($cdom,$cnum,$membership) = @_;
                   10526:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10527:     return $result;
                   10528: }
                   10529: 
1.682     raeburn  10530: sub get_active_groups {
                   10531:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10532:     my $now = time;
                   10533:     my %groups = ();
                   10534:     foreach my $key (keys(%env)) {
1.811     albertel 10535:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10536:             my ($start,$end) = split(/\./,$env{$key});
                   10537:             if (($end!=0) && ($end<$now)) { next; }
                   10538:             if (($start!=0) && ($start>$now)) { next; }
                   10539:             if ($1 eq $cdom && $2 eq $cnum) {
                   10540:                 $groups{$3} = $env{$key} ;
                   10541:             }
                   10542:         }
                   10543:     }
                   10544:     return %groups;
                   10545: }
                   10546: 
1.683     raeburn  10547: sub get_group_membership {
                   10548:     my ($cdom,$cnum,$group) = @_;
                   10549:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10550: }
                   10551: 
                   10552: sub get_users_groups {
                   10553:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10554:     my @usersgroups;
1.683     raeburn  10555:     my $cachetime=1800;
                   10556: 
                   10557:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10558:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10559:     if (defined($cached)) {
1.734     albertel 10560:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10561:     } else {  
                   10562:         $grouplist = '';
1.816     raeburn  10563:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10564:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10565:         my $access_end = $env{'course.'.$courseid.
                   10566:                               '.default_enrollment_end_date'};
                   10567:         my $now = time;
                   10568:         foreach my $key (keys(%roleshash)) {
                   10569:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10570:                 my $group = $1;
                   10571:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10572:                     my $start = $2;
                   10573:                     my $end = $1;
                   10574:                     if ($start == -1) { next; } # deleted from group
                   10575:                     if (($start!=0) && ($start>$now)) { next; }
                   10576:                     if (($end!=0) && ($end<$now)) {
                   10577:                         if ($access_end && $access_end < $now) {
                   10578:                             if ($access_end - $end < 86400) {
                   10579:                                 push(@usersgroups,$group);
1.733     raeburn  10580:                             }
                   10581:                         }
1.817     raeburn  10582:                         next;
1.733     raeburn  10583:                     }
1.817     raeburn  10584:                     push(@usersgroups,$group);
1.683     raeburn  10585:                 }
                   10586:             }
                   10587:         }
1.817     raeburn  10588:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10589:         $grouplist = join(':',@usersgroups);
                   10590:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10591:     }
1.733     raeburn  10592:     return @usersgroups;
1.683     raeburn  10593: }
                   10594: 
                   10595: sub devalidate_getgroups_cache {
                   10596:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10597:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10598: 
1.683     raeburn  10599:     my $hashid="$udom:$uname:$courseid";
                   10600:     &devalidate_cache_new('getgroups',$hashid);
                   10601: }
                   10602: 
1.12      www      10603: # ------------------------------------------------------------------ Plain Text
                   10604: 
                   10605: sub plaintext {
1.988     raeburn  10606:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10607:     if ($short =~ m{^cr/}) {
1.758     albertel 10608: 	return (split('/',$short))[-1];
                   10609:     }
1.742     raeburn  10610:     if (!defined($cid)) {
                   10611:         $cid = $env{'request.course.id'};
                   10612:     }
                   10613:     my %rolenames = (
1.1008    raeburn  10614:                       Course    => 'std',
                   10615:                       Community => 'alt1',
1.1305    raeburn  10616:                       Placement => 'std',
1.742     raeburn  10617:                     );
1.1037    raeburn  10618:     if ($cid ne '') {
                   10619:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10620:             unless ($forcedefault) {
                   10621:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10622:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10623:                 return &Apache::lonlocal::mt($roletext);
                   10624:             }
                   10625:         }
                   10626:     }
                   10627:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10628:         (defined($rolenames{$type})) && 
                   10629:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10630:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10631:     } elsif ($cid ne '') {
                   10632:         my $crstype = $env{'course.'.$cid.'.type'};
                   10633:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10634:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10635:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10636:         }
1.742     raeburn  10637:     }
1.1037    raeburn  10638:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10639: }
                   10640: 
                   10641: # ----------------------------------------------------------------- Assign Role
                   10642: 
                   10643: sub assignrole {
1.957     raeburn  10644:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
1.1512    raeburn  10645:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
1.1517  ! raeburn  10646:     my ($mrole,$rolelogcontext);
1.21      www      10647:     if ($role =~ /^cr\//) {
1.393     www      10648:         my $cwosec=$url;
1.811     albertel 10649:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.1502    raeburn  10650:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
1.1512    raeburn  10651:             my $refused = 1;
                   10652:             if ($context eq 'requestcourses') {
                   10653:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10654:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10655:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10656:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10657:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10658:                             if ($crsenv{'internal.courseowner'} eq
                   10659:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
                   10660:                                 $refused = '';
                   10661:                             }
                   10662:                         }
                   10663:                     }
                   10664:                 }
                   10665:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
                   10666:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10667:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
                   10668:                 my $key = "$uname:$udom:$role:$sec";
                   10669:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
                   10670:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10671:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10672:                         $refused = '';
                   10673:                     }
                   10674:                 }
                   10675:             }
                   10676:             if ($refused) {
                   10677:                 &logthis('Refused custom assignrole: '.
                   10678:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10679:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10680:                 return 'refused';
                   10681:             }
1.104     www      10682:         }
1.21      www      10683:         $mrole='cr';
1.678     raeburn  10684:     } elsif ($role =~ /^gr\//) {
                   10685:         my $cwogrp=$url;
1.811     albertel 10686:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.1512    raeburn  10687:         if (!&allowed('mdg',$cwogrp)) {
                   10688:             my $refused = 1;
                   10689:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
                   10690:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
                   10691:                 my $key = "$uname:$udom:$reqrole:$reqsec";
                   10692:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
                   10693:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10694:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10695:                         $refused = '';
                   10696:                     }
                   10697:                 }
                   10698:             }
                   10699:             if ($refused) {
                   10700:                 &logthis('Refused group assignrole: '.
                   10701:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10702:                          $env{'user.name'}.' at '.$env{'user.domain'});
                   10703:                 return 'refused';
                   10704:             }
1.678     raeburn  10705:         }
                   10706:         $mrole='gr';
1.21      www      10707:     } else {
1.82      www      10708:         my $cwosec=$url;
1.811     albertel 10709:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10710:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10711:             my $refused;
                   10712:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10713:                 if (!(&allowed('c'.$role,$url))) {
                   10714:                     $refused = 1;
                   10715:                 }
                   10716:             } else {
                   10717:                 $refused = 1;
                   10718:             }
1.947     raeburn  10719:             if ($refused) {
1.1045    raeburn  10720:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1512    raeburn  10721:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
                   10722:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10723:                     my %crsenv;
                   10724:                     if ($role eq 'cc' || $role eq 'co') {
                   10725:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10726:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10727:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10728:                                 if ($crsenv{'internal.courseowner'} eq 
                   10729:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10730:                                     $refused = '';
                   10731:                                 }
                   10732:                             }
                   10733:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10734:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10735:                                 if ($crsenv{'internal.courseowner'} eq 
                   10736:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10737:                                     $refused = '';
                   10738:                                 }
                   10739:                             }
                   10740:                         }
                   10741:                     }
1.1368    raeburn  10742:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10743:                     if ($role eq 'st') {
                   10744:                         $refused = '';
1.1377    raeburn  10745:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10746:                         $refused = '';
                   10747:                     }
1.1512    raeburn  10748:                 } elsif ($othdomby eq 'othdombyuser') {
                   10749:                     my ($key,%queuedrolereq);
                   10750:                     if ($context eq 'course') {
                   10751:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
                   10752:                         $key = "$uname:$udom:$role:$sec";
                   10753:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
                   10754:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10755:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10756:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
                   10757:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
                   10758:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10759:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
                   10760:                                         $refused = '';
                   10761:                                     }
                   10762:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
                   10763:                                     $refused = '';
                   10764:                                 }
                   10765:                             }
                   10766:                         }
                   10767:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
                   10768:                         my $key = "$uname:$udom:$role"; 
                   10769:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
                   10770:                         if (($audom ne '') && ($auname ne '')) {
                   10771:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
                   10772:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10773:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10774:                                     $refused = '';
                   10775:                                 }
                   10776:                             }
                   10777:                         }
                   10778:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
                   10779:                         my $key = "$uname:$udom:$role";
                   10780:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
                   10781:                         if ($roledom ne '') {
                   10782:                             my $confname = $roledom.'-domainconfig';
                   10783:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
                   10784:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
                   10785:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
                   10786:                                     $refused = '';
                   10787:                                 }
                   10788:                             }
                   10789:                         }
                   10790:                     }
1.1017    raeburn  10791:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10792:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10793:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10794:                         my $wrongcc;
                   10795:                         if ($cnum =~ /^$match_community$/) {
                   10796:                             $wrongcc = 1 if ($role eq 'cc');
                   10797:                         } else {
                   10798:                             $wrongcc = 1 if ($role eq 'co');
                   10799:                         }
                   10800:                         unless ($wrongcc) {
                   10801:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10802:                             if ($crsenv{'internal.courseowner'} eq 
                   10803:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10804:                                 $refused = '';
                   10805:                             }
1.1017    raeburn  10806:                         }
                   10807:                     }
1.1183    raeburn  10808:                 } elsif ($context eq 'requestauthor') {
                   10809:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10810:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10811:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10812:                             $refused = '';
                   10813:                         } else {
                   10814:                             my %domdefaults = &get_domain_defaults($udom);
                   10815:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10816:                                 my $checkbystatus;
                   10817:                                 if ($env{'user.adv'}) { 
                   10818:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10819:                                     if ($disposition eq 'automatic') {
                   10820:                                         $refused = '';
                   10821:                                     } elsif ($disposition eq '') {
                   10822:                                         $checkbystatus = 1;
                   10823:                                     } 
                   10824:                                 } else {
                   10825:                                     $checkbystatus = 1;
                   10826:                                 }
                   10827:                                 if ($checkbystatus) {
                   10828:                                     if ($env{'environment.inststatus'}) {
                   10829:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10830:                                         foreach my $type (@inststatuses) {
                   10831:                                             if (($type ne '') &&
                   10832:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10833:                                                 $refused = '';
                   10834:                                             }
                   10835:                                         }
                   10836:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10837:                                         $refused = '';
                   10838:                                     }
                   10839:                                 }
                   10840:                             }
                   10841:                         }
                   10842:                     }
1.1517  ! raeburn  10843:                 } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
        !          10844:                     if ($url =~ m{^/($match_domain)/($match_username)$}) {
        !          10845:                         my ($audom,$auname) = ($1,$2);
        !          10846:                         if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
        !          10847:                             ($env{"environment.internal.manager.$url"})) {
        !          10848:                             $refused = '';
        !          10849:                             $rolelogcontext = 'coauthor';
        !          10850:                         }
        !          10851:                     }
1.1017    raeburn  10852:                 }
                   10853:                 if ($refused) {
1.947     raeburn  10854:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10855:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10856: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10857:                     return 'refused';
                   10858:                 }
1.932     raeburn  10859:             }
1.1131    raeburn  10860:         } elsif ($role eq 'au') {
                   10861:             if ($url ne '/'.$udom.'/') {
                   10862:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10863:                          ' to assign author role for '.$uname.':'.$udom.
                   10864:                          ' in domain: '.$url.' refused (wrong domain).');
                   10865:                 return 'refused';
                   10866:             }
1.104     www      10867:         }
1.21      www      10868:         $mrole=$role;
                   10869:     }
1.620     albertel 10870:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10871:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10872:     if ($end) { $command.='_'.$end; }
1.21      www      10873:     if ($start) {
                   10874: 	if ($end) { 
1.81      www      10875:            $command.='_'.$start; 
1.21      www      10876:         } else {
1.81      www      10877:            $command.='_0_'.$start;
1.21      www      10878:         }
                   10879:     }
1.739     raeburn  10880:     my $origstart = $start;
                   10881:     my $origend = $end;
1.957     raeburn  10882:     my $delflag;
1.357     www      10883: # actually delete
                   10884:     if ($deleteflag) {
1.373     www      10885: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10886: # modify command to delete the role
1.620     albertel 10887:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10888:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10889: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10890: # set start and finish to negative values for userrolelog
                   10891:            $start=-1;
                   10892:            $end=-1;
1.957     raeburn  10893:            $delflag = 1;
1.357     www      10894:         }
                   10895:     }
                   10896: # send command
1.349     www      10897:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10898: # log new user role if status is ok
1.349     www      10899:     if ($answer eq 'ok') {
1.663     raeburn  10900: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10901:         if (($role eq 'cc') || ($role eq 'in') ||
                   10902:             ($role eq 'ep') || ($role eq 'ad') ||
                   10903:             ($role eq 'ta') || ($role eq 'st') ||
                   10904:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10905:             ($role eq 'co')) {
1.1200    raeburn  10906: # for course roles, perform group memberships changes triggered by role change.
                   10907:             unless ($role =~ /^gr/) {
                   10908:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10909:                                                  $origstart,$selfenroll,$context);
                   10910:             }
1.1184    raeburn  10911:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1512    raeburn  10912:                            $selfenroll,$context,$othdomby,$requester);
1.1184    raeburn  10913:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10914:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10915:                  ($role eq 'da')) {
1.1184    raeburn  10916:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1512    raeburn  10917:                            $context,$othdomby,$requester);
1.1184    raeburn  10918:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
1.1517  ! raeburn  10919:             if ($rolelogcontext eq '') {
        !          10920:                 $rolelogcontext = $context;
        !          10921:             }
1.1184    raeburn  10922:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1517  ! raeburn  10923:                              $rolelogcontext,$othdomby,$requester); 
1.1184    raeburn  10924:         }
1.1053    raeburn  10925:         if ($role eq 'cc') {
                   10926:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10927:         }
1.349     www      10928:     }
                   10929:     return $answer;
1.169     harris41 10930: }
                   10931: 
1.1053    raeburn  10932: sub autoupdate_coowners {
                   10933:     my ($url,$end,$start,$uname,$udom) = @_;
                   10934:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10935:     if (($cdom ne '') && ($cnum ne '')) {
                   10936:         my $now = time;
                   10937:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10938:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10939:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10940:             my $instcode = $coursehash{'internal.coursecode'};
1.1444    raeburn  10941:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10942:             if ($instcode ne '') {
1.1056    raeburn  10943:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10944:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10945:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10946:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444    raeburn  10947:                         unless ($result eq 'valid') {
                   10948:                             if ($xlists ne '') {
                   10949:                                 foreach my $xlist (split(',',$xlists)) {
                   10950:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10951:                                     $result =
1.1446    raeburn  10952:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10953:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10954:                                     last if ($result eq 'valid');
1.1444    raeburn  10955:                                 }
                   10956:                             }
                   10957:                         }
1.1056    raeburn  10958:                         if ($result eq 'valid') {
                   10959:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10960:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10961:                                     push(@newcoowners,$coowner);
                   10962:                                 }
                   10963:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10964:                                     push(@newcoowners,$uname.':'.$udom);
                   10965:                                 }
                   10966:                                 @newcoowners = sort(@newcoowners);
                   10967:                             } else {
                   10968:                                 push(@newcoowners,$uname.':'.$udom);
                   10969:                             }
1.1444    raeburn  10970:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10971:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10972:                                 unless ($coowner eq $uname.':'.$udom) {
                   10973:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10974:                                 }
1.1444    raeburn  10975:                             }
                   10976:                             unless (@newcoowners > 0) {
                   10977:                                 $delcoowners = 1;
                   10978:                                 $coowners = '';
1.1053    raeburn  10979:                             }
                   10980:                         }
                   10981:                         if (@newcoowners || $delcoowners) {
                   10982:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10983:                                             $delcoowners,@newcoowners);
                   10984:                         }
                   10985:                     }
                   10986:                 }
                   10987:             }
                   10988:         }
                   10989:     }
                   10990: }
                   10991: 
                   10992: sub store_coowners {
                   10993:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10994:     my $cid = $cdom.'_'.$cnum;
                   10995:     my ($coowners,$delresult,$putresult);
                   10996:     if (@newcoowners) {
                   10997:         $coowners = join(',',@newcoowners);
                   10998:         my %coownershash = (
                   10999:                             'internal.co-owners' => $coowners,
                   11000:                            );
                   11001:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   11002:         if ($putresult eq 'ok') {
                   11003:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   11004:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   11005:             }
                   11006:         }
                   11007:     }
                   11008:     if ($delcoowners) {
                   11009:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   11010:         if ($delresult eq 'ok') {
                   11011:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   11012:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   11013:             }
                   11014:         }
                   11015:     }
                   11016:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   11017:         my %crsinfo =
1.1494    raeburn  11018:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
1.1053    raeburn  11019:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   11020:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
1.1494    raeburn  11021:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
1.1053    raeburn  11022:         }
                   11023:     }
                   11024: }
                   11025: 
1.169     harris41 11026: # -------------------------------------------------- Modify user authentication
1.197     www      11027: # Overrides without validation
                   11028: 
1.169     harris41 11029: sub modifyuserauth {
                   11030:     my ($udom,$uname,$umode,$upass)=@_;
                   11031:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  11032:     my $allowed;
                   11033:     if (&allowed('mau',$udom)) {
                   11034:         $allowed = 1;
                   11035:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   11036:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   11037:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   11038:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11039:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11040:         if (($cdom ne '') && ($cnum ne '')) {
                   11041:             my $is_owner = &is_course_owner($cdom,$cnum);
                   11042:             if ($is_owner) {
                   11043:                 $allowed = 1;
                   11044:             }
                   11045:         }
                   11046:     }
                   11047:     unless ($allowed) { return 'refused'; }
1.197     www      11048:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 11049:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   11050:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 11051:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   11052: 		     &escape($upass),$uhome);
1.1434    raeburn  11053:     my $ip = &get_requestor_ip();
1.620     albertel 11054:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      11055:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434    raeburn  11056:          '(Remote '.$ip.'): '.$reply);
1.197     www      11057:     &log($udom,,$uname,$uhome,
1.620     albertel 11058:         'Authentication changed by '.$env{'user.domain'}.', '.
                   11059:                                      $env{'user.name'}.', '.$umode.
1.1435    raeburn  11060:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 11061:     unless ($reply eq 'ok') {
1.197     www      11062:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 11063: 	return 'error: '.$reply;
                   11064:     }   
1.170     harris41 11065:     return 'ok';
1.80      www      11066: }
                   11067: 
1.81      www      11068: # --------------------------------------------------------------- Modify a user
1.80      www      11069: 
1.81      www      11070: sub modifyuser {
1.206     matthew  11071:     my ($udom,    $uname, $uid,
                   11072:         $umode,   $upass, $first,
                   11073:         $middle,  $last,  $gene,
1.1058    raeburn  11074:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 11075:     $udom= &LONCAPA::clean_domain($udom);
                   11076:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  11077:     my $showcandelete = 'none';
                   11078:     if (ref($candelete) eq 'ARRAY') {
                   11079:         if (@{$candelete} > 0) {
                   11080:             $showcandelete = join(', ',@{$candelete});
                   11081:         }
                   11082:     }
1.81      www      11083:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      11084:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  11085: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  11086:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   11087:                                      ' desiredhome not specified'). 
1.620     albertel 11088:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   11089:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 11090:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  11091:     my $newuser;
                   11092:     if ($uhome eq 'no_host') {
                   11093:         $newuser = 1;
1.1368    raeburn  11094:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   11095:                 ($umode eq 'lti')) {
                   11096:             return 'error: more information needed to create new user';
                   11097:         }
1.1075    raeburn  11098:     }
1.80      www      11099: # ----------------------------------------------------------------- Create User
1.406     albertel 11100:     if (($uhome eq 'no_host') && 
1.1368    raeburn  11101: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      11102:         my $unhome='';
1.844     albertel 11103:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  11104:             $unhome = $desiredhome;
1.620     albertel 11105: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   11106: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  11107:         } else { # load balancing routine for determining $unhome
1.81      www      11108:             my $loadm=10000000;
1.841     albertel 11109: 	    my %servers = &get_servers($udom,'library');
                   11110: 	    foreach my $tryserver (keys(%servers)) {
                   11111: 		my $answer=reply('load',$tryserver);
                   11112: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   11113: 		    $loadm=$answer;
                   11114: 		    $unhome=$tryserver;
                   11115: 		}
1.80      www      11116: 	    }
                   11117:         }
                   11118:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  11119: 	    return 'error: unable to find a home server for '.$uname.
                   11120:                    ' in domain '.$udom;
1.80      www      11121:         }
                   11122:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   11123:                          &escape($upass),$unhome);
                   11124: 	unless ($reply eq 'ok') {
                   11125:             return 'error: '.$reply;
                   11126:         }   
1.230     stredwic 11127:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      11128:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  11129: 	    return 'error: unable verify users home machine.';
1.80      www      11130:         }
1.209     matthew  11131:     }   # End of creation of new user
1.80      www      11132: # ---------------------------------------------------------------------- Add ID
                   11133:     if ($uid) {
                   11134:        $uid=~tr/A-Z/a-z/;
                   11135:        my %uidhash=&idrget($udom,$uname);
1.196     www      11136:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   11137:          && (!$forceid)) {
1.80      www      11138: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  11139: 	      return 'error: user id "'.$uid.'" does not match '.
                   11140:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      11141:           }
                   11142:        } else {
1.1300    raeburn  11143: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      11144:        }
                   11145:     }
                   11146: # -------------------------------------------------------------- Add names, etc
1.313     matthew  11147:     my @tmp=&get('environment',
1.899     raeburn  11148: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  11149:                     'permanentemail','inststatus'],
1.134     albertel 11150: 		   $udom,$uname);
1.1075    raeburn  11151:     my (%names,%oldnames);
1.313     matthew  11152:     if ($tmp[0] =~ m/^error:.*/) { 
                   11153:         %names=(); 
                   11154:     } else {
                   11155:         %names = @tmp;
1.1075    raeburn  11156:         %oldnames = %names;
1.313     matthew  11157:     }
1.388     www      11158: #
1.1058    raeburn  11159: # If name, email and/or uid are blank (e.g., because an uploaded file
                   11160: # of users did not contain them), do not overwrite existing values
                   11161: # unless field is in $candelete array ref.  
                   11162: #
                   11163: 
                   11164:     my @fields = ('firstname','middlename','lastname','generation',
                   11165:                   'permanentemail','id');
                   11166:     my %newvalues;
                   11167:     if (ref($candelete) eq 'ARRAY') {
                   11168:         foreach my $field (@fields) {
                   11169:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   11170:                 if ($field eq 'firstname') {
                   11171:                     $names{$field} = $first;
                   11172:                 } elsif ($field eq 'middlename') {
                   11173:                     $names{$field} = $middle;
                   11174:                 } elsif ($field eq 'lastname') {
                   11175:                     $names{$field} = $last;
                   11176:                 } elsif ($field eq 'generation') { 
                   11177:                     $names{$field} = $gene;
                   11178:                 } elsif ($field eq 'permanentemail') {
                   11179:                     $names{$field} = $email;
                   11180:                 } elsif ($field eq 'id') {
                   11181:                     $names{$field}  = $uid;
                   11182:                 }
                   11183:             }
                   11184:         }
                   11185:     }
1.388     www      11186:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  11187:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      11188:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  11189:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      11190:     if ($email) {
                   11191:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  11192:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      11193:     }
1.899     raeburn  11194:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  11195:     if (defined($inststatus)) {
                   11196:         $names{'inststatus'} = '';
                   11197:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   11198:         if (ref($usertypes) eq 'HASH') {
                   11199:             my @okstatuses; 
                   11200:             foreach my $item (split(/:/,$inststatus)) {
                   11201:                 if (defined($usertypes->{$item})) {
                   11202:                     push(@okstatuses,$item);  
                   11203:                 }
                   11204:             }
                   11205:             if (@okstatuses) {
                   11206:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   11207:             }
                   11208:         }
                   11209:     }
1.1075    raeburn  11210:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  11211:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  11212:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  11213:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   11214:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   11215:     } else {
                   11216:         $logmsg .= ' during self creation';
                   11217:     }
1.1075    raeburn  11218:     my $changed;
                   11219:     if ($newuser) {
                   11220:         $changed = 1;
                   11221:     } else {
                   11222:         foreach my $field (@fields) {
                   11223:             if ($names{$field} ne $oldnames{$field}) {
                   11224:                 $changed = 1;
                   11225:                 last;
                   11226:             }
                   11227:         }
                   11228:     }
                   11229:     unless ($changed) {
                   11230:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   11231:         &logthis($logmsg);
                   11232:         return 'ok';
                   11233:     }
                   11234:     my $reply = &put('environment', \%names, $udom,$uname);
                   11235:     if ($reply ne 'ok') { 
                   11236:         return 'error: '.$reply;
                   11237:     }
1.1087    raeburn  11238:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
1.1494    raeburn  11239:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
1.1087    raeburn  11240:     }
1.1075    raeburn  11241:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   11242:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   11243:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  11244:     &logthis($logmsg);
1.134     albertel 11245:     return 'ok';
1.80      www      11246: }
                   11247: 
1.81      www      11248: # -------------------------------------------------------------- Modify student
1.80      www      11249: 
1.81      www      11250: sub modifystudent {
                   11251:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  11252:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  11253:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 11254:     if (!$cid) {
1.620     albertel 11255: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 11256: 	    return 'not_in_class';
                   11257: 	}
1.80      www      11258:     }
                   11259: # --------------------------------------------------------------- Make the user
1.81      www      11260:     my $reply=&modifyuser
1.209     matthew  11261: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  11262:          $desiredhome,$email,$inststatus);
1.80      www      11263:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  11264:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  11265:     # student's environment
1.297     matthew  11266:     $uid = undef if (!$forceid);
1.455     albertel 11267:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  11268:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  11269:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  11270:     return $reply;
                   11271: }
                   11272: 
                   11273: sub modify_student_enrollment {
1.1216    raeburn  11274:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1512    raeburn  11275:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
1.455     albertel 11276:     my ($cdom,$cnum,$chome);
                   11277:     if (!$cid) {
1.620     albertel 11278: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 11279: 	    return 'not_in_class';
                   11280: 	}
1.620     albertel 11281: 	$cdom=$env{'course.'.$cid.'.domain'};
                   11282: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 11283:     } else {
                   11284: 	($cdom,$cnum)=split(/_/,$cid);
                   11285:     }
1.620     albertel 11286:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 11287:     if (!$chome) {
1.457     raeburn  11288: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  11289:     }
1.455     albertel 11290:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  11291:     # Make sure the user exists
1.81      www      11292:     my $uhome=&homeserver($uname,$udom);
                   11293:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11294: 	return 'error: no such user';
                   11295:     }
1.297     matthew  11296:     # Get student data if we were not given enough information
                   11297:     if (!defined($first)  || $first  eq '' || 
                   11298:         !defined($last)   || $last   eq '' || 
                   11299:         !defined($uid)    || $uid    eq '' || 
                   11300:         !defined($middle) || $middle eq '' || 
                   11301:         !defined($gene)   || $gene   eq '') {
1.294     matthew  11302:         # They did not supply us with enough data to enroll the student, so
                   11303:         # we need to pick up more information.
1.297     matthew  11304:         my %tmp = &get('environment',
1.294     matthew  11305:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  11306:                        ,$udom,$uname);
                   11307: 
1.800     albertel 11308:         #foreach my $key (keys(%tmp)) {
                   11309:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 11310:         #}
1.294     matthew  11311:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   11312:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   11313:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  11314:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  11315:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   11316:     }
1.556     albertel 11317:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  11318:     my $user = "$uname:$udom";
1.1494    raeburn  11319:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
1.487     albertel 11320:     my $reply=cput('classlist',
1.1148    raeburn  11321: 		   {$user => 
1.1314    raeburn  11322: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 11323: 		   $cdom,$cnum);
1.1148    raeburn  11324:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   11325:         &devalidate_getsection_cache($udom,$uname,$cid);
                   11326:     } else { 
1.81      www      11327: 	return 'error: '.$reply;
                   11328:     }
1.297     matthew  11329:     # Add student role to user
1.83      www      11330:     my $uurl='/'.$cid;
1.81      www      11331:     $uurl=~s/\_/\//g;
                   11332:     if ($usec) {
                   11333: 	$uurl.='/'.$usec;
                   11334:     }
1.1148    raeburn  11335:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
1.1512    raeburn  11336:                              $selfenroll,$context,$othdomby,$requester);
1.1148    raeburn  11337:     if ($result ne 'ok') {
                   11338:         if ($old_entry{$user} ne '') {
                   11339:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   11340:         } else {
                   11341:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   11342:         }
                   11343:     }
                   11344:     return $result; 
1.21      www      11345: }
                   11346: 
1.556     albertel 11347: sub format_name {
                   11348:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   11349:     my $name;
                   11350:     if ($first ne 'lastname') {
                   11351: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   11352:     } else {
                   11353: 	if ($lastname=~/\S/) {
                   11354: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   11355: 	    $name=~s/\s+,/,/;
                   11356: 	} else {
                   11357: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   11358: 	}
                   11359:     }
                   11360:     $name=~s/^\s+//;
                   11361:     $name=~s/\s+$//;
                   11362:     $name=~s/\s+/ /g;
                   11363:     return $name;
                   11364: }
                   11365: 
1.84      www      11366: # ------------------------------------------------- Write to course preferences
                   11367: 
                   11368: sub writecoursepref {
                   11369:     my ($courseid,%prefs)=@_;
                   11370:     $courseid=~s/^\///;
                   11371:     $courseid=~s/\_/\//g;
                   11372:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   11373:     my $chome=homeserver($cnum,$cdomain);
                   11374:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   11375: 	return 'error: no such course';
                   11376:     }
                   11377:     my $cstring='';
1.800     albertel 11378:     foreach my $pref (keys(%prefs)) {
                   11379: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 11380:     }
1.84      www      11381:     $cstring=~s/\&$//;
                   11382:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   11383: }
                   11384: 
                   11385: # ---------------------------------------------------------- Make/modify course
                   11386: 
                   11387: sub createcourse {
1.741     raeburn  11388:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  11389:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      11390:     $url=&declutter($url);
                   11391:     my $cid='';
1.1028    raeburn  11392:     if ($context eq 'requestcourses') {
                   11393:         my $can_create = 0;
                   11394:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   11395:         if ($udom eq $ownerdom) {
1.1423    raeburn  11396:             my $reload;
                   11397:             if (($callercontext eq 'auto') &&
                   11398:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   11399:                 $reload = 'reload';
                   11400:             }
                   11401:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  11402:                                   $context)) {
                   11403:                 $can_create = 1;
                   11404:             }
                   11405:         } else {
                   11406:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   11407:                                            $category);
                   11408:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   11409:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   11410:                 if (@curr > 0) {
                   11411:                     my @options = qw(approval validate autolimit);
                   11412:                     my $optregex = join('|',@options);
                   11413:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   11414:                         $can_create = 1;
                   11415:                     }
                   11416:                 }
                   11417:             }
                   11418:         }
                   11419:         if ($can_create) {
                   11420:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   11421:                 unless (&allowed('ccc',$udom)) {
                   11422:                     return 'refused'; 
                   11423:                 }
1.1017    raeburn  11424:             }
                   11425:         } else {
                   11426:             return 'refused';
                   11427:         }
1.1028    raeburn  11428:     } elsif (!&allowed('ccc',$udom)) {
                   11429:         return 'refused';
1.84      www      11430:     }
1.1011    raeburn  11431: # --------------------------------------------------------------- Get Unique ID
                   11432:     my $uname;
                   11433:     if ($cnum =~ /^$match_courseid$/) {
                   11434:         my $chome=&homeserver($cnum,$udom,'true');
                   11435:         if (($chome eq '') || ($chome eq 'no_host')) {
                   11436:             $uname = $cnum;
                   11437:         } else {
1.1038    raeburn  11438:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11439:         }
                   11440:     } else {
1.1038    raeburn  11441:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11442:     }
                   11443:     return $uname if ($uname =~ /^error/);
                   11444: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  11445:     if (!defined($course_server)) {
                   11446:         if (defined(&domain($udom,'primary'))) {
                   11447:             $course_server = &domain($udom,'primary');
                   11448:         } else {
                   11449:             $course_server = $env{'user.home'}; 
                   11450:         }
                   11451:     }
                   11452:     my %host_servers =
1.1494    raeburn  11453:         &get_servers($udom,'library');
1.1052    raeburn  11454:     unless ($host_servers{$course_server}) {
                   11455:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11456:     }
1.84      www      11457: # ------------------------------------------------------------- Make the course
                   11458:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11459:                       $course_server);
1.84      www      11460:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11461:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11462:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11463: 	return 'error: no such course';
                   11464:     }
1.271     www      11465: # ----------------------------------------------------------------- Course made
1.516     raeburn  11466: # log existence
1.1029    raeburn  11467:     my $now = time;
1.918     raeburn  11468:     my $newcourse = {
                   11469:                     $udom.'_'.$uname => {
1.921     raeburn  11470:                                      description => $description,
                   11471:                                      inst_code   => $inst_code,
                   11472:                                      owner       => $course_owner,
                   11473:                                      type        => $crstype,
1.1029    raeburn  11474:                                      creator     => $env{'user.name'}.':'.
                   11475:                                                     $env{'user.domain'},
                   11476:                                      created     => $now,
                   11477:                                      context     => $context,
1.918     raeburn  11478:                                                 },
                   11479:                     };
1.921     raeburn  11480:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11481: # set toplevel url
1.271     www      11482:     my $topurl=$url;
                   11483:     unless ($nonstandard) {
                   11484: # ------------------------------------------ For standard courses, make top url
                   11485:         my $mapurl=&clutter($url);
1.278     www      11486:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11487:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11488: <map>
                   11489: <resource id="1" type="start"></resource>
                   11490: <resource id="2" src="$mapurl"></resource>
                   11491: <resource id="3" type="finish"></resource>
                   11492: <link index="1" from="1" to="2"></link>
                   11493: <link index="2" from="2" to="3"></link>
                   11494: </map>
                   11495: ENDINITMAP
                   11496:         $topurl=&declutter(
1.638     albertel 11497:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11498:                           );
                   11499:     }
                   11500: # ----------------------------------------------------------- Write preferences
1.84      www      11501:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11502:                      ('description'              => $description,
                   11503:                       'url'                      => $topurl,
                   11504:                       'internal.creator'         => $env{'user.name'}.':'.
                   11505:                                                     $env{'user.domain'},
                   11506:                       'internal.created'         => $now,
                   11507:                       'internal.creationcontext' => $context)
                   11508:                     );
1.84      www      11509:     return '/'.$udom.'/'.$uname;
                   11510: }
                   11511: 
1.1011    raeburn  11512: # ------------------------------------------------------------------- Create ID
                   11513: sub generate_coursenum {
1.1038    raeburn  11514:     my ($udom,$crstype) = @_;
1.1011    raeburn  11515:     my $domdesc = &domain($udom);
                   11516:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11517:     my $first;
                   11518:     if ($crstype eq 'Community') {
                   11519:         $first = '0';
                   11520:     } else {
                   11521:         $first = int(1+rand(9)); 
                   11522:     } 
                   11523:     my $uname=$first.
1.1011    raeburn  11524:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11525:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11526:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11527: # ----------------------------------------------- Make sure that does not exist
                   11528:     my $uhome=&homeserver($uname,$udom,'true');
                   11529:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11530:         if ($crstype eq 'Community') {
                   11531:             $first = '0';
                   11532:         } else {
                   11533:             $first = int(1+rand(9));
                   11534:         }
                   11535:         $uname=$first.
1.1011    raeburn  11536:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11537:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11538:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11539:         $uhome=&homeserver($uname,$udom,'true');
                   11540:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11541:             return 'error: unable to generate unique course-ID';
                   11542:         }
                   11543:     }
                   11544:     return $uname;
                   11545: }
                   11546: 
1.813     albertel 11547: sub is_course {
1.1167    droeschl 11548:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11549:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   11550: 
1.1381    raeburn  11551:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11552:     my $uhome=&homeserver($cnum,$cdom);
                   11553:     my $iscourse;
                   11554:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  11555:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  11556:     } else {
                   11557:         my $hashid = $cdom.':'.$cnum;
                   11558:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11559:         unless (defined($cached)) {
                   11560:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11561:                                         $cnum,undef,undef,'.');
                   11562:             $iscourse = 0;
                   11563:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11564:                 $iscourse = 1;
                   11565:             }
                   11566:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11567:         }
                   11568:     }
                   11569:     return unless ($iscourse);
1.1167    droeschl 11570:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11571: }
                   11572: 
1.1015    raeburn  11573: sub store_userdata {
                   11574:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11575:     my $result;
1.1016    raeburn  11576:     if ($datakey ne '') {
1.1013    raeburn  11577:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11578:             if ($udom eq '' || $uname eq '') {
                   11579:                 $udom = $env{'user.domain'};
                   11580:                 $uname = $env{'user.name'};
                   11581:             }
                   11582:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11583:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11584:                 $result = 'error: no_host';
                   11585:             } else {
1.1434    raeburn  11586:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11587:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11588: 
                   11589:                 my $namevalue='';
                   11590:                 foreach my $key (keys(%{$storehash})) {
                   11591:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11592:                 }
                   11593:                 $namevalue=~s/\&$//;
1.1224    raeburn  11594:                 unless ($namespace eq 'courserequests') {
                   11595:                     $datakey = &escape($datakey);
                   11596:                 }
1.1105    raeburn  11597:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11598:                                   $namevalue,$uhome);
1.1013    raeburn  11599:             }
                   11600:         } else {
                   11601:             $result = 'error: data to store was not a hash reference'; 
                   11602:         }
                   11603:     } else {
                   11604:         $result= 'error: invalid requestkey'; 
                   11605:     }
                   11606:     return $result;
                   11607: }
                   11608: 
1.21      www      11609: # ---------------------------------------------------------- Assign Custom Role
                   11610: 
                   11611: sub assigncustomrole {
1.1512    raeburn  11612:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
                   11613:         $selfenroll,$context,$othdomby,$requester)=@_;
1.21      www      11614:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.1512    raeburn  11615:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
                   11616:                        $requester);
1.21      www      11617: }
                   11618: 
                   11619: # ----------------------------------------------------------------- Revoke Role
                   11620: 
                   11621: sub revokerole {
1.957     raeburn  11622:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11623:     my $now=time;
1.965     raeburn  11624:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11625: }
                   11626: 
                   11627: # ---------------------------------------------------------- Revoke Custom Role
                   11628: 
                   11629: sub revokecustomrole {
1.957     raeburn  11630:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11631:     my $now=time;
1.357     www      11632:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11633:            $deleteflag,$selfenroll,$context);
1.17      www      11634: }
                   11635: 
1.533     banghart 11636: # ------------------------------------------------------------ Disk usage
1.535     albertel 11637: sub diskusage {
1.955     raeburn  11638:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11639:     $directorypath =~ s/\/$//;
                   11640:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11641:                        .&escape($getpropath).':'.&escape($uname).':'
                   11642:                        .&escape($udom),homeserver($uname,$udom));
                   11643:     if ($listing eq 'unknown_cmd') {
                   11644:         if ($getpropath) {
                   11645:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11646:         }
                   11647:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11648:     }
1.514     albertel 11649:     return $listing;
1.512     banghart 11650: }
                   11651: 
1.566     banghart 11652: sub is_locked {
1.1096    raeburn  11653:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11654:     my @check;
                   11655:     my $is_locked;
1.1093    raeburn  11656:     push (@check,$file_name);
1.613     albertel 11657:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11658: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11659:     my ($tmp)=keys(%locked);
                   11660:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11661:     
1.566     banghart 11662:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11663:         $is_locked = 'false';
                   11664:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11665:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11666:                $is_locked = 'true';
1.1096    raeburn  11667:                if (ref($which) eq 'ARRAY') {
                   11668:                    push(@{$which},$entry);
                   11669:                } else {
                   11670:                    last;
                   11671:                }
1.745     raeburn  11672:            }
                   11673:        }
1.566     banghart 11674:     } else {
                   11675:         $is_locked = 'false';
                   11676:     }
1.1093    raeburn  11677:     return $is_locked;
1.566     banghart 11678: }
                   11679: 
1.759     albertel 11680: sub declutter_portfile {
                   11681:     my ($file) = @_;
1.833     albertel 11682:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11683:     return $file;
                   11684: }
                   11685: 
1.559     banghart 11686: # ------------------------------------------------------------- Mark as Read Only
                   11687: 
                   11688: sub mark_as_readonly {
                   11689:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11690:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11691:     my ($tmp)=keys(%current_permissions);
                   11692:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11693:     foreach my $file (@{$files}) {
1.759     albertel 11694: 	$file = &declutter_portfile($file);
1.561     banghart 11695:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11696:     }
1.613     albertel 11697:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11698:     return;
                   11699: }
                   11700: 
1.572     banghart 11701: # ------------------------------------------------------------Save Selected Files
                   11702: 
                   11703: sub save_selected_files {
                   11704:     my ($user, $path, @files) = @_;
                   11705:     my $filename = $user."savedfiles";
1.573     banghart 11706:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  11707:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11708:     foreach my $file (@files) {
1.620     albertel 11709:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11710:     }
                   11711:     foreach my $file (@other_files) {
1.574     banghart 11712:         print (OUT $file."\n");
1.572     banghart 11713:     }
1.574     banghart 11714:     close (OUT);
1.572     banghart 11715:     return 'ok';
                   11716: }
                   11717: 
1.574     banghart 11718: sub clear_selected_files {
                   11719:     my ($user) = @_;
                   11720:     my $filename = $user."savedfiles";
1.1359    raeburn  11721:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11722:     print (OUT undef);
                   11723:     close (OUT);
                   11724:     return ("ok");    
                   11725: }
                   11726: 
1.572     banghart 11727: sub files_in_path {
                   11728:     my ($user, $path) = @_;
                   11729:     my $filename = $user."savedfiles";
                   11730:     my %return_files;
1.1359    raeburn  11731:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11732:     while (my $line_in = <IN>) {
1.574     banghart 11733:         chomp ($line_in);
                   11734:         my @paths_and_file = split (m!/!, $line_in);
                   11735:         my $file_part = pop (@paths_and_file);
                   11736:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11737:         $path_part.='/';
                   11738:         my $path_and_file = $path_part.$file_part;
                   11739:         if ($path_part eq $path) {
                   11740:             $return_files{$file_part}= 'selected';
                   11741:         }
                   11742:     }
1.574     banghart 11743:     close (IN);
                   11744:     return (\%return_files);
1.572     banghart 11745: }
                   11746: 
                   11747: # called in portfolio select mode, to show files selected NOT in current directory
                   11748: sub files_not_in_path {
                   11749:     my ($user, $path) = @_;
                   11750:     my $filename = $user."savedfiles";
                   11751:     my @return_files;
                   11752:     my $path_part;
1.1359    raeburn  11753:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11754:     while (my $line = <IN>) {
1.572     banghart 11755:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11756:         my @paths_and_file = split(m|/|, $line);
                   11757:         my $file_part = pop(@paths_and_file);
                   11758:         chomp($file_part);
                   11759:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11760:         $path_part .= '/';
                   11761:         my $path_and_file = $path_part.$file_part;
                   11762:         if ($path_part ne $path) {
1.800     albertel 11763:             push(@return_files, ($path_and_file));
1.572     banghart 11764:         }
                   11765:     }
1.800     albertel 11766:     close(OUT);
1.574     banghart 11767:     return (@return_files);
1.572     banghart 11768: }
                   11769: 
1.1273    raeburn  11770: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11771:  
                   11772: sub portfiles_versioning {
                   11773:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11774:     my $portfolio_root = '/userfiles/portfolio';
                   11775:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11776:     foreach my $file (@{$portfiles}) {
                   11777:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11778:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11779:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11780:         my $getpropath = 1;
                   11781:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11782:                                              $stu_name,$getpropath);
                   11783:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11784:         my $new_answer = 
                   11785:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11786:         if ($new_answer ne 'problem getting file') {
                   11787:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11788:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11789:                               [$symb,$env{'request.course.id'},'graded']);
                   11790:         }
                   11791:     }
                   11792: }
                   11793: 
                   11794: sub get_next_version {
                   11795:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11796:     my $version;
                   11797:     if (ref($dir_list) eq 'ARRAY') {
                   11798:         foreach my $row (@{$dir_list}) {
                   11799:             my ($file) = split(/\&/,$row,2);
                   11800:             my ($file_name,$file_version,$file_ext) =
                   11801:                 &file_name_version_ext($file);
                   11802:             if (($file_name eq $answer_name) &&
                   11803:                 ($file_ext eq $answer_ext)) {
                   11804:                      # gets here if filename and extension match,
                   11805:                      # regardless of version
                   11806:                 if ($file_version ne '') {
                   11807:                     # a versioned file is found  so save it for later
                   11808:                     if ($file_version > $version) {
                   11809:                         $version = $file_version;
                   11810:                     }
                   11811:                 }
                   11812:             }
                   11813:         }
                   11814:     }
                   11815:     $version ++;
                   11816:     return($version);
                   11817: }
                   11818: 
                   11819: sub version_selected_portfile {
                   11820:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11821:     my ($answer_name,$answer_ver,$answer_ext) =
                   11822:         &file_name_version_ext($file_name);
                   11823:     my $new_answer;
                   11824:     $env{'form.copy'} =
                   11825:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11826:     if($env{'form.copy'} eq '-1') {
                   11827:         $new_answer = 'problem getting file';
                   11828:     } else {
                   11829:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11830:         my $copy_result = 
                   11831:             &finishuserfileupload($stu_name,$domain,'copy',
                   11832:                                   '/portfolio'.$directory.$new_answer);
                   11833:     }
                   11834:     undef($env{'form.copy'});
                   11835:     return ($new_answer);
                   11836: }
                   11837: 
                   11838: sub file_name_version_ext {
                   11839:     my ($file)=@_;
                   11840:     my @file_parts = split(/\./, $file);
                   11841:     my ($name,$version,$ext);
                   11842:     if (@file_parts > 1) {
                   11843:         $ext=pop(@file_parts);
                   11844:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11845:             $version=pop(@file_parts);
                   11846:         }
                   11847:         $name=join('.',@file_parts);
                   11848:     } else {
                   11849:         $name=join('.',@file_parts);
                   11850:     }
                   11851:     return($name,$version,$ext);
                   11852: }
                   11853: 
1.745     raeburn  11854: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11855: 
1.745     raeburn  11856: sub get_portfile_permissions {
                   11857:     my ($domain,$user) = @_;
1.613     albertel 11858:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11859:     my ($tmp)=keys(%current_permissions);
                   11860:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11861:     return \%current_permissions;
                   11862: }
                   11863: 
                   11864: #---------------------------------------------Get portfolio file access controls
                   11865: 
1.749     raeburn  11866: sub get_access_controls {
1.745     raeburn  11867:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11868:     my %access;
                   11869:     my $real_file = $file;
                   11870:     $file =~ s/\.meta$//;
1.745     raeburn  11871:     if (defined($file)) {
1.749     raeburn  11872:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11873:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11874:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11875:             }
                   11876:         }
1.745     raeburn  11877:     } else {
1.749     raeburn  11878:         foreach my $key (keys(%{$current_permissions})) {
                   11879:             if ($key =~ /\0accesscontrol$/) {
                   11880:                 if (defined($group)) {
                   11881:                     if ($key !~ m-^\Q$group\E/-) {
                   11882:                         next;
                   11883:                     }
                   11884:                 }
                   11885:                 my ($fullpath) = split(/\0/,$key);
                   11886:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11887:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11888:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11889:                     }
                   11890:                 }
                   11891:             }
                   11892:         }
                   11893:     }
                   11894:     return %access;
                   11895: }
                   11896: 
                   11897: sub modify_access_controls {
                   11898:     my ($file_name,$changes,$domain,$user)=@_;
                   11899:     my ($outcome,$deloutcome);
                   11900:     my %store_permissions;
                   11901:     my %new_values;
                   11902:     my %new_control;
                   11903:     my %translation;
                   11904:     my @deletions = ();
                   11905:     my $now = time;
                   11906:     if (exists($$changes{'activate'})) {
                   11907:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11908:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11909:             my $numnew = scalar(@newitems);
                   11910:             for (my $i=0; $i<$numnew; $i++) {
                   11911:                 my $newkey = $newitems[$i];
                   11912:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11913:                 if ($newkey =~ /^\d+:/) { 
                   11914:                     $newkey =~ s/^(\d+)/$newid/;
                   11915:                     $translation{$1} = $newid;
                   11916:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11917:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11918:                     $translation{$1} = $newid;
                   11919:                 }
1.749     raeburn  11920:                 $new_values{$file_name."\0".$newkey} = 
                   11921:                                           $$changes{'activate'}{$newitems[$i]};
                   11922:                 $new_control{$newkey} = $now;
                   11923:             }
                   11924:         }
                   11925:     }
                   11926:     my %todelete;
                   11927:     my %changed_items;
                   11928:     foreach my $action ('delete','update') {
                   11929:         if (exists($$changes{$action})) {
                   11930:             if (ref($$changes{$action}) eq 'HASH') {
                   11931:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11932:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11933:                     if ($action eq 'delete') { 
                   11934:                         $todelete{$itemnum} = 1;
                   11935:                     } else {
                   11936:                         $changed_items{$itemnum} = $key;
                   11937:                     }
                   11938:                 }
1.745     raeburn  11939:             }
                   11940:         }
1.749     raeburn  11941:     }
                   11942:     # get lock on access controls for file.
                   11943:     my $lockhash = {
                   11944:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11945:                                                        ':'.$env{'user.domain'},
                   11946:                    }; 
                   11947:     my $tries = 0;
                   11948:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11949:    
1.1288    damieng  11950:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11951:         $tries ++;
1.1289    damieng  11952:         sleep(0.1);
1.749     raeburn  11953:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11954:     }
                   11955:     if ($gotlock eq 'ok') {
                   11956:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11957:         my ($tmp)=keys(%curr_permissions);
                   11958:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11959:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11960:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11961:             if (ref($curr_controls) eq 'HASH') {
                   11962:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11963:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11964:                     if (defined($todelete{$itemnum})) {
                   11965:                         push(@deletions,$file_name."\0".$control_item);
                   11966:                     } else {
                   11967:                         if (defined($changed_items{$itemnum})) {
                   11968:                             $new_control{$changed_items{$itemnum}} = $now;
                   11969:                             push(@deletions,$file_name."\0".$control_item);
                   11970:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11971:                         } else {
                   11972:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11973:                         }
                   11974:                     }
1.745     raeburn  11975:                 }
                   11976:             }
                   11977:         }
1.970     raeburn  11978:         my ($group);
                   11979:         if (&is_course($domain,$user)) {
                   11980:             ($group,my $file) = split(/\//,$file_name,2);
                   11981:         }
1.749     raeburn  11982:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11983:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11984:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11985:         #  remove lock
                   11986:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11987:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11988:         my $sqlresult =
1.970     raeburn  11989:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11990:                                     $group);
1.749     raeburn  11991:     } else {
                   11992:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11993:     }
1.749     raeburn  11994:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11995: }
                   11996: 
1.827     raeburn  11997: sub make_public_indefinitely {
1.1271    raeburn  11998:     my (@requrl) = @_;
                   11999:     return &automated_portfile_access('public',\@requrl);
                   12000: }
                   12001: 
                   12002: sub automated_portfile_access {
                   12003:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  12004:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   12005:         return 'invalid';
                   12006:     }
1.1271    raeburn  12007:     my %urls;
                   12008:     if (ref($addsref) eq 'ARRAY') {
                   12009:         foreach my $requrl (@{$addsref}) {
                   12010:             if (&is_portfolio_url($requrl)) {
                   12011:                 unless (exists($urls{$requrl})) {
                   12012:                     $urls{$requrl} = 'add';
                   12013:                 }
                   12014:             }
                   12015:         }
                   12016:     }
                   12017:     if (ref($delsref) eq 'ARRAY') {
                   12018:         foreach my $requrl (@{$delsref}) { 
                   12019:             if (&is_portfolio_url($requrl)) {
                   12020:                 unless (exists($urls{$requrl})) {
                   12021:                     $urls{$requrl} = 'delete'; 
                   12022:                 }
                   12023:             }
                   12024:         }
                   12025:     }
                   12026:     unless (keys(%urls)) {
                   12027:         return 'invalid';
                   12028:     }
                   12029:     my $ip;
                   12030:     if ($accesstype eq 'ip') {
                   12031:         if (ref($info) eq 'HASH') {
                   12032:             if ($info->{'ip'} ne '') {
                   12033:                 $ip = $info->{'ip'};
                   12034:             }
                   12035:         }
                   12036:         if ($ip eq '') {
                   12037:             return 'invalid';
                   12038:         }
                   12039:     }
                   12040:     my $errors;
1.827     raeburn  12041:     my $now = time;
1.1271    raeburn  12042:     my %current_perms;
                   12043:     foreach my $requrl (sort(keys(%urls))) {
                   12044:         my $action;
                   12045:         if ($urls{$requrl} eq 'add') {
                   12046:             $action = 'activate';
                   12047:         } else {
                   12048:             $action = 'none';
                   12049:         }
                   12050:         my $aclnum = 0;
1.827     raeburn  12051:         my (undef,$udom,$unum,$file_name,$group) =
                   12052:             &parse_portfolio_url($requrl);
1.1271    raeburn  12053:         unless (exists($current_perms{$unum.':'.$udom})) {
                   12054:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   12055:         }
                   12056:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  12057:                                                    $group,$file_name);
                   12058:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   12059:             my ($num,$scope,$end,$start) = 
                   12060:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  12061:             if ($scope eq $accesstype) {
                   12062:                 if (($start <= $now) && ($end == 0)) {
                   12063:                     if ($accesstype eq 'ip') {
                   12064:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   12065:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   12066:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   12067:                                     if ($urls{$requrl} eq 'add') {
                   12068:                                         $action = 'none';
                   12069:                                         last;
                   12070:                                     } else {
                   12071:                                         $action = 'delete';
                   12072:                                         $aclnum = $num;
                   12073:                                         last;
                   12074:                                     }
                   12075:                                 }
                   12076:                             }
                   12077:                         }
                   12078:                     } elsif ($accesstype eq 'public') {
                   12079:                         if ($urls{$requrl} eq 'add') {
                   12080:                             $action = 'none';
                   12081:                             last;
                   12082:                         } else {
                   12083:                             $action = 'delete';
                   12084:                             $aclnum = $num;
                   12085:                             last;
                   12086:                         }
                   12087:                     }
                   12088:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  12089:                     $action = 'update';
                   12090:                     $aclnum = $num;
1.1271    raeburn  12091:                     last;
1.827     raeburn  12092:                 }
                   12093:             }
                   12094:         }
                   12095:         if ($action eq 'none') {
1.1271    raeburn  12096:             next;
1.827     raeburn  12097:         } else {
                   12098:             my %changes;
                   12099:             my $newend = 0;
                   12100:             my $newstart = $now;
1.1271    raeburn  12101:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  12102:             $changes{$action}{$newkey} = {
1.1271    raeburn  12103:                 type => $accesstype,
1.827     raeburn  12104:                 time => {
                   12105:                     start => $newstart,
                   12106:                     end   => $newend,
                   12107:                 },
                   12108:             };
1.1271    raeburn  12109:             if ($accesstype eq 'ip') {
                   12110:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   12111:             }
1.827     raeburn  12112:             my ($outcome,$deloutcome,$new_values,$translation) =
                   12113:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  12114:             unless ($outcome eq 'ok') {
                   12115:                 $errors .= $outcome.' ';
                   12116:             }
1.827     raeburn  12117:         }
1.1271    raeburn  12118:     }
                   12119:     if ($errors) {
                   12120:         $errors =~ s/\s$//;
                   12121:         return $errors;
1.827     raeburn  12122:     } else {
1.1271    raeburn  12123:         return 'ok';
1.827     raeburn  12124:     }
                   12125: }
                   12126: 
1.745     raeburn  12127: #------------------------------------------------------Get Marked as Read Only
                   12128: 
                   12129: sub get_marked_as_readonly {
                   12130:     my ($domain,$user,$what,$group) = @_;
                   12131:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 12132:     my @readonly_files;
1.629     banghart 12133:     my $cmp1=$what;
                   12134:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  12135:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   12136:         if (defined($group)) {
                   12137:             if ($file_name !~ m-^\Q$group\E/-) {
                   12138:                 next;
                   12139:             }
                   12140:         }
1.561     banghart 12141:         if (ref($value) eq "ARRAY"){
                   12142:             foreach my $stored_what (@{$value}) {
1.629     banghart 12143:                 my $cmp2=$stored_what;
1.759     albertel 12144:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  12145:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  12146:                 }
1.629     banghart 12147:                 if ($cmp1 eq $cmp2) {
1.561     banghart 12148:                     push(@readonly_files, $file_name);
1.745     raeburn  12149:                     last;
1.563     banghart 12150:                 } elsif (!defined($what)) {
                   12151:                     push(@readonly_files, $file_name);
1.745     raeburn  12152:                     last;
1.561     banghart 12153:                 }
                   12154:             }
1.745     raeburn  12155:         }
1.561     banghart 12156:     }
                   12157:     return @readonly_files;
                   12158: }
1.577     banghart 12159: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 12160: 
1.577     banghart 12161: sub get_marked_as_readonly_hash {
1.745     raeburn  12162:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 12163:     my %readonly_files;
1.745     raeburn  12164:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   12165:         if (defined($group)) {
                   12166:             if ($file_name !~ m-^\Q$group\E/-) {
                   12167:                 next;
                   12168:             }
                   12169:         }
1.577     banghart 12170:         if (ref($value) eq "ARRAY"){
                   12171:             foreach my $stored_what (@{$value}) {
1.745     raeburn  12172:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 12173:                     foreach my $lock_descriptor(@{$stored_what}) {
                   12174:                         if ($lock_descriptor eq 'graded') {
                   12175:                             $readonly_files{$file_name} = 'graded';
                   12176:                         } elsif ($lock_descriptor eq 'handback') {
                   12177:                             $readonly_files{$file_name} = 'handback';
                   12178:                         } else {
                   12179:                             if (!exists($readonly_files{$file_name})) {
                   12180:                                 $readonly_files{$file_name} = 'locked';
                   12181:                             }
                   12182:                         }
1.745     raeburn  12183:                     }
1.750     banghart 12184:                 } 
1.577     banghart 12185:             }
                   12186:         } 
                   12187:     }
                   12188:     return %readonly_files;
                   12189: }
1.559     banghart 12190: # ------------------------------------------------------------ Unmark as Read Only
                   12191: 
                   12192: sub unmark_as_readonly {
1.629     banghart 12193:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   12194:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  12195:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 12196:     $file_name = &declutter_portfile($file_name);
1.634     albertel 12197:     my $symb_crs = $what;
                   12198:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  12199:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 12200:     my ($tmp)=keys(%current_permissions);
                   12201:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  12202:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 12203:     foreach my $file (@readonly_files) {
1.759     albertel 12204: 	my $clean_file = &declutter_portfile($file);
                   12205: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 12206: 	my $current_locks = $current_permissions{$file};
1.563     banghart 12207:         my @new_locks;
                   12208:         my @del_keys;
                   12209:         if (ref($current_locks) eq "ARRAY"){
                   12210:             foreach my $locker (@{$current_locks}) {
1.632     albertel 12211:                 my $compare=$locker;
1.749     raeburn  12212:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  12213:                     $compare=join('',@{$locker});
1.746     raeburn  12214:                     if ($compare ne $symb_crs) {
                   12215:                         push(@new_locks, $locker);
                   12216:                     }
1.563     banghart 12217:                 }
                   12218:             }
1.650     albertel 12219:             if (scalar(@new_locks) > 0) {
1.563     banghart 12220:                 $current_permissions{$file} = \@new_locks;
                   12221:             } else {
                   12222:                 push(@del_keys, $file);
1.613     albertel 12223:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 12224:                 delete($current_permissions{$file});
1.563     banghart 12225:             }
                   12226:         }
1.561     banghart 12227:     }
1.613     albertel 12228:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 12229:     return;
                   12230: }
1.512     banghart 12231: 
1.17      www      12232: # ------------------------------------------------------------ Directory lister
                   12233: 
                   12234: sub dirlist {
1.955     raeburn  12235:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      12236:     $uri=~s/^\///;
                   12237:     $uri=~s/\/$//;
1.253     stredwic 12238:     my ($udom, $uname);
1.955     raeburn  12239:     if ($getuserdir) {
1.253     stredwic 12240:         $udom = $userdomain;
                   12241:         $uname = $username;
1.955     raeburn  12242:     } else {
                   12243:         (undef,$udom,$uname)=split(/\//,$uri);
                   12244:         if(defined($userdomain)) {
                   12245:             $udom = $userdomain;
                   12246:         }
                   12247:         if(defined($username)) {
                   12248:             $uname = $username;
                   12249:         }
1.253     stredwic 12250:     }
1.955     raeburn  12251:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 12252: 
1.955     raeburn  12253:     $dirRoot = $perlvar{'lonDocRoot'};
                   12254:     if (defined($getpropath)) {
                   12255:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 12256:         $dirRoot =~ s/\/$//;
1.955     raeburn  12257:     } elsif (defined($getuserdir)) {
                   12258:         my $subdir=$uname.'__';
                   12259:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   12260:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   12261:                    ."/$udom/$subdir/$uname";
                   12262:     } elsif (defined($alternateRoot)) {
                   12263:         $dirRoot = $alternateRoot;
1.751     banghart 12264:     }
1.253     stredwic 12265: 
                   12266:     if($udom) {
                   12267:         if($uname) {
1.1135    raeburn  12268:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  12269:             if ($uhome eq 'no_host') {
                   12270:                 return ([],'no_host');
                   12271:             }
1.955     raeburn  12272:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  12273:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  12274:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  12275:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  12276:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  12277:             } else {
                   12278:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   12279:             }
1.605     matthew  12280:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  12281:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  12282:                 @listing_results = split(/:/,$listing);
                   12283:             } else {
                   12284:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   12285:             }
1.1135    raeburn  12286:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  12287:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   12288:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   12289:                 return ([],$listing);
                   12290:             } else {
                   12291:                 return (\@listing_results);
1.1135    raeburn  12292:             }
1.955     raeburn  12293:         } elsif(!$alternateRoot) {
1.1136    raeburn  12294:             my (%allusers,%listerror);
1.841     albertel 12295: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  12296:  	    foreach my $tryserver (keys(%servers)) {
                   12297:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   12298:                                   &escape($udom),$tryserver);
                   12299:                 if ($listing eq 'unknown_cmd') {
                   12300: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   12301: 				      $udom, $tryserver);
                   12302:                 } else {
                   12303:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   12304:                 }
1.841     albertel 12305: 		if ($listing eq 'unknown_cmd') {
                   12306: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   12307: 				      $udom, $tryserver);
                   12308: 		    @listing_results = split(/:/,$listing);
                   12309: 		} else {
                   12310: 		    @listing_results =
                   12311: 			map { &unescape($_); } split(/:/,$listing);
                   12312: 		}
1.1136    raeburn  12313:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   12314:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   12315:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   12316:                     $listerror{$tryserver} = $listing;
                   12317:                 } else {
1.841     albertel 12318: 		    foreach my $line (@listing_results) {
                   12319: 			my ($entry) = split(/&/,$line,2);
                   12320: 			$allusers{$entry} = 1;
                   12321: 		    }
                   12322: 		}
1.253     stredwic 12323:             }
1.1136    raeburn  12324:             my @alluserslist=();
1.800     albertel 12325:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  12326:                 push(@alluserslist,$user.'&user');
1.253     stredwic 12327:             }
1.1318    droeschl 12328: 
                   12329:             if (!%listerror) {
                   12330:                 # no errors
                   12331:                 return (\@alluserslist);
                   12332:             } elsif (scalar(keys(%servers)) == 1) {
                   12333:                 # one library server, one error 
                   12334:                 my ($key) = keys(%listerror);
                   12335:                 return (\@alluserslist, $listerror{$key});
                   12336:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   12337:                 # con_lost indicates that we might miss data from at least one
                   12338:                 # library server
                   12339:                 return (\@alluserslist, 'con_lost');
                   12340:             } else {
                   12341:                 # multiple library servers and no con_lost -> data should be
                   12342:                 # complete. 
                   12343:                 return (\@alluserslist);
                   12344:             }
                   12345: 
1.253     stredwic 12346:         } else {
1.1136    raeburn  12347:             return ([],'missing username');
1.253     stredwic 12348:         }
1.955     raeburn  12349:     } elsif(!defined($getpropath)) {
1.1136    raeburn  12350:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   12351:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   12352:         return (\@all_domains);
1.955     raeburn  12353:     } else {
1.1136    raeburn  12354:         return ([],'missing domain');
1.275     stredwic 12355:     }
                   12356: }
                   12357: 
                   12358: # --------------------------------------------- GetFileTimestamp
                   12359: # This function utilizes dirlist and returns the date stamp for
                   12360: # when it was last modified.  It will also return an error of -1
                   12361: # if an error occurs
                   12362: 
                   12363: sub GetFileTimestamp {
1.955     raeburn  12364:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 12365:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   12366:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  12367:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   12368:                                     undef,$getuserdir);
                   12369:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   12370:         return -1;
                   12371:     }
                   12372:     if (ref($fileref) eq 'ARRAY') {
                   12373:         my @stats = split('&',$fileref->[0]);
1.375     matthew  12374:         # @stats contains first the filename, then the stat output
                   12375:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 12376:     } else {
                   12377:         return -1;
1.253     stredwic 12378:     }
1.26      www      12379: }
                   12380: 
1.712     albertel 12381: sub stat_file {
                   12382:     my ($uri) = @_;
1.787     albertel 12383:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 12384: 
1.955     raeburn  12385:     my ($udom,$uname,$file);
1.712     albertel 12386:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   12387: 	($udom,$uname,$file) =
1.811     albertel 12388: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 12389: 	$file = 'userfiles/'.$file;
                   12390:     }
                   12391:     if ($uri =~ m-^/res/-) {
                   12392: 	($udom,$uname) = 
1.807     albertel 12393: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 12394: 	$file = $uri;
                   12395:     }
                   12396: 
                   12397:     if (!$udom || !$uname || !$file) {
                   12398: 	# unable to handle the uri
                   12399: 	return ();
                   12400:     }
1.956     raeburn  12401:     my $getpropath;
                   12402:     if ($file =~ /^userfiles\//) {
                   12403:         $getpropath = 1;
                   12404:     }
1.1136    raeburn  12405:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   12406:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   12407:         return ();
                   12408:     } else {
                   12409:         if (ref($listref) eq 'ARRAY') {
                   12410:             my @stats = split('&',$listref->[0]);
                   12411: 	    shift(@stats); #filename is first
                   12412: 	    return @stats;
                   12413:         }
1.712     albertel 12414:     }
                   12415:     return ();
                   12416: }
                   12417: 
1.1313    raeburn  12418: # --------------------------------------------------------- recursedirs
                   12419: # Recursive function to traverse either a specific user's Authoring Space
                   12420: # or corresponding Published Resource Space, and populate the hash ref:
                   12421: # $dirhashref with URLs of all directories, and if $filehashref hash
                   12422: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
1.1503    raeburn  12423: # or .rights files in resource space, and .meta, .save, .log, .bak and
                   12424: # .rights files in Authoring Space.
1.1313    raeburn  12425: #
                   12426: # Inputs:
                   12427: #
                   12428: # $is_home - true if current server is home server for user's space
1.1503    raeburn  12429: # $recurse - if true will also traverse subdirectories recursively
                   12430: # $include - reference to hash containing allowed file extensions.  If provided,
                   12431: #             files which do not have a matching extension will be ignored.
                   12432: # $exclude - reference to hash containing excluded file extensions.  If provided,
                   12433: #             files which have a matching extension will be ignored.
                   12434: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
                   12435: #             directory with first file found (with acceptable extension).
1.1505    raeburn  12436: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
1.1313    raeburn  12437: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   12438: # $relpath - Current path (relative to top level).
                   12439: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   12440: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   12441: #
                   12442: # Returns: nothing
                   12443: #
                   12444: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   12445: #
                   12446: # Currently used by interface/londocs.pm to create linked select boxes for
                   12447: # directory and filename to import a Course "Author" resource into a course, and
                   12448: # also to create linked select boxes for Authoring Space and Directory to choose
                   12449: # save location for creation of a new "standard" problem from the Course Editor.
                   12450: #
                   12451: 
                   12452: sub recursedirs {
1.1505    raeburn  12453:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
1.1313    raeburn  12454:     return unless (ref($dirhashref) eq 'HASH');
1.1503    raeburn  12455:     my $docroot = $perlvar{'lonDocRoot'};
1.1313    raeburn  12456:     my $currpath = $docroot.$toppath;
1.1503    raeburn  12457:     if ($relpath ne '') {
1.1313    raeburn  12458:         $currpath .= "/$relpath";
                   12459:     }
1.1503    raeburn  12460:     my ($savefile,$checkinc,$checkexc);
1.1313    raeburn  12461:     if (ref($filehashref)) {
                   12462:         $savefile = 1;
                   12463:     }
1.1503    raeburn  12464:     if (ref($include) eq 'HASH') {
                   12465:         $checkinc = 1;
                   12466:     }
                   12467:     if (ref($exclude) eq 'HASH') {
                   12468:         $checkexc = 1;
                   12469:     }
1.1313    raeburn  12470:     if ($is_home) {
1.1505    raeburn  12471:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
1.1503    raeburn  12472:             my $filecount = 0;
1.1313    raeburn  12473:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   12474:                 next if ($item eq '');
                   12475:                 if (-d "$currpath/$item") {
                   12476:                     my $newpath;
1.1503    raeburn  12477:                     if ($relpath ne '') {
1.1313    raeburn  12478:                         $newpath = "$relpath/$item";
                   12479:                     } else {
                   12480:                         $newpath = $item;
                   12481:                     }
                   12482:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503    raeburn  12483:                     if ($recurse) {
1.1505    raeburn  12484:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
1.1503    raeburn  12485:                     }
                   12486:                 } elsif (($savefile) || ($relpath eq '')) {
                   12487:                     next if ($nonemptydir && $filecount);
                   12488:                     if ($checkinc || $checkexc) {
                   12489:                         my ($extension) = ($item =~ /\.(\w+)$/);
                   12490:                         if ($checkinc) {
                   12491:                             next unless ($extension && $include->{$extension});
                   12492:                         }
                   12493:                         if ($checkexc) {
                   12494:                             next if ($extension && $exclude->{$extension});
                   12495:                         }
                   12496:                     }
1.1505    raeburn  12497:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
1.1503    raeburn  12498:                         $dirhashref->{'/'} = 1;
                   12499:                     }
                   12500:                     if ($savefile) {
                   12501:                         if ($relpath eq '') {
                   12502:                             $filehashref->{'/'}{$item} = 1;
                   12503:                         } else {
1.1313    raeburn  12504:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   12505:                         }
                   12506:                     }
1.1503    raeburn  12507:                     $filecount ++;
1.1313    raeburn  12508:                 }
                   12509:             }
                   12510:             closedir($dirh);
                   12511:         }
                   12512:     } else {
                   12513:         my ($dirlistref,$listerror) =
                   12514:             &dirlist($toppath.$relpath);
                   12515:         my @dir_lines;
                   12516:         my $dirptr=16384;
                   12517:         if (ref($dirlistref) eq 'ARRAY') {
1.1503    raeburn  12518:             my $filecount = 0;
1.1313    raeburn  12519:             foreach my $dir_line (sort
                   12520:                               {
                   12521:                                   my ($afile)=split('&',$a,2);
                   12522:                                   my ($bfile)=split('&',$b,2);
                   12523:                                   return (lc($afile) cmp lc($bfile));
                   12524:                               } (@{$dirlistref})) {
                   12525:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   12526:                     split(/\&/,$dir_line,16);
                   12527:                 $item =~ s/\s+$//;
                   12528:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   12529:                 if ($dirptr&$testdir) {
                   12530:                     my $newpath;
                   12531:                     if ($relpath) {
                   12532:                         $newpath = "$relpath/$item";
                   12533:                     } else {
                   12534:                         $newpath = $item;
                   12535:                     }
                   12536:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503    raeburn  12537:                     if ($recurse) {
1.1505    raeburn  12538:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
1.1503    raeburn  12539:                     }
                   12540:                 } elsif (($savefile) || ($relpath eq '')) {
                   12541:                     next if ($nonemptydir && $filecount);
                   12542:                     if ($checkinc || $checkexc) {
                   12543:                         my $extension;
                   12544:                         if ($checkinc) {
                   12545:                             next unless ($extension && $include->{$extension});
                   12546:                         }
                   12547:                         if ($checkexc) {
                   12548:                             next if ($extension && $exclude->{$extension});
                   12549:                         }
                   12550:                     }
                   12551:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
                   12552:                         $dirhashref->{'/'} = 1;
                   12553:                     }
                   12554:                     if ($savefile) {
                   12555:                         if ($relpath eq '') {
                   12556:                             $filehashref->{'/'}{$item} = 1;
                   12557:                         } else {
                   12558:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
1.1313    raeburn  12559:                         }
                   12560:                     }
1.1503    raeburn  12561:                     $filecount ++; 
1.1313    raeburn  12562:                 }
                   12563:             }
                   12564:         }
                   12565:     }
1.1505    raeburn  12566:     if ($addtopdir) {
                   12567:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
                   12568:             $dirhashref->{'/'} = 1;
                   12569:         }
                   12570:     }
1.1313    raeburn  12571:     return;
                   12572: }
                   12573: 
1.1503    raeburn  12574: sub priv_exclude {
                   12575:     return {
                   12576:              meta => 1,
                   12577:              save => 1,
                   12578:              log => 1,
                   12579:              bak => 1,
                   12580:              rights => 1,
                   12581:              DS_Store => 1,
                   12582:            };
                   12583: }
                   12584: 
1.26      www      12585: # -------------------------------------------------------- Value of a Condition
                   12586: 
1.713     albertel 12587: # gets the value of a specific preevaluated condition
                   12588: #    stored in the string  $env{user.state.<cid>}
                   12589: # or looks up a condition reference in the bighash and if if hasn't
                   12590: # already been evaluated recurses into docondval to get the value of
                   12591: # the condition, then memoizing it to 
                   12592: #   $env{user.state.<cid>.<condition>}
1.40      www      12593: sub directcondval {
                   12594:     my $number=shift;
1.620     albertel 12595:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 12596: 	&Apache::lonuserstate::evalstate();
                   12597:     }
1.713     albertel 12598:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   12599: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   12600:     } elsif ($number =~ /^_/) {
                   12601: 	my $sub_condition;
                   12602: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12603: 		&GDBM_READER(),0640)) {
                   12604: 	    $sub_condition=$bighash{'conditions'.$number};
                   12605: 	    untie(%bighash);
                   12606: 	}
                   12607: 	my $value = &docondval($sub_condition);
1.949     raeburn  12608: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 12609: 	return $value;
                   12610:     }
1.620     albertel 12611:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   12612:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      12613:     } else {
                   12614:        return 2;
                   12615:     }
                   12616: }
                   12617: 
1.713     albertel 12618: # get the collection of conditions for this resource
1.26      www      12619: sub condval {
                   12620:     my $condidx=shift;
1.54      www      12621:     my $allpathcond='';
1.713     albertel 12622:     foreach my $cond (split(/\|/,$condidx)) {
                   12623: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   12624: 	    $allpathcond.=
                   12625: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   12626: 	}
1.191     harris41 12627:     }
1.54      www      12628:     $allpathcond=~s/\|$//;
1.713     albertel 12629:     return &docondval($allpathcond);
                   12630: }
                   12631: 
                   12632: #evaluates an expression of conditions
                   12633: sub docondval {
                   12634:     my ($allpathcond) = @_;
                   12635:     my $result=0;
                   12636:     if ($env{'request.course.id'}
                   12637: 	&& defined($allpathcond)) {
                   12638: 	my $operand='|';
                   12639: 	my @stack;
                   12640: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   12641: 	    if ($chunk eq '(') {
                   12642: 		push @stack,($operand,$result);
                   12643: 	    } elsif ($chunk eq ')') {
                   12644: 		my $before=pop @stack;
                   12645: 		if (pop @stack eq '&') {
                   12646: 		    $result=$result>$before?$before:$result;
                   12647: 		} else {
                   12648: 		    $result=$result>$before?$result:$before;
                   12649: 		}
                   12650: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   12651: 		$operand=$chunk;
                   12652: 	    } else {
                   12653: 		my $new=directcondval($chunk);
                   12654: 		if ($operand eq '&') {
                   12655: 		    $result=$result>$new?$new:$result;
                   12656: 		} else {
                   12657: 		    $result=$result>$new?$result:$new;
                   12658: 		}
                   12659: 	    }
                   12660: 	}
1.26      www      12661:     }
                   12662:     return $result;
1.421     albertel 12663: }
                   12664: 
                   12665: # ---------------------------------------------------- Devalidate courseresdata
                   12666: 
                   12667: sub devalidatecourseresdata {
                   12668:     my ($coursenum,$coursedomain)=@_;
                   12669:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12670:     &devalidate_cache_new('courseres',$hashid);
1.28      www      12671: }
                   12672: 
1.763     www      12673: 
1.200     www      12674: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     12675: #
                   12676: #  Parameters:
                   12677: #      $coursenum    - Number of the course.
                   12678: #      $coursedomain - Domain at which the course was created.
                   12679: #  Returns:
                   12680: #     A hash of the course parameters along (I think) with timestamps
                   12681: #     and version info.
1.877     foxr     12682: 
1.624     albertel 12683: sub get_courseresdata {
                   12684:     my ($coursenum,$coursedomain)=@_;
1.200     www      12685:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   12686:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12687:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 12688:     my %dumpreply;
1.417     albertel 12689:     unless (defined($cached)) {
1.624     albertel 12690: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 12691: 	$result=\%dumpreply;
1.251     albertel 12692: 	my ($tmp) = keys(%dumpreply);
                   12693: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 12694: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 12695: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   12696: 	    return $tmp;
1.416     albertel 12697: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 12698: 	    $result=undef;
1.599     albertel 12699: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 12700: 	}
                   12701:     }
1.624     albertel 12702:     return $result;
                   12703: }
                   12704: 
1.633     albertel 12705: sub devalidateuserresdata {
                   12706:     my ($uname,$udom)=@_;
                   12707:     my $hashid="$udom:$uname";
                   12708:     &devalidate_cache_new('userres',$hashid);
                   12709: }
                   12710: 
1.624     albertel 12711: sub get_userresdata {
                   12712:     my ($uname,$udom)=@_;
                   12713:     #most student don\'t have any data set, check if there is some data
                   12714:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   12715: 
                   12716:     my $hashid="$udom:$uname";
                   12717:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   12718:     if (!defined($cached)) {
                   12719: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   12720: 	$result=\%resourcedata;
                   12721: 	&do_cache_new('userres',$hashid,$result,600);
                   12722:     }
                   12723:     my ($tmp)=keys(%$result);
                   12724:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   12725: 	return $result;
                   12726:     }
                   12727:     #error 2 occurs when the .db doesn't exist
                   12728:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  12729:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   12730: 	    &logthis("<font color=\"blue\">WARNING:".
                   12731: 		     " Trying to get resource data for ".
                   12732: 		     $uname." at ".$udom.": ".
                   12733: 		     $tmp."</font>");
                   12734:         }
1.624     albertel 12735:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 12736: 	#&EXT_cache_set($udom,$uname);
                   12737: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 12738: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 12739:     }
                   12740:     return $tmp;
                   12741: }
1.879     foxr     12742: #----------------------------------------------- resdata - return resource data
                   12743: #  Purpose:
                   12744: #    Return resource data for either users or for a course.
                   12745: #  Parameters:
                   12746: #     $name      - Course/user name.
                   12747: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  12748: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  12749: #     $mapp      - decluttered URL of enclosing map  
                   12750: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   12751: #     $recurseup - Ref to array of map URLs, starting with map containing
                   12752: #                  $mapp up through hierarchy of nested maps to top level map.  
                   12753: #     $courseid  - CourseID (first part of param identifier).
                   12754: #     $modifier  - Middle part of param identifier.
                   12755: #     $what      - Last part of param identifier.
1.879     foxr     12756: #     @which     - Array of names of resources desired.
                   12757: #  Returns:
                   12758: #     The value of the first reasource in @which that is found in the
                   12759: #     resource hash.
                   12760: #  Exceptional Conditions:
                   12761: #     If the $type passed in is not valid (not the string 'course' or 
                   12762: #     'user', an undefined  reference is returned.
                   12763: #     If none of the resources are found, an undef is returned
1.624     albertel 12764: sub resdata {
1.1301    raeburn  12765:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   12766:         $modifier,$what,@which)=@_;
1.624     albertel 12767:     my $result;
                   12768:     if ($type eq 'course') {
                   12769: 	$result=&get_courseresdata($name,$domain);
                   12770:     } elsif ($type eq 'user') {
                   12771: 	$result=&get_userresdata($name,$domain);
                   12772:     }
                   12773:     if (!ref($result)) { return $result; }    
1.251     albertel 12774:     foreach my $item (@which) {
1.1301    raeburn  12775:         if ($item->[1] eq 'course') {
                   12776:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   12777:                 unless ($$recursed) {
1.1302    raeburn  12778:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  12779:                     $$recursed = 1;
                   12780:                 }
                   12781:                 foreach my $item (@${recurseup}) {
                   12782:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   12783:                     last if (defined($result->{$norecursechk}));
                   12784:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   12785:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   12786:                 }
                   12787:             }
                   12788:         }
                   12789:         if (defined($result->{$item->[0]})) {
1.927     albertel 12790: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12791: 	}
1.250     albertel 12792:     }
1.291     albertel 12793:     return undef;
1.200     www      12794: }
                   12795: 
1.1360    raeburn  12796: sub get_domain_lti {
                   12797:     my ($cdom,$context) = @_;
1.1483    raeburn  12798:     my ($name,$cachename,%lti);
1.1360    raeburn  12799:     if ($context eq 'consumer') {
                   12800:         $name = 'ltitools';
                   12801:     } elsif ($context eq 'provider') {
                   12802:         $name = 'lti';
1.1483    raeburn  12803:     } elsif ($context eq 'linkprot') {
                   12804:         $name = 'ltisec';
1.1360    raeburn  12805:     } else {
                   12806:         return %lti;
                   12807:     }
1.1483    raeburn  12808:     if ($context eq 'linkprot') {
                   12809:         $cachename = $context;
                   12810:     } else {
                   12811:         $cachename = $name;
                   12812:     }
                   12813:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298    raeburn  12814:     if (defined($cached)) {
                   12815:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12816:             %lti = %{$result};
1.1298    raeburn  12817:         }
                   12818:     } else {
1.1360    raeburn  12819:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12820:         if (ref($domconfig{$name}) eq 'HASH') {
1.1483    raeburn  12821:             if ($context eq 'linkprot') {
                   12822:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12823:                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12824:                 }
                   12825:             } else {
                   12826:                 %lti = %{$domconfig{$name}};
                   12827:             }
1.1298    raeburn  12828:         }
                   12829:         my $cachetime = 24*60*60;
1.1483    raeburn  12830:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298    raeburn  12831:     }
1.1360    raeburn  12832:     return %lti;
1.1298    raeburn  12833: }
                   12834: 
1.1463    raeburn  12835: sub get_course_lti {
1.1510    raeburn  12836:     my ($cnum,$cdom,$context) = @_;
                   12837:     my ($name,$cachename,%lti);
                   12838:     if ($context eq 'consumer') {
                   12839:         $name = 'ltitools';
                   12840:         $cachename = 'courseltitools';
                   12841:     } elsif ($context eq 'provider') {
                   12842:         $name = 'lti';
                   12843:         $cachename = 'courselti';
                   12844:     } else {
                   12845:         return %lti;
                   12846:     }
1.1463    raeburn  12847:     my $hashid=$cdom.'_'.$cnum;
1.1510    raeburn  12848:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
1.1463    raeburn  12849:     if (defined($cached)) {
                   12850:         if (ref($result) eq 'HASH') {
1.1510    raeburn  12851:             %lti = %{$result};
1.1463    raeburn  12852:         }
                   12853:     } else {
1.1510    raeburn  12854:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
1.1463    raeburn  12855:         my $cachetime = 24*60*60;
1.1510    raeburn  12856:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
1.1463    raeburn  12857:     }
1.1510    raeburn  12858:     return %lti;
1.1463    raeburn  12859: }
                   12860: 
1.1479    raeburn  12861: sub courselti_itemid {
                   12862:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12863:     my ($chome,$itemid);
                   12864:     $chome = &homeserver($cnum,$cdom);
                   12865:     return if ($chome eq 'no_host');
                   12866:     if (ref($params) eq 'HASH') {
                   12867:         my $rep;
                   12868:         if (grep { $_ eq $chome } current_machine_ids()) {
                   12869:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12870:         } else {
                   12871:             my $escurl = &escape($url);
                   12872:             my $escmethod = &escape($method);
                   12873:             my $items = &freeze_escape($params);
                   12874:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12875:         }
                   12876:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12877:                 ($rep eq 'unknown_cmd')) {
                   12878:             $itemid = $rep;
                   12879:         }
                   12880:     }
                   12881:     return $itemid;
                   12882: }
                   12883: 
                   12884: sub domainlti_itemid {
                   12885:     my ($cdom,$url,$method,$params,$context) = @_;
                   12886:     my ($primary_id,$itemid);
                   12887:     $primary_id = &domain($cdom,'primary');
                   12888:     return if ($primary_id eq '');
                   12889:     if (ref($params) eq 'HASH') {
                   12890:         my $rep;
                   12891:         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12892:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12893:         } else {
                   12894:             my $cnum = '';
                   12895:             my $escurl = &escape($url);
                   12896:             my $escmethod = &escape($method);
                   12897:             my $items = &freeze_escape($params);
                   12898:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   12899:         }
                   12900:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12901:                 ($rep eq 'unknown_cmd')) {
                   12902:             $itemid = $rep;
                   12903:         }
                   12904:     }
                   12905:     return $itemid;
                   12906: }
                   12907: 
1.1513    raeburn  12908: sub get_ltitools_id {
                   12909:     my ($context,$cdom,$cnum,$title) = @_;
                   12910:     my ($lockhash,$tries,$gotlock,$id,$error);
                   12911: 
                   12912:     # get lock on ltitools db
                   12913:     $lockhash = {
                   12914:                    lock => $env{'user.name'}.
                   12915:                            ':'.$env{'user.domain'},
                   12916:                 };
                   12917:     $tries = 0;
                   12918:     if ($context eq 'domain') {
                   12919:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   12920:     } else {
                   12921:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   12922:     }
                   12923:     while (($gotlock ne 'ok') && ($tries<10)) {
                   12924:         $tries ++;
                   12925:         sleep (0.1);
                   12926:         if ($context eq 'domain') {
                   12927:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   12928:         } else {
                   12929:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   12930:         }
                   12931:     }
                   12932:     if ($gotlock eq 'ok') {
                   12933:         my %currids;
                   12934:         if ($context eq 'domain') {
                   12935:             %currids = &dump_dom('ltitools',$cdom);
                   12936:         } else {
                   12937:             %currids = &dump('ltitools',$cdom,$cnum);
                   12938:         }
                   12939:         if ($currids{'lock'}) {
                   12940:             delete($currids{'lock'});
                   12941:             if (keys(%currids)) {
                   12942:                 my @curr = sort { $a <=> $b } keys(%currids);
                   12943:                 if ($curr[-1] =~ /^\d+$/) {
                   12944:                     $id = 1 + $curr[-1];
                   12945:                 }
                   12946:             } else {
                   12947:                 $id = 1;
                   12948:             }
                   12949:             if ($id) {
                   12950:                 if ($context eq 'domain') {
                   12951:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
                   12952:                         $error = 'nostore';
                   12953:                     }
                   12954:                 } else {
                   12955:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
                   12956:                         $error = 'nostore';
                   12957:                     }
                   12958:                 }
                   12959:             } else {
                   12960:                 $error = 'nonumber';
                   12961:             }
                   12962:         }
                   12963:         my $dellockoutcome;
                   12964:         if ($context eq 'domain') {
                   12965:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
                   12966:         } else {
                   12967:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
                   12968:         }
                   12969:     } else {
                   12970:         $error = 'nolock';
                   12971:     }
                   12972:     return ($id,$error);
                   12973: }
                   12974: 
1.1496    raeburn  12975: sub count_supptools {
                   12976:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
                   12977:     my $hashid=$cnum.':'.$cdom;
                   12978:     my ($numexttools,$cached);
                   12979:     unless ($ignorecache) {
                   12980:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
                   12981:     }
                   12982:     unless (defined($cached)) {
                   12983:         my $chome=&homeserver($cnum,$cdom);
                   12984:         $numexttools = 0;
                   12985:         unless ($chome eq 'no_host') {
1.1500    raeburn  12986:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
1.1496    raeburn  12987:             if (ref($supplemental) eq 'HASH') {
                   12988:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12989:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12990:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   12991:                             $numexttools ++;
                   12992:                         }
                   12993:                     }
                   12994:                 }
                   12995:             }
                   12996:         }
                   12997:         &do_cache_new('supptools',$hashid,$numexttools,600);
                   12998:     }
                   12999:     return $numexttools;
                   13000: }
                   13001: 
                   13002: sub has_unhidden_suppfiles {
1.1498    raeburn  13003:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
1.1236    raeburn  13004:     my $hashid=$cnum.':'.$cdom;
1.1496    raeburn  13005:     my ($showsupp,$cached);
1.1236    raeburn  13006:     unless ($ignorecache) {
1.1496    raeburn  13007:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
1.1236    raeburn  13008:     }
                   13009:     unless (defined($cached)) {
                   13010:         my $chome=&homeserver($cnum,$cdom);
                   13011:         unless ($chome eq 'no_host') {
1.1500    raeburn  13012:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
1.1496    raeburn  13013:             if (ref($supplemental) eq 'HASH') {
                   13014:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   13015:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   13016:                         next if ($key =~ /\.sequence$/);
                   13017:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   13018:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   13019:                                 unless ($supplemental->{'hidden'}->{$id}) {
                   13020:                                     $showsupp = 1;
                   13021:                                     last;
                   13022:                                 }
                   13023:                             }
                   13024:                         }
                   13025:                         last if ($showsupp);
                   13026:                     }
                   13027:                 }
                   13028:             }
1.1236    raeburn  13029:         }
1.1496    raeburn  13030:         &do_cache_new('showsupp',$hashid,$showsupp,600);
1.1236    raeburn  13031:     }
1.1496    raeburn  13032:     return $showsupp;
                   13033: }
                   13034: 
1.379     matthew  13035: #
                   13036: # EXT resource caching routines
                   13037: #
                   13038: 
1.1302    raeburn  13039: {
                   13040: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   13041: #
                   13042: # The course for which we cache
                   13043: my $cachedmapkey='';
                   13044: # The cached recursive maps for this course
                   13045: my %cachedmaps=();
                   13046: # When this was last done
                   13047: my $cachedmaptime='';
                   13048: 
1.379     matthew  13049: sub clear_EXT_cache_status {
1.383     albertel 13050:     &delenv('cache.EXT.');
1.379     matthew  13051: }
                   13052: 
                   13053: sub EXT_cache_status {
                   13054:     my ($target_domain,$target_user) = @_;
1.383     albertel 13055:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 13056:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  13057:         # We know already the user has no data
                   13058:         return 1;
                   13059:     } else {
                   13060:         return 0;
                   13061:     }
                   13062: }
                   13063: 
                   13064: sub EXT_cache_set {
                   13065:     my ($target_domain,$target_user) = @_;
1.383     albertel 13066:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  13067:     #&appenv({$cachename => time});
1.379     matthew  13068: }
                   13069: 
1.28      www      13070: # --------------------------------------------------------- Value of a Variable
1.58      www      13071: sub EXT {
1.715     albertel 13072: 
1.1461    raeburn  13073:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68      www      13074:     unless ($varname) { return ''; }
1.218     albertel 13075:     #get real user name/domain, courseid and symb
                   13076:     my $courseid;
1.359     albertel 13077:     my $publicuser;
1.427     www      13078:     if ($symbparm) {
                   13079: 	$symbparm=&get_symb_from_alias($symbparm);
                   13080:     }
1.218     albertel 13081:     if (!($uname && $udom)) {
1.790     albertel 13082:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 13083:       if (!$symbparm) {	$symbparm=$cursymb; }
                   13084:     } else {
1.620     albertel 13085: 	$courseid=$env{'request.course.id'};
1.218     albertel 13086:     }
1.48      www      13087:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   13088:     my $rest;
1.320     albertel 13089:     if (defined($therest[0])) {
1.48      www      13090:        $rest=join('.',@therest);
                   13091:     } else {
                   13092:        $rest='';
                   13093:     }
1.320     albertel 13094: 
1.57      www      13095:     my $qualifierrest=$qualifier;
                   13096:     if ($rest) { $qualifierrest.='.'.$rest; }
                   13097:     my $spacequalifierrest=$space;
                   13098:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      13099:     if ($realm eq 'user') {
1.48      www      13100: # --------------------------------------------------------------- user.resource
                   13101: 	if ($space eq 'resource') {
1.651     albertel 13102: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   13103: 		  || defined($Apache::lonhomework::parsing_a_task))
                   13104: 		 &&
1.1469    raeburn  13105: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 13106: 		# if we are in the middle of processing the resource the
                   13107: 		# get the value we are planning on committing
                   13108:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   13109:                     return $Apache::lonhomework::results{$qualifierrest};
                   13110:                 } else {
                   13111:                     return $Apache::lonhomework::history{$qualifierrest};
                   13112:                 }
1.335     albertel 13113: 	    } else {
1.359     albertel 13114: 		my %restored;
1.620     albertel 13115: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 13116: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   13117: 		} else {
                   13118: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   13119: 		}
1.335     albertel 13120: 		return $restored{$qualifierrest};
                   13121: 	    }
1.48      www      13122: # ----------------------------------------------------------------- user.access
                   13123:         } elsif ($space eq 'access') {
1.218     albertel 13124: 	    # FIXME - not supporting calls for a specific user
1.48      www      13125:             return &allowed($qualifier,$rest);
                   13126: # ------------------------------------------ user.preferences, user.environment
                   13127:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 13128: 	    if (($uname eq $env{'user.name'}) &&
                   13129: 		($udom eq $env{'user.domain'})) {
                   13130: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 13131: 	    } else {
1.359     albertel 13132: 		my %returnhash;
                   13133: 		if (!$publicuser) {
                   13134: 		    %returnhash=&userenvironment($udom,$uname,
                   13135: 						 $qualifierrest);
                   13136: 		}
1.218     albertel 13137: 		return $returnhash{$qualifierrest};
                   13138: 	    }
1.48      www      13139: # ----------------------------------------------------------------- user.course
                   13140:         } elsif ($space eq 'course') {
1.218     albertel 13141: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 13142:             return $env{join('.',('request.course',$qualifier))};
1.48      www      13143: # ------------------------------------------------------------------- user.role
                   13144:         } elsif ($space eq 'role') {
1.218     albertel 13145: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 13146:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      13147:             if ($qualifier eq 'value') {
                   13148: 		return $role;
                   13149:             } elsif ($qualifier eq 'extent') {
                   13150:                 return $where;
                   13151:             }
                   13152: # ----------------------------------------------------------------- user.domain
                   13153:         } elsif ($space eq 'domain') {
1.218     albertel 13154:             return $udom;
1.48      www      13155: # ------------------------------------------------------------------- user.name
                   13156:         } elsif ($space eq 'name') {
1.218     albertel 13157:             return $uname;
1.48      www      13158: # ---------------------------------------------------- Any other user namespace
1.29      www      13159:         } else {
1.359     albertel 13160: 	    my %reply;
                   13161: 	    if (!$publicuser) {
                   13162: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   13163: 	    }
                   13164: 	    return $reply{$qualifierrest};
1.48      www      13165:         }
1.236     www      13166:     } elsif ($realm eq 'query') {
                   13167: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 13168:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   13169: 						[$spacequalifierrest]);
1.620     albertel 13170: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      13171:    } elsif ($realm eq 'request') {
1.48      www      13172: # ------------------------------------------------------------- request.browser
                   13173:         if ($space eq 'browser') {
1.1145    bisitz   13174:             return $env{'browser.'.$qualifier};
1.57      www      13175: # ------------------------------------------------------------ request.filename
                   13176:         } else {
1.620     albertel 13177:             return $env{'request.'.$spacequalifierrest};
1.29      www      13178:         }
1.28      www      13179:     } elsif ($realm eq 'course') {
1.48      www      13180: # ---------------------------------------------------------- course.description
1.620     albertel 13181:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      13182:     } elsif ($realm eq 'resource') {
1.165     www      13183: 
1.620     albertel 13184: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 13185: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   13186: 	}
1.693     albertel 13187: 
1.1232    raeburn  13188:         if ($qualifier eq '') {
                   13189: 	    if ($space eq 'title') {
                   13190: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   13191: 	        return &gettitle($symbparm);
                   13192: 	    }
1.693     albertel 13193: 	
1.1232    raeburn  13194: 	    if ($space eq 'map') {
                   13195: 	        my ($map) = &decode_symb($symbparm);
                   13196: 	        return &symbread($map);
                   13197: 	    }
                   13198:             if ($space eq 'maptitle') {
                   13199:                 my ($map) = &decode_symb($symbparm);
                   13200:                 return &gettitle($map);
                   13201:             }
                   13202: 	    if ($space eq 'filename') {
                   13203: 	        if ($symbparm) {
                   13204: 		    return &clutter((&decode_symb($symbparm))[2]);
                   13205: 	        }
                   13206: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 13207: 	    }
1.1232    raeburn  13208: 
1.1233    raeburn  13209:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   13210:                 if ($space eq 'visibleparts') {
                   13211:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   13212:                     my $item;
                   13213:                     if (ref($navmap)) {
                   13214:                         my $res = $navmap->getBySymb($symbparm);
                   13215:                         my $parts = $res->parts();
                   13216:                         if (ref($parts) eq 'ARRAY') {
                   13217:                             $item = join(',',@{$parts});
                   13218:                         }
                   13219:                         undef($navmap);
1.1232    raeburn  13220:                     }
1.1233    raeburn  13221:                     return $item;
1.1232    raeburn  13222:                 }
                   13223:             }
                   13224:         }
1.693     albertel 13225: 
1.1301    raeburn  13226: 	my ($section, $group, @groups, @recurseup, $recursed);
1.1461    raeburn  13227:         if (ref($recurseupref) eq 'ARRAY') {
                   13228:             @recurseup = @{$recurseupref};
                   13229:             $recursed = 1;
                   13230:         }
1.1301    raeburn  13231: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  13232:         if (($courseid eq '') && ($cid)) {
                   13233:             $courseid = $cid;
                   13234:         }
                   13235: 	if (($symbparm && $courseid) && 
                   13236: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      13237: 
1.218     albertel 13238: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      13239: 
1.60      www      13240: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 13241: 	    my $symbp=$symbparm;
1.1301    raeburn  13242: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 13243: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  13244:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 13245: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 13246: 	    if (($env{'user.name'} eq $uname) &&
                   13247: 		($env{'user.domain'} eq $udom)) {
                   13248: 		$section=$env{'request.course.sec'};
1.733     raeburn  13249:                 @groups = split(/:/,$env{'request.course.groups'});  
                   13250:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 13251: 	    } else {
1.539     albertel 13252: 		if (! defined($usection)) {
1.551     albertel 13253: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 13254: 		} else {
                   13255: 		    $section = $usection;
                   13256: 		}
1.733     raeburn  13257:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 13258: 	    }
                   13259: 
                   13260: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   13261: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  13262:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 13263: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   13264: 
1.593     albertel 13265: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 13266: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  13267:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 13268: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      13269: 
1.60      www      13270: # ----------------------------------------------------------- first, check user
1.624     albertel 13271: 
1.1301    raeburn  13272: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   13273:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 13274: 				       ([$courselevelr,'resource'],
                   13275: 					[$courselevelm,'map'     ],
1.1301    raeburn  13276:                                         [$courseleveli,'map'     ],
1.927     albertel 13277: 					[$courselevel, 'course'  ]));
1.931     albertel 13278: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      13279: 
1.594     albertel 13280: # ------------------------------------------------ second, check some of course
1.684     raeburn  13281:             my $coursereply;
1.691     raeburn  13282:             if (@groups > 0) {
                   13283:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  13284:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   13285:                                        $mapp,\$recursed,\@recurseup);
                   13286:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  13287:             }
1.96      www      13288: 
1.684     raeburn  13289: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 13290: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  13291: 				  'course',$mapp,\$recursed,\@recurseup,
                   13292:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 13293: 				  ([$seclevelr,   'resource'],
                   13294: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  13295:                                    [$secleveli,   'map'     ],
1.927     albertel 13296: 				   [$seclevel,    'course'  ],
                   13297: 				   [$courselevelr,'resource']));
                   13298: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      13299: 
1.60      www      13300: # ------------------------------------------------------ third, check map parms
1.218     albertel 13301: 	    my %parmhash=();
                   13302: 	    my $thisparm='';
                   13303: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 13304: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 13305: 		    &GDBM_READER(),0640)) {
1.218     albertel 13306: 		$thisparm=$parmhash{$symbparm};
                   13307: 		untie(%parmhash);
                   13308: 	    }
1.927     albertel 13309: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 13310: 	}
1.594     albertel 13311: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  13312:  
                   13313:         my $what = $spacequalifierrest;
                   13314: 	$what=~s/\./\_/;
1.282     albertel 13315: 	my $filename;
                   13316: 	if (!$symbparm) { $symbparm=&symbread(); }
                   13317: 	if ($symbparm) {
1.409     www      13318: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 13319: 	} else {
1.620     albertel 13320: 	    $filename=$env{'request.filename'};
1.282     albertel 13321: 	}
1.1362    raeburn  13322:         my $toolsymb;
                   13323:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   13324:             $toolsymb = $symbparm;
                   13325:         }
                   13326: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 13327: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  13328: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 13329: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      13330: 
1.1301    raeburn  13331: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 13332: 	if ($symbparm && defined($courseid) && 
1.620     albertel 13333: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 13334: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   13335: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  13336: 				     'course',$mapp,\$recursed,\@recurseup,
                   13337:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 13338: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  13339:                                       [$courseleveli,'map'   ],
1.927     albertel 13340: 				      [$courselevel, 'course']));
                   13341: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 13342: 	}
1.145     www      13343: # ------------------------------------------------------------------ Cascade up
1.218     albertel 13344: 	unless ($space eq '0') {
1.336     albertel 13345: 	    my @parts=split(/_/,$space);
                   13346: 	    my $id=pop(@parts);
                   13347: 	    my $part=join('_',@parts);
                   13348: 	    if ($part eq '') { $part='0'; }
1.927     albertel 13349: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 13350: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  13351: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 13352: 	}
1.395     albertel 13353: 	if ($recurse) { return undef; }
1.1362    raeburn  13354: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 13355: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      13356: # ---------------------------------------------------- Any other user namespace
                   13357:     } elsif ($realm eq 'environment') {
                   13358: # ----------------------------------------------------------------- environment
1.620     albertel 13359: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   13360: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 13361: 	} else {
1.770     albertel 13362: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   13363: 		return '';
                   13364: 	    }
1.219     albertel 13365: 	    my %returnhash=&userenvironment($udom,$uname,
                   13366: 					    $spacequalifierrest);
                   13367: 	    return $returnhash{$spacequalifierrest};
                   13368: 	}
1.28      www      13369:     } elsif ($realm eq 'system') {
1.48      www      13370: # ----------------------------------------------------------------- system.time
                   13371: 	if ($space eq 'time') {
                   13372: 	    return time;
                   13373:         }
1.696     albertel 13374:     } elsif ($realm eq 'server') {
                   13375: # ----------------------------------------------------------------- system.time
                   13376: 	if ($space eq 'name') {
                   13377: 	    return $ENV{'SERVER_NAME'};
                   13378:         }
1.1415    raeburn  13379:     } elsif ($realm eq 'client') {
                   13380:         if ($space eq 'remote_addr') {
1.1441    raeburn  13381:             return &get_requestor_ip();
1.1415    raeburn  13382:         }
1.28      www      13383:     }
1.48      www      13384:     return '';
1.61      www      13385: }
                   13386: 
1.927     albertel 13387: sub get_reply {
                   13388:     my ($reply_value) = @_;
1.940     raeburn  13389:     if (ref($reply_value) eq 'ARRAY') {
                   13390:         if (wantarray) {
                   13391: 	    return @$reply_value;
                   13392:         }
                   13393:         return $reply_value->[0];
                   13394:     } else {
                   13395:         return $reply_value;
1.927     albertel 13396:     }
                   13397: }
                   13398: 
1.691     raeburn  13399: sub check_group_parms {
1.1301    raeburn  13400:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   13401:         $recursed,$recurseupref) = @_;
                   13402:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   13403:                   [$what,'course']);
                   13404:     my $coursereply;
1.691     raeburn  13405:     foreach my $group (@{$groups}) {
1.1301    raeburn  13406:         my @groupitems = ();
1.691     raeburn  13407:         foreach my $level (@levels) {
1.927     albertel 13408:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   13409:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  13410:         }
1.1301    raeburn  13411:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   13412:                                    $env{'course.'.$courseid.'.domain'},
                   13413:                                    'course',$mapp,$recursed,$recurseupref,
                   13414:                                    $courseid,'.['.$group.'].',$what,
                   13415:                                    @groupitems);
                   13416:         last if (defined($coursereply));
1.691     raeburn  13417:     }
                   13418:     return $coursereply;
                   13419: }
                   13420: 
1.1301    raeburn  13421: sub get_map_hierarchy {
1.1302    raeburn  13422:     my ($mapname,$courseid) = @_;
                   13423:     my @recurseup = ();
1.1301    raeburn  13424:     if ($mapname) {
1.1302    raeburn  13425:         if (($cachedmapkey eq $courseid) &&
                   13426:             (abs($cachedmaptime-time)<5)) {
                   13427:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   13428:                 return @{$cachedmaps{$mapname}};
                   13429:             }
                   13430:         }
1.1301    raeburn  13431:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13432:         if (ref($navmap)) {
                   13433:             @recurseup = $navmap->recurseup_maps($mapname);
                   13434:             undef($navmap);
1.1302    raeburn  13435:             $cachedmaps{$mapname} = \@recurseup;
                   13436:             $cachedmaptime=time;
                   13437:             $cachedmapkey=$courseid;
1.1301    raeburn  13438:         }
                   13439:     }
                   13440:     return @recurseup;
                   13441: }
                   13442: 
1.1302    raeburn  13443: }
                   13444: 
1.691     raeburn  13445: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  13446:     my ($courseid,@groups) = @_;
                   13447:     @groups = sort(@groups);
1.691     raeburn  13448:     return @groups;
                   13449: }
                   13450: 
1.395     albertel 13451: sub packages_tab_default {
1.1362    raeburn  13452:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 13453:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 13454: 
                   13455:     my (@extension,@specifics,$do_default);
1.1362    raeburn  13456:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 13457: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 13458: 	if ($pack_type eq 'default') {
                   13459: 	    $do_default=1;
                   13460: 	} elsif ($pack_type eq 'extension') {
                   13461: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 13462: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 13463: 	    # only look at packages defaults for packages that this id is
1.738     albertel 13464: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   13465: 	}
                   13466:     }
                   13467:     # first look for a package that matches the requested part id
                   13468:     foreach my $package (@specifics) {
                   13469: 	my (undef,$pack_type,$pack_part)=@{$package};
                   13470: 	next if ($pack_part ne $part);
                   13471: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   13472: 	    return $packagetab{"$pack_type&$name&default"};
                   13473: 	}
                   13474:     }
                   13475:     # look for any possible matching non extension_ package
                   13476:     foreach my $package (@specifics) {
                   13477: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 13478: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   13479: 	    return $packagetab{"$pack_type&$name&default"};
                   13480: 	}
1.585     albertel 13481: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 13482: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   13483: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 13484: 	}
                   13485:     }
1.738     albertel 13486:     # look for any posible extension_ match
                   13487:     foreach my $package (@extension) {
                   13488: 	my ($package,$pack_type)=@{$package};
                   13489: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   13490: 	    return $packagetab{"$pack_type&$name&default"};
                   13491: 	}
                   13492: 	if (defined($packagetab{$package."&$name&default"})) {
                   13493: 	    return $packagetab{$package."&$name&default"};
                   13494: 	}
                   13495:     }
                   13496:     # look for a global default setting
                   13497:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   13498: 	return $packagetab{"default&$name&default"};
                   13499:     }
1.395     albertel 13500:     return undef;
                   13501: }
                   13502: 
1.334     albertel 13503: sub add_prefix_and_part {
                   13504:     my ($prefix,$part)=@_;
                   13505:     my $keyroot;
                   13506:     if (defined($prefix) && $prefix !~ /^__/) {
                   13507: 	# prefix that has a part already
                   13508: 	$keyroot=$prefix;
                   13509:     } elsif (defined($prefix)) {
                   13510: 	# prefix that is missing a part
                   13511: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   13512:     } else {
                   13513: 	# no prefix at all
                   13514: 	if (defined($part)) { $keyroot='_'.$part; }
                   13515:     }
                   13516:     return $keyroot;
                   13517: }
                   13518: 
1.71      www      13519: # ---------------------------------------------------------------- Get metadata
                   13520: 
1.599     albertel 13521: my %metaentry;
1.1070    www      13522: my %importedpartids;
1.1369    raeburn  13523: my %importedrespids;
1.71      www      13524: sub metadata {
1.1362    raeburn  13525:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      13526:     $uri=&declutter($uri);
1.288     albertel 13527:     # if it is a non metadata possible uri return quickly
1.529     albertel 13528:     if (($uri eq '') || 
                   13529: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  13530: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  13531:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 13532: 	return undef;
                   13533:     }
1.1261    raeburn  13534:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 13535: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 13536: 	return undef;
1.288     albertel 13537:     }
1.73      www      13538:     my $filename=$uri;
                   13539:     $uri=~s/\.meta$//;
1.172     www      13540: #
                   13541: # Is the metadata already cached?
1.177     www      13542: # Look at timestamp of caching
1.172     www      13543: # Everything is cached by the main uri, libraries are never directly cached
                   13544: #
1.428     albertel 13545:     if (!defined($liburi)) {
1.599     albertel 13546: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 13547: 	if (defined($cached)) { return $result->{':'.$what}; }
                   13548:     }
1.1362    raeburn  13549: 
                   13550: #
                   13551: # If the uri is for an external tool the file from
                   13552: # which metadata should be retrieved depends on whether
                   13553: # the tool had been configured to be gradable (set in the Course
                   13554: # Editor or Resource Editor).
                   13555: #
                   13556: # If a valid symb has been included as the third arg in the call
                   13557: # to &metadata() that can be used to retrieve the value of
                   13558: # parameter_0_gradable set for the resource, and included in the
                   13559: # uploaded map containing the tool. The value is retrieved via
                   13560: # &EXT(), if a valid symb is available.  Otherwise the value of
                   13561: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  13562: # is retrieved via &get().
                   13563: #
                   13564: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   13565: # hiddenresource and encrypturl (during course initialization)
                   13566: # the map-level parameter for resource.0.gradable included in the 
                   13567: # uploaded map containing the tool will not yet have been stored
                   13568: # in the user_course_parms.db file for the user's session, so in 
                   13569: # this case fall back to retrieving gradable status from the
                   13570: # exttool_$marker.db file.
1.1362    raeburn  13571: #
                   13572: # In order to avoid an infinite loop, &metadata() will return
                   13573: # before a call to &EXT(), if the uri is for an external tool
                   13574: # and the $what for which metadata is being requested is
                   13575: # parameter_0_gradable or 0_gradable.
                   13576: #
                   13577: 
                   13578:     if ($uri =~ /ext\.tool$/) {
                   13579:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   13580:             return;
                   13581:         } else {
                   13582:             my ($checked,$use_passback);
                   13583:             if ($toolsymb ne '') {
                   13584:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  13585:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  13586:                     $checked = 1;
                   13587:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   13588:                         $use_passback = 1;
                   13589:                     }
                   13590:                 }
                   13591:             }
                   13592:             unless ($checked) {
                   13593:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   13594:                 $marker=~s/\D//g;
1.1363    raeburn  13595:                 if ($marker) {
1.1362    raeburn  13596:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   13597:                     $use_passback = $toolsettings{'gradable'};
                   13598:                 }
                   13599:             }
                   13600:             if ($use_passback) {
                   13601:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   13602:             } else {
                   13603:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   13604:             }
                   13605:         }
                   13606:     }
                   13607: 
1.428     albertel 13608:     {
1.1069    www      13609: # Imported parts would go here
1.1369    raeburn  13610:         my @origfiletagids=();
1.1069    www      13611:         my $importedparts=0;
1.1369    raeburn  13612: 
                   13613: # Imported responseids would go here
                   13614:         my $importedresponses=0;
1.172     www      13615: #
                   13616: # Is this a recursive call for a library?
                   13617: #
1.599     albertel 13618: #	if (! exists($metacache{$uri})) {
                   13619: #	    $metacache{$uri}={};
                   13620: #	}
1.924     albertel 13621: 	my $cachetime = 60*60;
1.171     www      13622:         if ($liburi) {
                   13623: 	    $liburi=&declutter($liburi);
                   13624:             $filename=$liburi;
1.401     bowersj2 13625:         } else {
1.599     albertel 13626: 	    &devalidate_cache_new('meta',$uri);
                   13627: 	    undef(%metaentry);
1.401     bowersj2 13628: 	}
1.140     www      13629:         my %metathesekeys=();
1.73      www      13630:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 13631: 	my $metastring;
1.1140    www      13632: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 13633: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 13634: 	    $metastring = 
1.929     albertel 13635: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 13636: 					  ('grade_target' => 'meta'));
                   13637: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  13638: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   13639:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 13640: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 13641: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 13642: 	    $metastring=&getfile($file);
1.489     albertel 13643: 	}
1.208     albertel 13644:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      13645:         my $token;
1.140     www      13646:         undef %metathesekeys;
1.71      www      13647:         while ($token=$parser->get_token) {
1.339     albertel 13648: 	    if ($token->[0] eq 'S') {
                   13649: 		if (defined($token->[2]->{'package'})) {
1.172     www      13650: #
                   13651: # This is a package - get package info
                   13652: #
1.339     albertel 13653: 		    my $package=$token->[2]->{'package'};
                   13654: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13655: 		    if (defined($token->[2]->{'id'})) { 
                   13656: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   13657: 		    }
1.599     albertel 13658: 		    if ($metaentry{':packages'}) {
                   13659: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 13660: 		    } else {
1.599     albertel 13661: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 13662: 		    }
1.736     albertel 13663: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 13664: 			my $part=$keyroot;
                   13665: 			$part=~s/^\_//;
1.736     albertel 13666: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   13667: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   13668: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 13669: 			    # ignore package.tab specified default values
                   13670:                             # here &package_tab_default() will fetch those
                   13671: 			    if ($subp eq 'default') { next; }
1.736     albertel 13672: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 13673: 			    my $unikey;
                   13674: 			    if ($pack =~ /_0$/) {
                   13675: 				$unikey='parameter_0_'.$name;
                   13676: 				$part=0;
                   13677: 			    } else {
                   13678: 				$unikey='parameter'.$keyroot.'_'.$name;
                   13679: 			    }
1.339     albertel 13680: 			    if ($subp eq 'display') {
                   13681: 				$value.=' [Part: '.$part.']';
                   13682: 			    }
1.599     albertel 13683: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 13684: 			    $metathesekeys{$unikey}=1;
1.599     albertel 13685: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13686: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 13687: 			    }
1.599     albertel 13688: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   13689: 				$metaentry{':'.$unikey}=
                   13690: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 13691: 			    }
1.339     albertel 13692: 			}
                   13693: 		    }
                   13694: 		} else {
1.172     www      13695: #
                   13696: # This is not a package - some other kind of start tag
1.339     albertel 13697: #
                   13698: 		    my $entry=$token->[1];
1.1068    www      13699: 		    my $unikey='';
1.175     www      13700: 
1.339     albertel 13701: 		    if ($entry eq 'import') {
1.175     www      13702: #
                   13703: # Importing a library here
1.339     albertel 13704: #
1.1067    www      13705:                         my $location=$parser->get_text('/import');
                   13706:                         my $dir=$filename;
                   13707:                         $dir=~s|[^/]*$||;
                   13708:                         $location=&filelocation($dir,$location);
1.1369    raeburn  13709: 
                   13710:                         my $importid=$token->[2]->{'id'};
1.1068    www      13711:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  13712: #
                   13713: # Check metadata for imported file to
                   13714: # see if it contained response items
                   13715: #
1.1372    raeburn  13716:                         my ($origfile,@libfilekeys);
1.1370    raeburn  13717:                         my %currmetaentry = %metaentry;
1.1372    raeburn  13718:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   13719:                                                            $depthcount+1));
                   13720:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   13721:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   13722:                                                              undef,$depthcount+1);
                   13723:                             if ($libresponseorder ne '') {
                   13724:                                 if ($#origfiletagids<0) {
                   13725:                                     undef(%importedrespids);
                   13726:                                     undef(%importedpartids);
                   13727:                                 }
1.1373    raeburn  13728:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   13729:                                 if (@respids) {
                   13730:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   13731:                                 }
                   13732:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  13733:                                     $importedresponses = 1;
1.1369    raeburn  13734: # We need to get the original file and the imported file to get the response order correct
                   13735: # Load and inspect original file
1.1372    raeburn  13736:                                     if ($#origfiletagids<0) {
                   13737:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13738:                                         $origfile=&getfile($origfilelocation);
                   13739:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13740:                                     }
1.1369    raeburn  13741:                                 }
                   13742:                             }
                   13743:                         }
1.1370    raeburn  13744: # Do not overwrite contents of %metaentry hash for resource itself with 
                   13745: # hash populated for imported library file
                   13746:                         %metaentry = %currmetaentry;
                   13747:                         undef(%currmetaentry);
1.1374    raeburn  13748:                         if ($importmode eq 'part') {
1.1068    www      13749: # Import as part(s)
1.1069    www      13750:                            $importedparts=1;
                   13751: # We need to get the original file and the imported file to get the part order correct
                   13752: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  13753: # Load and inspect original file if we didn't do that already
                   13754:                            if ($#origfiletagids<0) {
                   13755:                                undef(%importedrespids);
                   13756:                                undef(%importedpartids);
                   13757:                                if ($origfile eq '') {
                   13758:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13759:                                    $origfile=&getfile($origfilelocation);
                   13760:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13761:                                }
1.1070    www      13762:                            }
1.1372    raeburn  13763:                            my @impfilepartids;
                   13764: # If <partorder> tag is included in metadata for the imported file
                   13765: # get the parts in the imported file from that.
                   13766:                            if (grep(/^partorder$/,@libfilekeys)) {
                   13767:                                %currmetaentry = %metaentry;
                   13768:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13769:                                                             $depthcount+1);
                   13770:                                %metaentry = %currmetaentry;
                   13771:                                undef(%currmetaentry);
                   13772:                                if ($libpartorder ne '') {
                   13773:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   13774:                                }
                   13775:                            } else {
                   13776: # If no <partorder> tag available, load and inspect imported file
                   13777:                                my $impfile=&getfile($location);
                   13778:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13779:                            }
1.1069    www      13780:                            if ($#impfilepartids>=0) {
                   13781: # This problem had parts
1.1070    www      13782:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      13783:                            } else {
                   13784: # Importing by turning a single problem into a problem part
                   13785: # It gets the import-tags ID as part-ID
                   13786:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      13787:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      13788:                            }
1.1068    www      13789:                         } else {
1.1374    raeburn  13790: # Import as problem or as normal import
                   13791:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13792:                             unless ($importmode eq 'problem') {
1.1068    www      13793: # Normal import
1.1374    raeburn  13794:                                 if (defined($token->[2]->{'id'})) {
                   13795:                                     $unikey.='_'.$token->[2]->{'id'};
                   13796:                                 }
                   13797:                             }
                   13798: # Check metadata for imported file to
                   13799: # see if it contained parts
                   13800:                             if (grep(/^partorder$/,@libfilekeys)) {
                   13801:                                 %currmetaentry = %metaentry;
                   13802:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13803:                                                              $depthcount+1);
                   13804:                                 %metaentry = %currmetaentry;
                   13805:                                 undef(%currmetaentry);
                   13806:                                 if ($libpartorder ne '') {
                   13807:                                     $importedparts = 1;
                   13808:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   13809:                                 }
                   13810:                             }
1.1067    www      13811:                         }
1.339     albertel 13812: 			if ($depthcount<20) {
1.736     albertel 13813: 			    my $metadata = 
1.1362    raeburn  13814: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 13815: 					  $depthcount+1);
                   13816: 			    foreach my $meta (split(',',$metadata)) {
                   13817: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   13818: 				$metathesekeys{$meta}=1;
1.339     albertel 13819: 			    }
1.1068    www      13820:                         }
1.1067    www      13821: 		    } else {
                   13822: #
                   13823: # Not importing, some other kind of non-package, non-library start tag
                   13824: # 
                   13825:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13826:                         if (defined($token->[2]->{'id'})) {
                   13827:                             $unikey.='_'.$token->[2]->{'id'};
                   13828:                         }
1.339     albertel 13829: 			if (defined($token->[2]->{'name'})) { 
                   13830: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13831: 			}
                   13832: 			$metathesekeys{$unikey}=1;
1.736     albertel 13833: 			foreach my $param (@{$token->[3]}) {
                   13834: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13835: 				$token->[2]->{$param};
1.339     albertel 13836: 			}
                   13837: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13838: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13839: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13840: 		 # only ws inside the tag, and not in default, so use default
                   13841: 		 # as value
1.599     albertel 13842: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13843: 			} elsif ( $internaltext =~ /\S/ ) {
                   13844: 		  # something interesting inside the tag
                   13845: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13846: 			} else {
1.908     albertel 13847: 		  # no interesting values, don't set a default
1.339     albertel 13848: 			}
1.172     www      13849: # end of not-a-package not-a-library import
1.339     albertel 13850: 		    }
1.172     www      13851: # end of not-a-package start tag
1.339     albertel 13852: 		}
1.172     www      13853: # the next is the end of "start tag"
1.339     albertel 13854: 	    }
                   13855: 	}
1.483     albertel 13856: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13857: 	$extension = lc($extension);
                   13858: 	if ($extension eq 'htm') { $extension='html'; }
                   13859: 
1.737     albertel 13860: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13861: 	    #no specific packages #how's our extension
                   13862: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13863: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13864: 					 \%metathesekeys);
                   13865: 	}
1.883     albertel 13866: 
                   13867: 	if (!exists($metaentry{':packages'})
                   13868: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13869: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13870: 		#no specific packages well let's get default then
                   13871: 		if ($key!~/^default&/) { next; }
1.488     albertel 13872: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13873: 					     \%metathesekeys);
                   13874: 	    }
                   13875: 	}
1.338     www      13876: # are there custom rights to evaluate
1.599     albertel 13877: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13878: 
1.338     www      13879:     #
                   13880:     # Importing a rights file here
1.339     albertel 13881:     #
                   13882: 	    unless ($depthcount) {
1.599     albertel 13883: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13884: 		my $dir=$filename;
                   13885: 		$dir=~s|[^/]*$||;
                   13886: 		$location=&filelocation($dir,$location);
1.736     albertel 13887: 		my $rights_metadata =
1.1362    raeburn  13888: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13889: 			      $depthcount+1);
                   13890: 		foreach my $rights (split(',',$rights_metadata)) {
                   13891: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13892: 		    $metathesekeys{$rights}=1;
1.339     albertel 13893: 		}
                   13894: 	    }
                   13895: 	}
1.737     albertel 13896: 	# uniqifiy package listing
                   13897: 	my %seen;
                   13898: 	my @uniq_packages =
                   13899: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   13900: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   13901: 
1.1369    raeburn  13902:         if (($importedresponses) || ($importedparts)) {
                   13903:             if ($importedparts) {
1.1070    www      13904: # We had imported parts and need to rebuild partorder
1.1369    raeburn  13905:                 $metaentry{':partorder'}='';
                   13906:                 $metathesekeys{'partorder'}=1;
                   13907:             }
                   13908:             if ($importedresponses) {
                   13909: # We had imported responses and need to rebuil responseorder
                   13910:                 $metaentry{':responseorder'}='';
                   13911:                 $metathesekeys{'responseorder'}=1;
                   13912:             }
                   13913:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   13914:                 my $origid = $origfiletagids[$index+1];
                   13915:                 if ($origfiletagids[$index] eq 'part') {
                   13916: # Original part, part of the problem
                   13917:                     if ($importedparts) {
                   13918:                         $metaentry{':partorder'}.=','.$origid;
                   13919:                     }
                   13920:                 } elsif ($origfiletagids[$index] eq 'import') {
                   13921:                     if ($importedparts) {
                   13922: # We have imported parts at this position
1.1373    raeburn  13923:                         if ($importedpartids{$origid} ne '') {
                   13924:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   13925:                         }
1.1369    raeburn  13926:                     }
                   13927:                     if ($importedresponses) {
                   13928: # We have imported responses at this position
1.1373    raeburn  13929:                         if ($importedrespids{$origid} ne '') {
                   13930:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  13931:                         }
                   13932:                     }
                   13933:                 } else {
                   13934: # Original response item, part of the problem
                   13935:                     if ($importedresponses) {
                   13936:                         $metaentry{':responseorder'}.=','.$origid;
                   13937:                     }
                   13938:                 }
                   13939:             }
                   13940:             if ($importedparts) {
                   13941:                 $metaentry{':partorder'}=~s/^\,//;
                   13942:             }
                   13943:             if ($importedresponses) {
                   13944:                 $metaentry{':responseorder'}=~s/^\,//;
                   13945:             }
1.1070    www      13946:         }
1.737     albertel 13947: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13948: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  13949: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  13950:         unless ($liburi) {
                   13951: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   13952:         }
1.177     www      13953: # this is the end of "was not already recently cached
1.71      www      13954:     }
1.599     albertel 13955:     return $metaentry{':'.$what};
1.261     albertel 13956: }
                   13957: 
1.488     albertel 13958: sub metadata_create_package_def {
1.483     albertel 13959:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13960:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13961:     if ($subp eq 'default') { next; }
                   13962:     
1.599     albertel 13963:     if (defined($metaentry{':packages'})) {
                   13964: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13965:     } else {
1.599     albertel 13966: 	$metaentry{':packages'}=$package;
1.483     albertel 13967:     }
                   13968:     my $value=$packagetab{$key};
                   13969:     my $unikey;
                   13970:     $unikey='parameter_0_'.$name;
1.599     albertel 13971:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13972:     $$metathesekeys{$unikey}=1;
1.599     albertel 13973:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13974: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13975:     }
1.599     albertel 13976:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13977: 	$metaentry{':'.$unikey}=
                   13978: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13979:     }
                   13980: }
                   13981: 
1.261     albertel 13982: sub metadata_generate_part0 {
                   13983:     my ($metadata,$metacache,$uri) = @_;
                   13984:     my %allnames;
1.737     albertel 13985:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13986: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13987: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13988: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13989: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13990: 	    $allnames{$name}=$part;
                   13991: 	  }
                   13992: 	}
                   13993:     }
                   13994:     foreach my $name (keys(%allnames)) {
                   13995:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13996:       my $key=":parameter_0_$name";
1.261     albertel 13997:       $$metacache{"$key.part"}='0';
                   13998:       $$metacache{"$key.name"}=$name;
1.428     albertel 13999:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 14000: 					   $allnames{$name}.'_'.$name.
                   14001: 					   '.type'};
1.428     albertel 14002:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 14003: 			     '.display'};
1.644     www      14004:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 14005:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 14006:       $$metacache{"$key.display"}=$olddis;
                   14007:     }
1.71      www      14008: }
                   14009: 
1.764     albertel 14010: # ------------------------------------------------------ Devalidate title cache
                   14011: 
                   14012: sub devalidate_title_cache {
                   14013:     my ($url)=@_;
                   14014:     if (!$env{'request.course.id'}) { return; }
                   14015:     my $symb=&symbread($url);
                   14016:     if (!$symb) { return; }
                   14017:     my $key=$env{'request.course.id'}."\0".$symb;
                   14018:     &devalidate_cache_new('title',$key);
                   14019: }
                   14020: 
1.1014    droeschl 14021: # ------------------------------------------------- Get the title of a course
                   14022: 
                   14023: sub current_course_title {
                   14024:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   14025: }
1.301     www      14026: # ------------------------------------------------- Get the title of a resource
                   14027: 
                   14028: sub gettitle {
                   14029:     my $urlsymb=shift;
                   14030:     my $symb=&symbread($urlsymb);
1.534     albertel 14031:     if ($symb) {
1.620     albertel 14032: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 14033: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 14034: 	if (defined($cached)) { 
                   14035: 	    return $result;
                   14036: 	}
1.534     albertel 14037: 	my ($map,$resid,$url)=&decode_symb($symb);
                   14038: 	my $title='';
1.907     albertel 14039: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   14040: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   14041: 	} else {
                   14042: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   14043: 		    &GDBM_READER(),0640)) {
                   14044: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   14045: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   14046: 		untie(%bighash);
                   14047: 	    }
1.534     albertel 14048: 	}
                   14049: 	$title=~s/\&colon\;/\:/gs;
                   14050: 	if ($title) {
1.1159    www      14051: # Remember both $symb and $title for dynamic metadata
                   14052:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      14053:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      14054: # Cache this title and then return it
1.599     albertel 14055: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 14056: 	}
                   14057: 	$urlsymb=$url;
                   14058:     }
                   14059:     my $title=&metadata($urlsymb,'title');
                   14060:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   14061:     return $title;
1.301     www      14062: }
1.613     albertel 14063: 
1.614     albertel 14064: sub get_slot {
                   14065:     my ($which,$cnum,$cdom)=@_;
                   14066:     if (!$cnum || !$cdom) {
1.790     albertel 14067: 	(undef,my $courseid)=&whichuser();
1.620     albertel 14068: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   14069: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 14070:     }
1.703     albertel 14071:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   14072:     my %slotinfo;
                   14073:     if (exists($remembered{$key})) {
                   14074: 	$slotinfo{$which} = $remembered{$key};
                   14075:     } else {
                   14076: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   14077: 	&Apache::lonhomework::showhash(%slotinfo);
                   14078: 	my ($tmp)=keys(%slotinfo);
                   14079: 	if ($tmp=~/^error:/) { return (); }
                   14080: 	$remembered{$key} = $slotinfo{$which};
                   14081:     }
1.616     albertel 14082:     if (ref($slotinfo{$which}) eq 'HASH') {
                   14083: 	return %{$slotinfo{$which}};
                   14084:     }
                   14085:     return $slotinfo{$which};
1.614     albertel 14086: }
1.1150    raeburn  14087: 
                   14088: sub get_reservable_slots {
                   14089:     my ($cnum,$cdom,$uname,$udom) = @_;
                   14090:     my $now = time;
                   14091:     my $reservable_info;
                   14092:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   14093:     if (exists($remembered{$key})) {
                   14094:         $reservable_info = $remembered{$key};
                   14095:     } else {
                   14096:         my %resv;
                   14097:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   14098:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   14099:         $reservable_info = \%resv;
                   14100:         $remembered{$key} = $reservable_info;
                   14101:     }
                   14102:     return $reservable_info;
                   14103: }
                   14104: 
                   14105: sub get_course_slots {
                   14106:     my ($cnum,$cdom) = @_;
                   14107:     my $hashid=$cnum.':'.$cdom;
1.1494    raeburn  14108:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
1.1150    raeburn  14109:     if (defined($cached)) {
                   14110:         if (ref($result) eq 'HASH') {
                   14111:             return %{$result};
                   14112:         }
                   14113:     } else {
1.1494    raeburn  14114:         my %slots=&dump('slots',$cdom,$cnum);
1.1150    raeburn  14115:         my ($tmp) = keys(%slots);
                   14116:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  14117:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  14118:             return %slots;
                   14119:         }
                   14120:     }
                   14121:     return;
                   14122: }
                   14123: 
                   14124: sub devalidate_slots_cache {
                   14125:     my ($cnum,$cdom)=@_;
                   14126:     my $hashid=$cnum.':'.$cdom;
                   14127:     &devalidate_cache_new('allslots',$hashid);
                   14128: }
                   14129: 
1.1181    raeburn  14130: sub get_coursechange {
                   14131:     my ($cdom,$cnum) = @_;
                   14132:     if ($cdom eq '' || $cnum eq '') {
                   14133:         return unless ($env{'request.course.id'});
                   14134:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   14135:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   14136:     }
                   14137:     my $hashid=$cdom.'_'.$cnum;
                   14138:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   14139:     if ((defined($cached)) && ($change ne '')) {
                   14140:         return $change;
                   14141:     } else {
                   14142:         my %crshash;
                   14143:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   14144:         if ($crshash{'internal.contentchange'} eq '') {
                   14145:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   14146:             if ($change eq '') {
                   14147:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   14148:                 $change = $crshash{'internal.created'};
                   14149:             }
                   14150:         } else {
                   14151:             $change = $crshash{'internal.contentchange'};
                   14152:         }
                   14153:         my $cachetime = 600;
                   14154:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   14155:     }
                   14156:     return $change;
                   14157: }
                   14158: 
                   14159: sub devalidate_coursechange_cache {
1.1496    raeburn  14160:     my ($cdom,$cnum)=@_;
                   14161:     my $hashid=$cdom.'_'.$cnum;
1.1181    raeburn  14162:     &devalidate_cache_new('crschange',$hashid);
                   14163: }
                   14164: 
1.1496    raeburn  14165: sub get_suppchange {
                   14166:     my ($cdom,$cnum) = @_;
                   14167:     if ($cdom eq '' || $cnum eq '') {
                   14168:         return unless ($env{'request.course.id'});
                   14169:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   14170:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   14171:     }
                   14172:     my $hashid=$cdom.'_'.$cnum;
                   14173:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   14174:     if ((defined($cached)) && ($change ne '')) {
                   14175:         return $change;
                   14176:     } else {
                   14177:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   14178:         if ($crshash{'internal.supplementalchange'} eq '') {
                   14179:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   14180:             if ($change eq '') {
                   14181:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   14182:                 $change = $crshash{'internal.created'};
                   14183:             }
                   14184:         } else {
                   14185:             $change = $crshash{'internal.supplementalchange'};
                   14186:         }
                   14187:         my $cachetime = 600;
                   14188:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   14189:     }
                   14190:     return $change;
                   14191: }
                   14192: 
                   14193: sub devalidate_suppchange_cache {
                   14194:     my ($cdom,$cnum)=@_;
                   14195:     my $hashid=$cdom.'_'.$cnum;
                   14196:     &devalidate_cache_new('suppchange',$hashid);
                   14197: }
                   14198: 
1.1497    raeburn  14199: sub update_supp_caches {
                   14200:     my ($cdom,$cnum) = @_;
                   14201:     my %servers = &internet_dom_servers($cdom);
                   14202:     my @ids=&current_machine_ids();
                   14203:     foreach my $server (keys(%servers)) {
                   14204:         next if (grep(/^\Q$server\E$/,@ids));
                   14205:         my $hashid=$cnum.':'.$cdom;
                   14206:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   14207:         &remote_devalidate_cache($server,[$cachekey]);
                   14208:     }
                   14209:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   14210:     &count_supptools($cnum,$cdom,1);
                   14211:     my $now = time;
                   14212:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   14213:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   14214:     }
                   14215:     &put('environment',{'internal.supplementalchange' => $now},
                   14216:          $cdom,$cnum);
                   14217:     &Apache::lonnet::appenv(
                   14218:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   14219:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   14220: }
                   14221: 
1.31      www      14222: # ------------------------------------------------- Update symbolic store links
                   14223: 
                   14224: sub symblist {
                   14225:     my ($mapname,%newhash)=@_;
1.438     www      14226:     $mapname=&deversion(&declutter($mapname));
1.31      www      14227:     my %hash;
1.620     albertel 14228:     if (($env{'request.course.fn'}) && (%newhash)) {
                   14229:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 14230:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  14231: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 14232: 		next if ($url eq 'last_known'
                   14233: 			 && $env{'form.no_update_last_known'});
                   14234: 		$hash{declutter($url)}=&encode_symb($mapname,
                   14235: 						    $newhash{$url}->[1],
                   14236: 						    $newhash{$url}->[0]);
1.191     harris41 14237:             }
1.31      www      14238:             if (untie(%hash)) {
                   14239: 		return 'ok';
                   14240:             }
                   14241:         }
                   14242:     }
                   14243:     return 'error';
1.212     www      14244: }
                   14245: 
                   14246: # --------------------------------------------------------------- Verify a symb
                   14247: 
                   14248: sub symbverify {
1.1190    raeburn  14249:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      14250:     my $thisfn=$thisurl;
1.439     www      14251:     $thisfn=&declutter($thisfn);
1.215     www      14252: # direct jump to resource in page or to a sequence - will construct own symbs
                   14253:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   14254: # check URL part
1.409     www      14255:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      14256: 
1.431     www      14257:     unless ($url eq $thisfn) { return 0; }
1.213     www      14258: 
1.216     www      14259:     $symb=&symbclean($symb);
1.510     www      14260:     $thisurl=&deversion($thisurl);
1.439     www      14261:     $thisfn=&deversion($thisfn);
1.213     www      14262: 
                   14263:     my %bighash;
                   14264:     my $okay=0;
1.431     www      14265: 
1.620     albertel 14266:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 14267:                             &GDBM_READER(),0640)) {
1.1032    raeburn  14268:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   14269:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  14270:             if ($map =~ m{^uploaded/.+\.page$}) {
                   14271:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   14272:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   14273:             }
                   14274:         }
                   14275:         my $ids;
1.1419    raeburn  14276:         if ($map =~ m{^uploaded/.+\.page$}) {
                   14277:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  14278:         } else {
                   14279:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  14280:         }
1.1102    raeburn  14281:         unless ($ids) {
                   14282:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   14283:             $ids=$bighash{$idkey};
1.216     www      14284:         }
                   14285:         if ($ids) {
                   14286: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  14287:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  14288:                 $symb =~ s/\?.+$//;
1.1202    raeburn  14289:             }
1.800     albertel 14290: 	    foreach my $id (split(/\,/,$ids)) {
                   14291: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      14292:                if (
                   14293:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  14294:    eq $symb) {
                   14295:                    if (ref($encstate)) {
                   14296:                        $$encstate = $bighash{'encrypted_'.$id};
                   14297:                    }
1.620     albertel 14298: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  14299: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   14300:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  14301: 		       $okay=1;
1.1202    raeburn  14302:                        last;
1.582     albertel 14303: 		   }
                   14304: 	       }
1.216     www      14305: 	   }
                   14306:         }
1.213     www      14307: 	untie(%bighash);
                   14308:     }
                   14309:     return $okay;
1.31      www      14310: }
                   14311: 
1.210     www      14312: # --------------------------------------------------------------- Clean-up symb
                   14313: 
                   14314: sub symbclean {
                   14315:     my $symb=shift;
1.568     albertel 14316:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      14317: # remove version from map
                   14318:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      14319: 
1.210     www      14320: # remove version from URL
                   14321:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      14322: 
1.507     www      14323: # remove wrapper
                   14324: 
1.510     www      14325:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 14326:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      14327:     return $symb;
1.409     www      14328: }
                   14329: 
                   14330: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 14331: 
                   14332: sub encode_symb {
                   14333:     my ($map,$resid,$url)=@_;
                   14334:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   14335: }
1.409     www      14336: 
                   14337: sub decode_symb {
1.568     albertel 14338:     my $symb=shift;
                   14339:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   14340:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      14341:     return (&fixversion($map),$resid,&fixversion($url));
                   14342: }
                   14343: 
                   14344: sub fixversion {
                   14345:     my $fn=shift;
1.609     banghart 14346:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      14347:     my %bighash;
                   14348:     my $uri=&clutter($fn);
1.620     albertel 14349:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      14350: # is this cached?
1.599     albertel 14351:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      14352:     if (defined($cached)) { return $result; }
                   14353: # unfortunately not cached, or expired
1.620     albertel 14354:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      14355: 	    &GDBM_READER(),0640)) {
                   14356:  	if ($bighash{'version_'.$uri}) {
                   14357:  	    my $version=$bighash{'version_'.$uri};
1.444     www      14358:  	    unless (($version eq 'mostrecent') || 
                   14359: 		    ($version==&getversion($uri))) {
1.440     www      14360:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   14361:  	    }
                   14362:  	}
                   14363:  	untie %bighash;
1.413     www      14364:     }
1.599     albertel 14365:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      14366: }
                   14367: 
                   14368: sub deversion {
                   14369:     my $url=shift;
                   14370:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   14371:     return $url;
1.210     www      14372: }
                   14373: 
1.31      www      14374: # ------------------------------------------------------ Return symb list entry
                   14375: 
                   14376: sub symbread {
1.1424    raeburn  14377:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  14378:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  14379:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  14380:     if (defined($env{$cache_str})) {
1.1424    raeburn  14381:         unless (ref($possibles) eq 'HASH') {
                   14382:             if ($ignorecachednull) {
                   14383:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   14384:             } else {
                   14385:                 return $env{$cache_str};
                   14386:             }
1.1282    raeburn  14387:         }
                   14388:     }
1.242     www      14389: # no filename provided? try from environment
1.1265    raeburn  14390:     unless ($thisfn) {
1.620     albertel 14391:         if ($env{'request.symb'}) {
1.1427    raeburn  14392:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 14393: 	}
1.620     albertel 14394: 	$thisfn=$env{'request.filename'};
1.44      www      14395:     }
1.569     albertel 14396:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      14397: # is that filename actually a symb? Verify, clean, and return
                   14398:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 14399: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  14400: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 14401: 	}
1.242     www      14402:     }
1.44      www      14403:     $thisfn=declutter($thisfn);
1.31      www      14404:     my %hash;
1.37      www      14405:     my %bighash;
                   14406:     my $syval='';
1.620     albertel 14407:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427    raeburn  14408:         unless ($ignoresymbdb) {
1.1424    raeburn  14409:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   14410:                           &GDBM_READER(),0640)) {
1.1487    raeburn  14411: 	        $syval=$hash{$thisfn};
1.1424    raeburn  14412:                 untie(%hash);
                   14413:             }
1.1427    raeburn  14414:             if ($syval && $checkforblock) {
                   14415:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  14416:                 if (@blockers) {
                   14417:                     $syval='';
                   14418:                 }
                   14419:             }
1.37      www      14420:         }
                   14421: # ---------------------------------------------------------- There was an entry
                   14422:         if ($syval) {
1.601     albertel 14423: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 14424: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  14425: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 14426: 		    #return $env{$cache_str}='';
1.601     albertel 14427: 		#}    
                   14428: 		#$syval.=$1;
                   14429: 	    #}
1.37      www      14430:         } else {
                   14431: # ------------------------------------------------------- Was not in symb table
1.620     albertel 14432:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 14433:                             &GDBM_READER(),0640)) {
1.37      www      14434: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      14435:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      14436:               unless ($ids) { 
                   14437:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      14438:               }
                   14439:               unless ($ids) {
                   14440: # alias?
                   14441: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      14442:               }
1.37      www      14443:               if ($ids) {
                   14444: # ------------------------------------------------------------------- Has ID(s)
                   14445:                  my @possibilities=split(/\,/,$ids);
1.39      www      14446:                  if ($#possibilities==0) {
                   14447: # ----------------------------------------------- There is only one possibility
1.37      www      14448: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 14449: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   14450: 						    $resid,$thisfn);
1.1282    raeburn  14451:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  14452:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   14453:                              $possibles->{$syval} = 1;
                   14454:                          }
1.1282    raeburn  14455:                      }
                   14456:                      if ($checkforblock) {
1.1424    raeburn  14457:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  14458:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  14459:                              if (@blockers) {
                   14460:                                  $syval = '';
1.1425    raeburn  14461:                                  untie(%bighash);
                   14462:                                  return $env{$cache_str}='';
1.1424    raeburn  14463:                              }
1.1282    raeburn  14464:                          }
                   14465:                      }
                   14466:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      14467: # ------------------------------------------ There is more than one possibility
                   14468:                      my $realpossible=0;
1.800     albertel 14469:                      foreach my $id (@possibilities) {
                   14470: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  14471:                          my $canaccess;
                   14472:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   14473:                              $canaccess = 1;
                   14474:                          } else { 
                   14475:                              $canaccess = &allowed('bre',$file);
                   14476:                          }
                   14477:                          if ($canaccess) {
                   14478:          		     my ($mapid,$resid)=split(/\./,$id);
                   14479:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   14480:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   14481: 						             $resid,$thisfn);
1.1424    raeburn  14482:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  14483:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  14484:                                  if ($checkforblock) {
1.1426    raeburn  14485:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  14486:                                      if (@blockers > 0) {
                   14487:                                          $syval = '';
                   14488:                                      } else {
1.1282    raeburn  14489:                                          $syval = $poss_syval;
                   14490:                                          $realpossible++;
                   14491:                                      }
                   14492:                                  } else {
                   14493:                                      $syval = $poss_syval;
                   14494:                                      $realpossible++;
                   14495:                                  }
1.1424    raeburn  14496:                                  if ($syval) {
                   14497:                                      if (ref($possibles) eq 'HASH') {
                   14498:                                          $possibles->{$syval} = 1;
                   14499:                                      }
                   14500:                                  }
1.1282    raeburn  14501:                              }
1.39      www      14502: 			 }
1.191     harris41 14503:                      }
1.39      www      14504: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      14505:                  } else {
                   14506:                      $syval='';
1.37      www      14507:                  }
                   14508: 	      }
1.1282    raeburn  14509:               untie(%bighash);
1.481     raeburn  14510:            }
1.31      www      14511:         }
1.62      www      14512:         if ($syval) {
1.1427    raeburn  14513: 	    return $env{$cache_str}=$syval;
1.62      www      14514:         }
1.31      www      14515:     }
1.949     raeburn  14516:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 14517:     return $env{$cache_str}='';
1.31      www      14518: }
                   14519: 
                   14520: # ---------------------------------------------------------- Return random seed
                   14521: 
1.32      www      14522: sub numval {
                   14523:     my $txt=shift;
                   14524:     $txt=~tr/A-J/0-9/;
                   14525:     $txt=~tr/a-j/0-9/;
                   14526:     $txt=~tr/K-T/0-9/;
                   14527:     $txt=~tr/k-t/0-9/;
                   14528:     $txt=~tr/U-Z/0-5/;
                   14529:     $txt=~tr/u-z/0-5/;
                   14530:     $txt=~s/\D//g;
1.564     albertel 14531:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      14532:     return int($txt);
1.368     albertel 14533: }
                   14534: 
1.484     albertel 14535: sub numval2 {
                   14536:     my $txt=shift;
                   14537:     $txt=~tr/A-J/0-9/;
                   14538:     $txt=~tr/a-j/0-9/;
                   14539:     $txt=~tr/K-T/0-9/;
                   14540:     $txt=~tr/k-t/0-9/;
                   14541:     $txt=~tr/U-Z/0-5/;
                   14542:     $txt=~tr/u-z/0-5/;
                   14543:     $txt=~s/\D//g;
                   14544:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   14545:     my $total;
                   14546:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 14547:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 14548:     return int($total);
                   14549: }
                   14550: 
1.575     albertel 14551: sub numval3 {
                   14552:     use integer;
                   14553:     my $txt=shift;
                   14554:     $txt=~tr/A-J/0-9/;
                   14555:     $txt=~tr/a-j/0-9/;
                   14556:     $txt=~tr/K-T/0-9/;
                   14557:     $txt=~tr/k-t/0-9/;
                   14558:     $txt=~tr/U-Z/0-5/;
                   14559:     $txt=~tr/u-z/0-5/;
                   14560:     $txt=~s/\D//g;
                   14561:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   14562:     my $total;
                   14563:     foreach my $val (@txts) { $total+=$val; }
                   14564:     if ($_64bit) { $total=(($total<<32)>>32); }
                   14565:     return $total;
                   14566: }
                   14567: 
1.675     albertel 14568: sub digest {
                   14569:     my ($data)=@_;
                   14570:     my $digest=&Digest::MD5::md5($data);
                   14571:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   14572:     my ($e,$f);
                   14573:     {
                   14574:         use integer;
                   14575:         $e=($a+$b);
                   14576:         $f=($c+$d);
                   14577:         if ($_64bit) {
                   14578:             $e=(($e<<32)>>32);
                   14579:             $f=(($f<<32)>>32);
                   14580:         }
                   14581:     }
                   14582:     if (wantarray) {
                   14583: 	return ($e,$f);
                   14584:     } else {
                   14585: 	my $g;
                   14586: 	{
                   14587: 	    use integer;
                   14588: 	    $g=($e+$f);
                   14589: 	    if ($_64bit) {
                   14590: 		$g=(($g<<32)>>32);
                   14591: 	    }
                   14592: 	}
                   14593: 	return $g;
                   14594:     }
                   14595: }
                   14596: 
1.368     albertel 14597: sub latest_rnd_algorithm_id {
1.675     albertel 14598:     return '64bit5';
1.366     albertel 14599: }
1.32      www      14600: 
1.503     albertel 14601: sub get_rand_alg {
                   14602:     my ($courseid)=@_;
1.790     albertel 14603:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 14604:     if ($courseid) {
1.620     albertel 14605: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 14606:     }
                   14607:     return &latest_rnd_algorithm_id();
                   14608: }
                   14609: 
1.562     albertel 14610: sub validCODE {
                   14611:     my ($CODE)=@_;
                   14612:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   14613:     return 0;
                   14614: }
                   14615: 
1.491     albertel 14616: sub getCODE {
1.620     albertel 14617:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 14618:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   14619: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   14620: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 14621: 	return $Apache::lonhomework::history{'resource.CODE'};
                   14622:     }
                   14623:     return undef;
                   14624: }
1.1133    foxr     14625: #
                   14626: #  Determines the random seed for a specific context:
                   14627: #
                   14628: # parameters:
                   14629: #   symb      - in course context the symb for the seed.
                   14630: #   course_id - The course id of the form domain_coursenum.
                   14631: #   domain    - Domain for the user.
                   14632: #   course    - Course for the user.
                   14633: #   cenv      - environment of the course.
                   14634: #
                   14635: # NOTE:
                   14636: #   All parameters are picked out of the environment if missing
                   14637: #   or not defined.
                   14638: #   If a symb cannot be determined the current time is used instead.
                   14639: #
                   14640: #  For a given well defined symb, courside, domain, username,
                   14641: #  and course environment, the seed is reproducible.
                   14642: #
1.31      www      14643: sub rndseed {
1.1133    foxr     14644:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 14645:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 14646:     if (!defined($symb)) {
1.366     albertel 14647: 	unless ($symb=$wsymb) { return time; }
                   14648:     }
1.1146    foxr     14649:     if (!defined $courseid) { 
                   14650: 	$courseid=$wcourseid; 
                   14651:     }
                   14652:     if (!defined $domain) { $domain=$wdomain; }
                   14653:     if (!defined $username) { $username=$wusername }
1.1133    foxr     14654: 
                   14655:     my $which;
                   14656:     if (defined($cenv->{'rndseed'})) {
                   14657: 	$which = $cenv->{'rndseed'};
                   14658:     } else {
                   14659: 	$which =&get_rand_alg($courseid);
                   14660:     }
1.491     albertel 14661:     if (defined(&getCODE())) {
1.1133    foxr     14662: 
1.675     albertel 14663: 	if ($which eq '64bit5') {
                   14664: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   14665: 	} elsif ($which eq '64bit4') {
1.575     albertel 14666: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   14667: 	} else {
                   14668: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   14669: 	}
1.675     albertel 14670:     } elsif ($which eq '64bit5') {
                   14671: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 14672:     } elsif ($which eq '64bit4') {
                   14673: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 14674:     } elsif ($which eq '64bit3') {
                   14675: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 14676:     } elsif ($which eq '64bit2') {
                   14677: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 14678:     } elsif ($which eq '64bit') {
                   14679: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   14680:     }
                   14681:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   14682: }
                   14683: 
                   14684: sub rndseed_32bit {
                   14685:     my ($symb,$courseid,$domain,$username)=@_;
                   14686:     {
                   14687: 	use integer;
                   14688: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   14689: 	my $symbseed=numval($symb) << 22;
                   14690: 	my $namechck=unpack("%32C*",$username) << 17;
                   14691: 	my $nameseed=numval($username) << 12;
                   14692: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   14693: 	my $courseseed=unpack("%32C*",$courseid);
                   14694: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 14695: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14696: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14697: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 14698: 	return $num;
                   14699:     }
                   14700: }
                   14701: 
                   14702: sub rndseed_64bit {
                   14703:     my ($symb,$courseid,$domain,$username)=@_;
                   14704:     {
                   14705: 	use integer;
                   14706: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   14707: 	my $symbseed=numval($symb) << 10;
                   14708: 	my $namechck=unpack("%32S*",$username);
                   14709: 	
                   14710: 	my $nameseed=numval($username) << 21;
                   14711: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   14712: 	my $courseseed=unpack("%32S*",$courseid);
                   14713: 	
                   14714: 	my $num1=$symbchck+$symbseed+$namechck;
                   14715: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14716: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14717: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14718: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 14719: 	return "$num1,$num2";
1.155     albertel 14720:     }
1.366     albertel 14721: }
                   14722: 
1.443     albertel 14723: sub rndseed_64bit2 {
                   14724:     my ($symb,$courseid,$domain,$username)=@_;
                   14725:     {
                   14726: 	use integer;
                   14727: 	# strings need to be an even # of cahracters long, it it is odd the
                   14728:         # last characters gets thrown away
                   14729: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14730: 	my $symbseed=numval($symb) << 10;
                   14731: 	my $namechck=unpack("%32S*",$username.' ');
                   14732: 	
                   14733: 	my $nameseed=numval($username) << 21;
1.501     albertel 14734: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14735: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14736: 	
                   14737: 	my $num1=$symbchck+$symbseed+$namechck;
                   14738: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14739: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14740: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 14741: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 14742: 	return "$num1,$num2";
                   14743:     }
                   14744: }
                   14745: 
                   14746: sub rndseed_64bit3 {
                   14747:     my ($symb,$courseid,$domain,$username)=@_;
                   14748:     {
                   14749: 	use integer;
                   14750: 	# strings need to be an even # of cahracters long, it it is odd the
                   14751:         # last characters gets thrown away
                   14752: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14753: 	my $symbseed=numval2($symb) << 10;
                   14754: 	my $namechck=unpack("%32S*",$username.' ');
                   14755: 	
                   14756: 	my $nameseed=numval2($username) << 21;
1.443     albertel 14757: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14758: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14759: 	
                   14760: 	my $num1=$symbchck+$symbseed+$namechck;
                   14761: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14762: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14763: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 14764: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14765: 	
1.503     albertel 14766: 	return "$num1:$num2";
1.443     albertel 14767:     }
                   14768: }
                   14769: 
1.575     albertel 14770: sub rndseed_64bit4 {
                   14771:     my ($symb,$courseid,$domain,$username)=@_;
                   14772:     {
                   14773: 	use integer;
                   14774: 	# strings need to be an even # of cahracters long, it it is odd the
                   14775:         # last characters gets thrown away
                   14776: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14777: 	my $symbseed=numval3($symb) << 10;
                   14778: 	my $namechck=unpack("%32S*",$username.' ');
                   14779: 	
                   14780: 	my $nameseed=numval3($username) << 21;
                   14781: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14782: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14783: 	
                   14784: 	my $num1=$symbchck+$symbseed+$namechck;
                   14785: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14786: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14787: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 14788: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14789: 	
1.575     albertel 14790: 	return "$num1:$num2";
                   14791:     }
                   14792: }
                   14793: 
1.675     albertel 14794: sub rndseed_64bit5 {
                   14795:     my ($symb,$courseid,$domain,$username)=@_;
                   14796:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   14797:     return "$num1:$num2";
                   14798: }
                   14799: 
1.366     albertel 14800: sub rndseed_CODE_64bit {
                   14801:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 14802:     {
1.366     albertel 14803: 	use integer;
1.443     albertel 14804: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 14805: 	my $symbseed=numval2($symb);
1.491     albertel 14806: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14807: 	my $CODEseed=numval(&getCODE());
1.443     albertel 14808: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 14809: 	my $num1=$symbseed+$CODEchck;
                   14810: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14811: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14812: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 14813: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14814: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 14815: 	return "$num1:$num2";
1.366     albertel 14816:     }
                   14817: }
                   14818: 
1.575     albertel 14819: sub rndseed_CODE_64bit4 {
                   14820:     my ($symb,$courseid,$domain,$username)=@_;
                   14821:     {
                   14822: 	use integer;
                   14823: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   14824: 	my $symbseed=numval3($symb);
                   14825: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14826: 	my $CODEseed=numval3(&getCODE());
                   14827: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14828: 	my $num1=$symbseed+$CODEchck;
                   14829: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14830: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14831: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14832: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14833: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14834: 	return "$num1:$num2";
                   14835:     }
                   14836: }
                   14837: 
1.675     albertel 14838: sub rndseed_CODE_64bit5 {
                   14839:     my ($symb,$courseid,$domain,$username)=@_;
                   14840:     my $code = &getCODE();
                   14841:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14842:     return "$num1:$num2";
                   14843: }
                   14844: 
1.366     albertel 14845: sub setup_random_from_rndseed {
                   14846:     my ($rndseed)=@_;
1.503     albertel 14847:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  14848:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14849:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14850:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14851:         } else {
                   14852:             &Math::Random::random_set_seed($num1,$num2);
                   14853:         }
1.366     albertel 14854:     } else {
                   14855: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14856:     }
1.36      albertel 14857: }
                   14858: 
1.474     albertel 14859: sub latest_receipt_algorithm_id {
1.835     albertel 14860:     return 'receipt3';
1.474     albertel 14861: }
                   14862: 
1.480     www      14863: sub recunique {
                   14864:     my $fucourseid=shift;
                   14865:     my $unique;
1.835     albertel 14866:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14867: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14868: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14869:     } else {
                   14870: 	$unique=$perlvar{'lonReceipt'};
                   14871:     }
                   14872:     return unpack("%32C*",$unique);
                   14873: }
                   14874: 
                   14875: sub recprefix {
                   14876:     my $fucourseid=shift;
                   14877:     my $prefix;
1.835     albertel 14878:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14879: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14880: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14881:     } else {
                   14882: 	$prefix=$perlvar{'lonHostID'};
                   14883:     }
                   14884:     return unpack("%32C*",$prefix);
                   14885: }
                   14886: 
1.76      www      14887: sub ireceipt {
1.474     albertel 14888:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14889: 
                   14890:     my $return =&recprefix($fucourseid).'-';
                   14891: 
                   14892:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14893: 	$env{'request.state'} eq 'construct') {
                   14894: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   14895: 	return $return;
                   14896:     }
                   14897: 
1.76      www      14898:     my $cuname=unpack("%32C*",$funame);
                   14899:     my $cudom=unpack("%32C*",$fudom);
                   14900:     my $cucourseid=unpack("%32C*",$fucourseid);
                   14901:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      14902:     my $cunique=&recunique($fucourseid);
1.474     albertel 14903:     my $cpart=unpack("%32S*",$part);
1.835     albertel 14904:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   14905: 
1.790     albertel 14906: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 14907: 			       
                   14908: 	$return.= ($cunique%$cuname+
                   14909: 		   $cunique%$cudom+
                   14910: 		   $cusymb%$cuname+
                   14911: 		   $cusymb%$cudom+
                   14912: 		   $cucourseid%$cuname+
                   14913: 		   $cucourseid%$cudom+
                   14914: 		   $cpart%$cuname+
                   14915: 		   $cpart%$cudom);
                   14916:     } else {
                   14917: 	$return.= ($cunique%$cuname+
                   14918: 		   $cunique%$cudom+
                   14919: 		   $cusymb%$cuname+
                   14920: 		   $cusymb%$cudom+
                   14921: 		   $cucourseid%$cuname+
                   14922: 		   $cucourseid%$cudom);
                   14923:     }
                   14924:     return $return;
1.76      www      14925: }
                   14926: 
                   14927: sub receipt {
1.474     albertel 14928:     my ($part)=@_;
1.790     albertel 14929:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14930:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14931: }
1.260     ng       14932: 
1.790     albertel 14933: sub whichuser {
                   14934:     my ($passedsymb)=@_;
                   14935:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14936:     if (defined($env{'form.grade_symb'})) {
                   14937: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14938: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14939: 	if (!$allowed &&
                   14940: 	    exists($env{'request.course.sec'}) &&
                   14941: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14942: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14943: 			      '/'.$env{'request.course.sec'});
                   14944: 	}
                   14945: 	if ($allowed) {
                   14946: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14947: 	    $courseid=$tmp_courseid;
                   14948: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14949: 	    ($name)=&get_env_multiple('form.grade_username');
                   14950: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14951: 	}
                   14952:     }
                   14953:     if (!$passedsymb) {
                   14954: 	$symb=&symbread();
                   14955:     } else {
                   14956: 	$symb=$passedsymb;
                   14957:     }
                   14958:     $courseid=$env{'request.course.id'};
                   14959:     $domain=$env{'user.domain'};
                   14960:     $name=$env{'user.name'};
                   14961:     if ($name eq 'public' && $domain eq 'public') {
                   14962: 	if (!defined($env{'form.username'})) {
                   14963: 	    $env{'form.username'}.=time.rand(10000000);
                   14964: 	}
                   14965: 	$name.=$env{'form.username'};
                   14966:     }
                   14967:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14968: 
                   14969: }
                   14970: 
1.36      albertel 14971: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14972: # returns either the contents of the file or 
                   14973: # -1 if the file doesn't exist
1.481     raeburn  14974: #
                   14975: # if the target is a file that was uploaded via DOCS, 
                   14976: # a check will be made to see if a current copy exists on the local server,
                   14977: # if it does this will be served, otherwise a copy will be retrieved from
                   14978: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14979: # the local server.   
1.472     albertel 14980: 
1.36      albertel 14981: sub getfile {
1.538     albertel 14982:     my ($file) = @_;
1.609     banghart 14983:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14984:     &repcopy($file);
                   14985:     return &readfile($file);
                   14986: }
                   14987: 
                   14988: sub repcopy_userfile {
                   14989:     my ($file)=@_;
1.1142    raeburn  14990:     my $londocroot = $perlvar{'lonDocRoot'};
                   14991:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14992:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14993:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14994: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14995:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14996:     if (-e "$file") {
1.828     www      14997: # we already have a local copy, check it out
1.538     albertel 14998: 	my @fileinfo = stat($file);
1.828     www      14999: 	my $rtncode;
                   15000: 	my $info;
1.538     albertel 15001: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 15002: 	if ($lwpresp ne 'ok') {
1.828     www      15003: # there is no such file anymore, even though we had a local copy
1.482     albertel 15004: 	    if ($rtncode eq '404') {
1.538     albertel 15005: 		unlink($file);
1.482     albertel 15006: 	    }
                   15007: 	    return -1;
                   15008: 	}
                   15009: 	if ($info < $fileinfo[9]) {
1.828     www      15010: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  15011: 	    return 'ok';
1.828     www      15012: 	} else {
                   15013: # the file is outdated, get rid of it
                   15014: 	    unlink($file);
1.482     albertel 15015: 	}
1.828     www      15016:     }
                   15017: # one way or the other, at this point, we don't have the file
                   15018: # construct the correct path for the file
                   15019:     my @parts = ($cdom,$cnum); 
                   15020:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   15021: 	push @parts, split(/\//,$1);
                   15022:     }
                   15023:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   15024:     foreach my $part (@parts) {
                   15025: 	$path .= '/'.$part;
                   15026: 	if (!-e $path) {
                   15027: 	    mkdir($path,0770);
1.482     albertel 15028: 	}
                   15029:     }
1.828     www      15030: # now the path exists for sure
                   15031: # get a user agent
                   15032:     my $transferfile=$file.'.in.transfer';
                   15033: # FIXME: this should flock
                   15034:     if (-e $transferfile) { return 'ok'; }
                   15035:     my $request;
                   15036:     $uri=~s/^\///;
1.980     raeburn  15037:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  15038:     my $hostname = &hostname($homeserver);
1.980     raeburn  15039:     my $protocol = $protocol{$homeserver};
                   15040:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  15041:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  15042:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      15043: # did it work?
                   15044:     if ($response->is_error()) {
                   15045: 	unlink($transferfile);
                   15046: 	&logthis("Userfile repcopy failed for $uri");
                   15047: 	return -1;
                   15048:     }
                   15049: # worked, rename the transfer file
                   15050:     rename($transferfile,$file);
1.607     raeburn  15051:     return 'ok';
1.481     raeburn  15052: }
                   15053: 
1.517     albertel 15054: sub tokenwrapper {
                   15055:     my $uri=shift;
1.980     raeburn  15056:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 15057:     $uri=~s|^/||;
1.620     albertel 15058:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 15059:     my $token=$1;
1.552     albertel 15060:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   15061:     if ($udom && $uname && $file) {
                   15062: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  15063:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  15064:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  15065:         my $hostname = &hostname($homeserver);
1.980     raeburn  15066:         my $protocol = $protocol{$homeserver};
                   15067:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  15068:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 15069:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   15070:                                '&tokenissued='.$perlvar{'lonHostID'};
                   15071:     } else {
                   15072:         return '/adm/notfound.html';
                   15073:     }
                   15074: }
                   15075: 
1.828     www      15076: # call with reqtype HEAD: get last modification time
                   15077: # call with reqtype GET: get the file contents
                   15078: # Do not call this with reqtype GET for large files! It loads everything into memory
                   15079: #
1.481     raeburn  15080: sub getuploaded {
                   15081:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   15082:     $uri=~s/^\///;
1.980     raeburn  15083:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  15084:     my $hostname = &hostname($homeserver);
1.980     raeburn  15085:     my $protocol = $protocol{$homeserver};
                   15086:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  15087:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  15088:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  15089:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  15090:     $$rtncode = $response->code;
1.482     albertel 15091:     if (! $response->is_success()) {
                   15092: 	return 'failed';
                   15093:     }      
                   15094:     if ($reqtype eq 'HEAD') {
1.486     www      15095: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 15096:     } elsif ($reqtype eq 'GET') {
                   15097: 	$$info = $response->content;
1.472     albertel 15098:     }
1.482     albertel 15099:     return 'ok';
1.36      albertel 15100: }
                   15101: 
1.481     raeburn  15102: sub readfile {
                   15103:     my $file = shift;
                   15104:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   15105:     my $fh;
1.1359    raeburn  15106:     open($fh,"<",$file);
1.481     raeburn  15107:     my $a='';
1.800     albertel 15108:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  15109:     return $a;
                   15110: }
                   15111: 
1.36      albertel 15112: sub filelocation {
1.590     banghart 15113:     my ($dir,$file) = @_;
                   15114:     my $location;
                   15115:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 15116: 
                   15117:     if ($file =~ m-^/adm/-) {
                   15118: 	$file=~s-^/adm/wrapper/-/-;
                   15119: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   15120:     }
1.882     albertel 15121: 
1.1139    www      15122:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  15123:         $location = $file;
1.609     banghart 15124:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 15125:         my ($udom,$uname,$filename)=
1.811     albertel 15126:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 15127:         my $home=&homeserver($uname,$udom);
                   15128:         my $is_me=0;
                   15129:         my @ids=&current_machine_ids();
                   15130:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   15131:         if ($is_me) {
1.1117    foxr     15132:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 15133:         } else {
                   15134:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   15135:   	      $udom.'/'.$uname.'/'.$filename;
                   15136:         }
1.882     albertel 15137:     } elsif ($file =~ m-^/adm/-) {
                   15138: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 15139:     } else {
                   15140:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      15141:         $file=~s:^/(res|priv)/:/:;
                   15142:         my $space=$1;
1.590     banghart 15143:         if ( !( $file =~ m:^/:) ) {
                   15144:             $location = $dir. '/'.$file;
                   15145:         } else {
1.1142    raeburn  15146:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 15147:         }
1.59      albertel 15148:     }
1.590     banghart 15149:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 15150:     while ($location=~m{/\.\./}) {
                   15151: 	if ($location =~ m{/[^/]+/\.\./}) {
                   15152: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   15153: 	} else {
                   15154: 	    $location=~ s{/\.\./}{/}g;
                   15155: 	}
                   15156:     } #remove dir/..
1.590     banghart 15157:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   15158:     return $location;
1.46      www      15159: }
1.36      albertel 15160: 
1.46      www      15161: sub hreflocation {
                   15162:     my ($dir,$file)=@_;
1.980     raeburn  15163:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 15164: 	$file=filelocation($dir,$file);
1.700     albertel 15165:     } elsif ($file=~m-^/adm/-) {
                   15166: 	$file=~s-^/adm/wrapper/-/-;
                   15167: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 15168:     }
                   15169:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   15170: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   15171:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  15172: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   15173: 	        {/uploaded/$1/$2/}x;
1.46      www      15174:     }
1.913     albertel 15175:     if ($file=~ m{^/userfiles/}) {
                   15176: 	$file =~ s{^/userfiles/}{/uploaded/};
                   15177:     }
1.462     albertel 15178:     return $file;
1.465     albertel 15179: }
                   15180: 
1.1139    www      15181: 
                   15182: 
                   15183: 
                   15184: 
1.465     albertel 15185: sub current_machine_domains {
1.853     albertel 15186:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   15187: }
                   15188: 
                   15189: sub machine_domains {
                   15190:     my ($hostname) = @_;
1.465     albertel 15191:     my @domains;
1.838     albertel 15192:     my %hostname = &all_hostnames();
1.465     albertel 15193:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  15194: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 15195: 	if ($hostname eq $name) {
1.844     albertel 15196: 	    push(@domains,&host_domain($id));
1.465     albertel 15197: 	}
                   15198:     }
                   15199:     return @domains;
                   15200: }
                   15201: 
                   15202: sub current_machine_ids {
1.853     albertel 15203:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   15204: }
                   15205: 
                   15206: sub machine_ids {
                   15207:     my ($hostname) = @_;
                   15208:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 15209:     my @ids;
1.888     albertel 15210:     my %name_to_host = &all_names();
1.889     albertel 15211:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   15212: 	return @{ $name_to_host{$hostname} };
                   15213:     }
                   15214:     return;
1.31      www      15215: }
                   15216: 
1.824     raeburn  15217: sub additional_machine_domains {
                   15218:     my @domains;
1.1466    raeburn  15219:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   15220:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   15221:             while (my $line = <$fh>) {
                   15222:                 chomp($line);           
                   15223:                 $line =~ s/\s//g;
                   15224:                 push(@domains,$line);
                   15225:             }
                   15226:             close($fh);
                   15227:         }
1.824     raeburn  15228:     }
                   15229:     return @domains;
                   15230: }
                   15231: 
                   15232: sub default_login_domain {
                   15233:     my $domain = $perlvar{'lonDefDomain'};
                   15234:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   15235:     foreach my $posdom (&current_machine_domains(),
                   15236:                         &additional_machine_domains()) {
                   15237:         if (lc($posdom) eq lc($testdomain)) {
                   15238:             $domain=$posdom;
                   15239:             last;
                   15240:         }
                   15241:     }
                   15242:     return $domain;
                   15243: }
                   15244: 
1.1414    raeburn  15245: sub shared_institution {
1.1439    raeburn  15246:     my ($dom,$lonhost) = @_;
                   15247:     if ($lonhost eq '') {
                   15248:         $lonhost = $perlvar{'lonHostID'};
                   15249:     }
1.1414    raeburn  15250:     my $same_intdom;
1.1439    raeburn  15251:     my $hostintdom = &internet_dom($lonhost);
1.1414    raeburn  15252:     if ($hostintdom ne '') {
                   15253:         my %iphost = &get_iphost();
                   15254:         my $primary_id = &domain($dom,'primary');
                   15255:         my $primary_ip = &get_host_ip($primary_id);
                   15256:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   15257:             foreach my $id (@{$iphost{$primary_ip}}) {
                   15258:                 my $intdom = &internet_dom($id);
                   15259:                 if ($intdom eq $hostintdom) {
                   15260:                     $same_intdom = 1;
                   15261:                     last;
                   15262:                 }
                   15263:             }
                   15264:         }
                   15265:     }
                   15266:     return $same_intdom;
                   15267: }
                   15268: 
1.1398    raeburn  15269: sub uses_sts {
                   15270:     my ($ignore_cache) = @_;
                   15271:     my $lonhost = $perlvar{'lonHostID'};
                   15272:     my $hostname = &hostname($lonhost);
                   15273:     my $sts_on;
                   15274:     if ($protocol{$lonhost} eq 'https') {
                   15275:         my $cachetime = 12*3600;
                   15276:         if (!$ignore_cache) {
                   15277:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   15278:             if (defined($cached)) {
                   15279:                 return $sts_on;
                   15280:             }
                   15281:         }
                   15282:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   15283:         my $request=new HTTP::Request('HEAD',$url);
                   15284:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   15285:         if ($response->is_success) {
                   15286:             my $has_sts = $response->header('Strict-Transport-Security');
                   15287:             if ($has_sts eq '') {
                   15288:                 $sts_on = 0;
                   15289:             } else {
                   15290:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   15291:                     my $maxage = $1;
                   15292:                     if ($maxage) {
                   15293:                         $sts_on = 1;
                   15294:                     } else {
                   15295:                         $sts_on = 0;
                   15296:                     }
                   15297:                 } else {
                   15298:                     $sts_on = 0;
                   15299:                 }
                   15300:             }
                   15301:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   15302:         }
                   15303:     }
                   15304:     return;
                   15305: }
                   15306: 
1.1449    raeburn  15307: sub waf_allssl {
                   15308:     my ($host_name) = @_;
                   15309:     my $alias = &get_proxy_alias();
                   15310:     if ($host_name eq '') {
                   15311:         $host_name = $ENV{'SERVER_NAME'};
                   15312:     }
                   15313:     if (($host_name ne '') && ($alias eq $host_name)) {
                   15314:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   15315:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   15316:         if ($defdomdefaults{'waf_sslopt'}) {
                   15317:             return $defdomdefaults{'waf_sslopt'};
                   15318:         }
                   15319:     }
                   15320:     return;
                   15321: }
                   15322: 
1.1434    raeburn  15323: sub get_requestor_ip {
                   15324:     my ($r,$nolookup,$noproxy) = @_;
                   15325:     my $from_ip;
                   15326:     if (ref($r)) {
1.1447    raeburn  15327:         if ($r->can('useragent_ip')) {
                   15328:             if ($noproxy && $r->can('client_ip')) {
                   15329:                 $from_ip = $r->client_ip();
                   15330:             } else {
                   15331:                 $from_ip = $r->useragent_ip();
                   15332:             }
                   15333:         } elsif ($r->connection->can('remote_ip')) {
                   15334:             $from_ip = $r->connection->remote_ip();
                   15335:         } else {
                   15336:             $from_ip = $r->get_remote_host($nolookup);
                   15337:         }
1.1434    raeburn  15338:     } else {
                   15339:         $from_ip = $ENV{'REMOTE_ADDR'};
                   15340:     }
                   15341:     return $from_ip if ($noproxy); 
                   15342:     # Who controls proxy settings for server
                   15343:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15344:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   15345:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437    raeburn  15346:         if ($proxyinfo->{'vpnint'}) {
                   15347:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434    raeburn  15348:                 return $from_ip;
                   15349:             }
                   15350:         }
                   15351:         if ($proxyinfo->{'trusted'}) {
                   15352:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   15353:                 my $ipheader = $proxyinfo->{'ipheader'};
                   15354:                 my ($ip,$xfor);
                   15355:                 if (ref($r)) {
                   15356:                     if ($ipheader) {
                   15357:                         $ip = $r->headers_in->{$ipheader};
                   15358:                     }
                   15359:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   15360:                 } else {
                   15361:                     if ($ipheader) {
                   15362:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   15363:                     }
                   15364:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   15365:                 }
                   15366:                 if (($ip eq '') && ($xfor ne '')) {
                   15367:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   15368:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   15369:                             $ip = $poss_ip;
1.1435    raeburn  15370:                             last;
1.1434    raeburn  15371:                         }
                   15372:                     }
                   15373:                 }
                   15374:                 if ($ip ne '') {
                   15375:                     return $ip;
                   15376:                 }
                   15377:             }
                   15378:         }
                   15379:     }
                   15380:     return $from_ip;
                   15381: }
                   15382: 
                   15383: sub get_proxy_settings {
                   15384:     my ($dom_in_use) = @_;
1.1494    raeburn  15385:     my %domdefaults = &get_domain_defaults($dom_in_use);
1.1434    raeburn  15386:     my $proxyinfo = {
                   15387:                        ipheader => $domdefaults{'waf_ipheader'},
                   15388:                        trusted  => $domdefaults{'waf_trusted'},
1.1437    raeburn  15389:                        vpnint   => $domdefaults{'waf_vpnint'},
1.1438    raeburn  15390:                        vpnext   => $domdefaults{'waf_vpnext'},
1.1449    raeburn  15391:                        sslopt   => $domdefaults{'waf_sslopt'},
1.1434    raeburn  15392:                     };
                   15393:     return $proxyinfo;
                   15394: }
                   15395: 
                   15396: sub ip_match {
                   15397:     my ($ip,$pattern_str) = @_;
                   15398:     $ip=Net::CIDR::cidrvalidate($ip);
                   15399:     if ($ip) {
                   15400:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   15401:     }
                   15402:     return;
                   15403: }
                   15404: 
                   15405: sub get_proxy_alias {
1.1450    raeburn  15406:     my ($lonid) = @_;
                   15407:     if ($lonid eq '') {
                   15408:         $lonid = $perlvar{'lonHostID'};
                   15409:     }
                   15410:     if (!defined(&hostname($lonid))) {
                   15411:         return;
                   15412:     }
                   15413:     if ($lonid ne '') {
                   15414:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434    raeburn  15415:         if ($cached) {
                   15416:             return $alias;
                   15417:         }
1.1494    raeburn  15418:         my $dom = &host_domain($lonid);
1.1434    raeburn  15419:         if ($dom ne '') {
                   15420:             my $cachetime = 60*60*24;
                   15421:             my %domconfig =
1.1494    raeburn  15422:                 &get_dom('configuration',['wafproxy'],$dom);
1.1437    raeburn  15423:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   15424:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450    raeburn  15425:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   15426:                 }
                   15427:             }
                   15428:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   15429:         }
                   15430:     }
                   15431:     return;
                   15432: }
                   15433: 
                   15434: sub use_proxy_alias {
                   15435:     my ($r,$lonid) = @_;
                   15436:     my $alias = &get_proxy_alias($lonid);
                   15437:     if ($alias) {
                   15438:         my $dom = &host_domain($lonid);
                   15439:         if ($dom ne '') {
1.1467    raeburn  15440:             my $proxyinfo = &get_proxy_settings($dom);
1.1450    raeburn  15441:             my ($vpnint,$remote_ip);
                   15442:             if (ref($proxyinfo) eq 'HASH') {
                   15443:                 $vpnint = $proxyinfo->{'vpnint'};
                   15444:                 if ($vpnint) {
                   15445:                     $remote_ip = &get_requestor_ip($r,1,1);
1.1434    raeburn  15446:                 }
                   15447:             }
1.1450    raeburn  15448:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   15449:                 return $alias;
                   15450:             }
1.1434    raeburn  15451:         }
                   15452:     }
                   15453:     return;
                   15454: }
                   15455: 
1.1474    raeburn  15456: sub alias_sso {
1.1467    raeburn  15457:     my ($lonid) = @_;
                   15458:     if ($lonid eq '') {
                   15459:         $lonid = $perlvar{'lonHostID'};
                   15460:     }
                   15461:     if (!defined(&hostname($lonid))) {
                   15462:         return;
                   15463:     }
                   15464:     if ($lonid ne '') {
                   15465:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   15466:         if ($cached) {
                   15467:             return $use_alias;
                   15468:         }
1.1494    raeburn  15469:         my $dom = &host_domain($lonid);
1.1467    raeburn  15470:         if ($dom ne '') {
                   15471:             my $cachetime = 60*60*24;
                   15472:             my %domconfig =
1.1494    raeburn  15473:                 &get_dom('configuration',['wafproxy'],$dom);
1.1467    raeburn  15474:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   15475:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   15476:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   15477:                 }
                   15478:             }
                   15479:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   15480:         }
                   15481:     }
                   15482:     return;
                   15483: }
                   15484: 
1.1465    raeburn  15485: sub get_saml_landing {
                   15486:     my ($lonid) = @_;
                   15487:     if ($lonid eq '') {
                   15488:         my $defdom = &default_login_domain();
                   15489:         my @hosts = &current_machine_ids();
                   15490:         if (@hosts > 1) {
                   15491:             foreach my $hostid (@hosts) {
                   15492:                 if (&host_domain($hostid) eq $defdom) {
                   15493:                     $lonid = $hostid;
                   15494:                     last;
                   15495:                 }
                   15496:             }
                   15497:         } else {
                   15498:             $lonid = $perlvar{'lonHostID'};
                   15499:         }
                   15500:         if ($lonid) {
1.1494    raeburn  15501:             unless (&host_domain($lonid) eq $defdom) {
1.1465    raeburn  15502:                 return;
                   15503:             }
                   15504:         } else {
                   15505:             return;
                   15506:         }
                   15507:     } elsif (!defined(&hostname($lonid))) {
                   15508:         return;
                   15509:     }
                   15510:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   15511:     if ($cached) {
                   15512:         return $landing;
                   15513:     }
1.1494    raeburn  15514:     my $dom = &host_domain($lonid);
1.1465    raeburn  15515:     if ($dom ne '') {
                   15516:         my $cachetime = 60*60*24;
                   15517:         my %domconfig =
1.1494    raeburn  15518:             &get_dom('configuration',['login'],$dom);
1.1465    raeburn  15519:         if (ref($domconfig{'login'}) eq 'HASH') {
                   15520:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   15521:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   15522:                     $landing = 1;
                   15523:                 }
                   15524:             }
                   15525:         }
                   15526:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   15527:     }
                   15528:     return;
                   15529: }
                   15530: 
1.31      www      15531: # ------------------------------------------------------------- Declutters URLs
                   15532: 
                   15533: sub declutter {
                   15534:     my $thisfn=shift;
1.569     albertel 15535:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  15536:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   15537:         $thisfn=~s{^/home/httpd/html}{};
                   15538:     }
1.31      www      15539:     $thisfn=~s/^\///;
1.697     albertel 15540:     $thisfn=~s|^adm/wrapper/||;
                   15541:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      15542:     $thisfn=~s/^res\///;
1.1172    bisitz   15543:     $thisfn=~s/^priv\///;
1.1032    raeburn  15544:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   15545:         $thisfn=~s/\?.+$//;
                   15546:     }
1.268     www      15547:     return $thisfn;
                   15548: }
                   15549: 
                   15550: # ------------------------------------------------------------- Clutter up URLs
                   15551: 
                   15552: sub clutter {
                   15553:     my $thisfn='/'.&declutter(shift);
1.887     albertel 15554:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 15555: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      15556:        $thisfn='/res'.$thisfn; 
                   15557:     }
1.1031    raeburn  15558:     if ($thisfn !~m|^/adm|) {
                   15559: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 15560: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 15561: 	} else {
                   15562: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   15563: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 15564: 	    if ($embstyle eq 'ssi'
                   15565: 		|| ($embstyle eq 'hdn')
                   15566: 		|| ($embstyle eq 'rat')
                   15567: 		|| ($embstyle eq 'prv')
                   15568: 		|| ($embstyle eq 'ign')) {
                   15569: 		#do nothing with these
                   15570: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 15571: 		|| ($embstyle eq 'emb')
                   15572: 		|| ($embstyle eq 'wrp')) {
                   15573: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 15574: 	    } elsif ($embstyle eq 'unk'
                   15575: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 15576: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 15577: 	    } else {
1.718     www      15578: #		&logthis("Got a blank emb style");
1.695     albertel 15579: 	    }
1.694     albertel 15580: 	}
1.1343    raeburn  15581:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  15582:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 15583:     }
1.31      www      15584:     return $thisfn;
1.12      www      15585: }
                   15586: 
1.787     albertel 15587: sub clutter_with_no_wrapper {
                   15588:     my $uri = &clutter(shift);
                   15589:     if ($uri =~ m-^/adm/-) {
                   15590: 	$uri =~ s-^/adm/wrapper/-/-;
                   15591: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   15592:     }
                   15593:     return $uri;
                   15594: }
                   15595: 
1.557     albertel 15596: sub freeze_escape {
                   15597:     my ($value)=@_;
                   15598:     if (ref($value)) {
                   15599: 	$value=&nfreeze($value);
                   15600: 	return '__FROZEN__'.&escape($value);
                   15601:     }
                   15602:     return &escape($value);
                   15603: }
                   15604: 
1.11      www      15605: 
1.557     albertel 15606: sub thaw_unescape {
                   15607:     my ($value)=@_;
                   15608:     if ($value =~ /^__FROZEN__/) {
                   15609: 	substr($value,0,10,undef);
                   15610: 	$value=&unescape($value);
                   15611: 	return &thaw($value);
                   15612:     }
                   15613:     return &unescape($value);
                   15614: }
                   15615: 
1.436     albertel 15616: sub correct_line_ends {
                   15617:     my ($result)=@_;
                   15618:     $$result =~s/\r\n/\n/mg;
                   15619:     $$result =~s/\r/\n/mg;
1.415     albertel 15620: }
1.1       albertel 15621: # ================================================================ Main Program
                   15622: 
1.184     www      15623: sub goodbye {
1.204     albertel 15624:    &logthis("Starting Shut down");
1.443     albertel 15625: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 15626:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 15627: #converted
1.599     albertel 15628: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 15629:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   15630: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   15631: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 15632: #1.1 only
1.870     albertel 15633: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   15634: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   15635: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   15636: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   15637:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 15638:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   15639:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      15640:    &flushcourselogs();
                   15641:    &logthis("Shutting down");
                   15642: }
                   15643: 
1.852     albertel 15644: sub get_dns {
1.1210    raeburn  15645:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 15646:     if (!$ignore_cache) {
                   15647: 	my ($content,$cached)=
1.1494    raeburn  15648: 	    &is_cached_new('dns',$url);
1.869     albertel 15649: 	if ($cached) {
1.1210    raeburn  15650: 	    &$func($content,$hashref);
1.869     albertel 15651: 	    return;
                   15652: 	}
                   15653:     }
                   15654: 
                   15655:     my %alldns;
1.1379    raeburn  15656:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   15657:         foreach my $dns (<$config>) {
                   15658: 	    next if ($dns !~ /^\^(\S*)/x);
                   15659:             my $line = $1;
                   15660:             my ($host,$protocol) = split(/:/,$line);
                   15661:             if ($protocol ne 'https') {
                   15662:                 $protocol = 'http';
                   15663:             }
                   15664: 	    $alldns{$host} = $protocol;
1.979     raeburn  15665:         }
1.1379    raeburn  15666:         close($config);
1.869     albertel 15667:     }
                   15668:     while (%alldns) {
1.1263    raeburn  15669: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456    raeburn  15670:         my ($contents,@content);
                   15671:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   15672:             my $command = (split('/',$url))[3];
                   15673:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   15674:             delete($alldns{$dns});
                   15675:             next if (($dir eq '') || ($file eq ''));
                   15676:             if (open(my $config,'<',"$dir/$file")) {
1.1457    raeburn  15677:                 @content = <$config>;
1.1456    raeburn  15678:                 close($config);
                   15679:             }
                   15680:             if ($url eq '/adm/dns/loncapaCRL') {
                   15681:                 $contents = join('',@content);
                   15682:             }
                   15683:         } else {
                   15684: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   15685:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
                   15686:             delete($alldns{$dns});
                   15687: 	    next if ($response->is_error());
                   15688:             if ($url eq '/adm/dns/loncapaCRL') {
                   15689:                 $contents = $response->content;
                   15690:             } else {
                   15691:                 @content = split("\n",$response->content);
                   15692:             }
                   15693:         }
1.1379    raeburn  15694:         if ($url eq '/adm/dns/loncapaCRL') {
1.1456    raeburn  15695:             return &$func($contents);
1.1379    raeburn  15696:         } else {
                   15697: 	    unless ($nocache) {
                   15698: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   15699: 	    }
                   15700: 	    &$func(\@content,$hashref);
                   15701:             return;
                   15702:         }
                   15703:     }
                   15704:     my $which = (split('/',$url,4))[3];
                   15705:     if ($which eq 'loncapaCRL') {
                   15706:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   15707:         if (-e $diskfile) {
                   15708:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   15709:         } else {
                   15710:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   15711:         }
                   15712:     } else {
                   15713:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   15714:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   15715:             my @content = <$config>;
                   15716:             close($config);
                   15717:             &$func(\@content,$hashref);
                   15718:         }
1.852     albertel 15719:     }
1.1210    raeburn  15720:     return;
                   15721: }
                   15722: 
                   15723: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  15724: sub parse_dns_checksums_tab {
1.1210    raeburn  15725:     my ($lines,$hashref) = @_;
1.1264    raeburn  15726:     my $lonhost = $perlvar{'lonHostID'};
1.1494    raeburn  15727:     my $machine_dom = &host_domain($lonhost);
1.1210    raeburn  15728:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  15729:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   15730:     my $webconfdir = '/etc/httpd/conf';
                   15731:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   15732:         $webconfdir = '/etc/apache2';
                   15733:     } elsif ($distro =~ /^sles(\d+)$/) {
                   15734:         if ($1 >= 10) {
                   15735:             $webconfdir = '/etc/apache2';
                   15736:         }
                   15737:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   15738:         if ($1 >= 10.0) {
                   15739:             $webconfdir = '/etc/apache2';
                   15740:         }
                   15741:     }
1.1210    raeburn  15742:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15743:     my (%chksum,%revnum);
                   15744:     if (ref($lines) eq 'ARRAY') {
                   15745:         chomp(@{$lines});
1.1238    raeburn  15746:         my $version = shift(@{$lines});
                   15747:         if ($version eq $release) {  
1.1210    raeburn  15748:             foreach my $line (@{$lines}) {
1.1238    raeburn  15749:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  15750:                 if ($file =~ m{^/etc/httpd/conf}) {
                   15751:                     if ($webconfdir eq '/etc/apache2') {
                   15752:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   15753:                     }
                   15754:                 }
1.1238    raeburn  15755:                 $chksum{$file} = $shasum;
                   15756:                 $revnum{$file} = $version;
1.1210    raeburn  15757:             }
                   15758:             if (ref($hashref) eq 'HASH') {
                   15759:                 %{$hashref} = (
                   15760:                                 sums     => \%chksum,
                   15761:                                 versions => \%revnum,
                   15762:                               );
                   15763:             }
                   15764:         }
                   15765:     }
1.869     albertel 15766:     return;
1.852     albertel 15767: }
1.1210    raeburn  15768: 
                   15769: sub fetch_dns_checksums {
1.1238    raeburn  15770:     my %checksums;
1.1494    raeburn  15771:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
1.1260    raeburn  15772:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  15773:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15774:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  15775:              \%checksums);
1.1210    raeburn  15776:     return \%checksums;
                   15777: }
                   15778: 
1.1379    raeburn  15779: sub fetch_crl_pemfile {
                   15780:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   15781: }
                   15782: 
                   15783: sub save_crl_pem {
1.1456    raeburn  15784:     my ($content) = @_;
1.1380    raeburn  15785:     my ($msg,$hadchanges);
1.1456    raeburn  15786:     if ($content ne '') {
1.1379    raeburn  15787:         my $now = time;
                   15788:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   15789:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   15790:         if (open(my $fh,'>',"$tmpcrl")) {
1.1456    raeburn  15791:             print $fh $content;
1.1379    raeburn  15792:             close($fh);
                   15793:             if (-e $lonca) {
                   15794:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   15795:                     my $check = <PIPE>;
                   15796:                     close(PIPE);
                   15797:                     chomp($check);
                   15798:                     if ($check eq 'verify OK') {
                   15799:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  15800:                         my $backup;
1.1379    raeburn  15801:                         if (-e $dest) {
1.1380    raeburn  15802:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   15803:                                 $backup = 'ok';
                   15804:                             }
1.1379    raeburn  15805:                         }
                   15806:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   15807:                             $msg = 'ok';
1.1380    raeburn  15808:                             if ($backup) {
                   15809:                                 my (%oldnums,%newnums);
                   15810:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   15811:                                     while (<PIPE>) {
                   15812:                                         $oldnums{(split(/:/))[1]} = 1;
                   15813:                                     }
                   15814:                                     close(PIPE);
                   15815:                                 }
                   15816:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   15817:                                     while(<PIPE>) {
                   15818:                                         $newnums{(split(/:/))[1]} = 1;
                   15819:                                     }
                   15820:                                     close(PIPE);
                   15821:                                 }
                   15822:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   15823:                                     unless (exists($oldnums{$key})) {
                   15824:                                         $hadchanges = 1;
                   15825:                                         last;
                   15826:                                     }
                   15827:                                 }
                   15828:                                 unless ($hadchanges) {
                   15829:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   15830:                                         unless (exists($newnums{$key})) {
                   15831:                                             $hadchanges = 1;
                   15832:                                             last;
                   15833:                                         }
                   15834:                                     }
                   15835:                                 }
                   15836:                             }
1.1379    raeburn  15837:                         }
                   15838:                     } else {
                   15839:                         unlink($tmpcrl);
                   15840:                     }
                   15841:                 } else {
                   15842:                     unlink($tmpcrl);
                   15843:                 }
                   15844:             } else {
                   15845:                 unlink($tmpcrl);
                   15846:             }
                   15847:         }
                   15848:     }
1.1380    raeburn  15849:     return ($msg,$hadchanges);
1.1379    raeburn  15850: }
                   15851: 
1.1456    raeburn  15852: sub parse_getdns_url {
                   15853:     my ($command,$url) = @_;
                   15854:     my $dir = $perlvar{'lonTabDir'};
                   15855:     my $file;
                   15856:     if ($command eq 'hosts') {
                   15857:         $file = 'dns_hosts.tab';
                   15858:     } elsif ($command eq 'domain') {
                   15859:         $file = 'dns_domain.tab';
                   15860:     } elsif ($command eq 'checksums') {
                   15861:         my $version = (split('/',$url))[4];
                   15862:         $file = "dns_checksums/$version.tab",
                   15863:     } elsif ($command eq 'loncapaCRL') {
                   15864:         $dir = $perlvar{'lonCertificateDirectory'};
                   15865:         $file = $perlvar{'lonnetCertRevocationList'};
                   15866:     }
                   15867:     return ($dir,$file);
                   15868: }
                   15869: 
1.327     albertel 15870: # ------------------------------------------------------------ Read domain file
                   15871: {
1.852     albertel 15872:     my $loaded;
1.846     albertel 15873:     my %domain;
                   15874: 
1.852     albertel 15875:     sub parse_domain_tab {
                   15876: 	my ($lines) = @_;
                   15877: 	foreach my $line (@$lines) {
                   15878: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      15879: 
1.846     albertel 15880: 	    chomp($line);
1.852     albertel 15881: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 15882: 	    my %this_domain;
                   15883: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   15884: 			       'lang_def', 'city', 'longi', 'lati',
                   15885: 			       'primary') {
                   15886: 		$this_domain{$field} = shift(@elements);
                   15887: 	    }
                   15888: 	    $domain{$name} = \%this_domain;
1.852     albertel 15889: 	}
                   15890:     }
1.864     albertel 15891: 
                   15892:     sub reset_domain_info {
                   15893: 	undef($loaded);
                   15894: 	undef(%domain);
                   15895:     }
                   15896: 
1.852     albertel 15897:     sub load_domain_tab {
1.1293    raeburn  15898: 	my ($ignore_cache,$nocache) = @_;
                   15899: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 15900: 	my $fh;
1.1359    raeburn  15901: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 15902: 	    my @lines = <$fh>;
                   15903: 	    &parse_domain_tab(\@lines);
1.448     albertel 15904: 	}
1.852     albertel 15905: 	close($fh);
                   15906: 	$loaded = 1;
1.327     albertel 15907:     }
1.846     albertel 15908: 
                   15909:     sub domain {
1.852     albertel 15910: 	&load_domain_tab() if (!$loaded);
                   15911: 
1.846     albertel 15912: 	my ($name,$what) = @_;
                   15913: 	return if ( !exists($domain{$name}) );
                   15914: 
                   15915: 	if (!$what) {
                   15916: 	    return $domain{$name}{'description'};
                   15917: 	}
                   15918: 	return $domain{$name}{$what};
                   15919:     }
1.974     raeburn  15920: 
                   15921:     sub domain_info {
                   15922:         &load_domain_tab() if (!$loaded);
                   15923:         return %domain;
                   15924:     }
                   15925: 
1.327     albertel 15926: }
                   15927: 
                   15928: 
1.1       albertel 15929: # ------------------------------------------------------------- Read hosts file
                   15930: {
1.838     albertel 15931:     my %hostname;
1.844     albertel 15932:     my %hostdom;
1.845     albertel 15933:     my %libserv;
1.852     albertel 15934:     my $loaded;
1.888     albertel 15935:     my %name_to_host;
1.1074    raeburn  15936:     my %internetdom;
1.1107    raeburn  15937:     my %LC_dns_serv;
1.852     albertel 15938: 
                   15939:     sub parse_hosts_tab {
                   15940: 	my ($file) = @_;
                   15941: 	foreach my $configline (@$file) {
                   15942: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  15943:             chomp($configline);
                   15944: 	    if ($configline =~ /^\^/) {
                   15945:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   15946:                     $LC_dns_serv{$1} = 1;
                   15947:                 }
                   15948:                 next;
                   15949:             }
1.1074    raeburn  15950: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 15951: 	    $name=~s/\s//g;
                   15952: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  15953:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   15954:                     my $curr = $hostname{$id};
                   15955:                     my $skip;
                   15956:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   15957:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   15958:                             $skip = 1;
                   15959:                         } else {
                   15960:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   15961:                         }
                   15962:                     }
                   15963:                     unless ($skip) {
                   15964:                         push(@{$name_to_host{$name}},$id);
                   15965:                     }
                   15966:                 } else {
                   15967:                     push(@{$name_to_host{$name}},$id);
                   15968:                 }
1.852     albertel 15969: 		$hostname{$id}=$name;
                   15970: 		$hostdom{$id}=$domain;
                   15971: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  15972:                 if (defined($protocol)) {
                   15973:                     if ($protocol eq 'https') {
                   15974:                         $protocol{$id} = $protocol;
                   15975:                     } else {
                   15976:                         $protocol{$id} = 'http'; 
                   15977:                     }
1.968     raeburn  15978:                 } else {
1.969     raeburn  15979:                     $protocol{$id} = 'http';
1.968     raeburn  15980:                 }
1.1074    raeburn  15981:                 if (defined($intdom)) {
                   15982:                     $internetdom{$id} = $intdom;
                   15983:                 }
1.852     albertel 15984: 	    }
                   15985: 	}
                   15986:     }
1.864     albertel 15987:     
                   15988:     sub reset_hosts_info {
1.897     albertel 15989: 	&purge_remembered();
1.864     albertel 15990: 	&reset_domain_info();
                   15991: 	&reset_hosts_ip_info();
1.1339    raeburn  15992:         undef(%internetdom);
1.892     albertel 15993: 	undef(%name_to_host);
1.864     albertel 15994: 	undef(%hostname);
                   15995: 	undef(%hostdom);
                   15996: 	undef(%libserv);
                   15997: 	undef($loaded);
                   15998:     }
1.1       albertel 15999: 
1.852     albertel 16000:     sub load_hosts_tab {
1.1293    raeburn  16001: 	my ($ignore_cache,$nocache) = @_;
                   16002: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  16003: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 16004: 	my @config = <$config>;
                   16005: 	&parse_hosts_tab(\@config);
                   16006: 	close($config);
                   16007: 	$loaded=1;
1.1       albertel 16008:     }
1.852     albertel 16009: 
1.838     albertel 16010:     sub hostname {
1.852     albertel 16011: 	&load_hosts_tab() if (!$loaded);
                   16012: 
1.838     albertel 16013: 	my ($lonid) = @_;
                   16014: 	return $hostname{$lonid};
                   16015:     }
1.845     albertel 16016: 
1.838     albertel 16017:     sub all_hostnames {
1.852     albertel 16018: 	&load_hosts_tab() if (!$loaded);
                   16019: 
1.838     albertel 16020: 	return %hostname;
                   16021:     }
1.845     albertel 16022: 
1.888     albertel 16023:     sub all_names {
1.1293    raeburn  16024:         my ($ignore_cache,$nocache) = @_;
                   16025: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 16026: 
                   16027: 	return %name_to_host;
                   16028:     }
                   16029: 
1.974     raeburn  16030:     sub all_host_domain {
                   16031:         &load_hosts_tab() if (!$loaded);
                   16032:         return %hostdom;
                   16033:     }
                   16034: 
1.1339    raeburn  16035:     sub all_host_intdom {
                   16036:         &load_hosts_tab() if (!$loaded);
                   16037:         return %internetdom;
                   16038:     }
                   16039: 
1.845     albertel 16040:     sub is_library {
1.852     albertel 16041: 	&load_hosts_tab() if (!$loaded);
                   16042: 
1.845     albertel 16043: 	return exists($libserv{$_[0]});
                   16044:     }
                   16045: 
                   16046:     sub all_library {
1.852     albertel 16047: 	&load_hosts_tab() if (!$loaded);
                   16048: 
1.845     albertel 16049: 	return %libserv;
                   16050:     }
                   16051: 
1.1062    droeschl 16052:     sub unique_library {
                   16053: 	#2x reverse removes all hostnames that appear more than once
                   16054:         my %unique = reverse &all_library();
                   16055:         return reverse %unique;
                   16056:     }
                   16057: 
1.841     albertel 16058:     sub get_servers {
1.852     albertel 16059: 	&load_hosts_tab() if (!$loaded);
                   16060: 
1.841     albertel 16061: 	my ($domain,$type) = @_;
                   16062: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   16063: 	                                          : %hostname;
                   16064: 	my %result;
1.842     albertel 16065: 	if (ref($domain) eq 'ARRAY') {
                   16066: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 16067: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 16068: 		    $result{$host} = $hostname;
                   16069: 		}
                   16070: 	    }
                   16071: 	} else {
                   16072: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   16073: 		if ($hostdom{$host} eq $domain) {
                   16074: 		    $result{$host} = $hostname;
                   16075: 		}
1.841     albertel 16076: 	    }
                   16077: 	}
                   16078: 	return %result;
                   16079:     }
1.845     albertel 16080: 
1.1062    droeschl 16081:     sub get_unique_servers {
                   16082:         my %unique = reverse &get_servers(@_);
                   16083: 	return reverse %unique;
                   16084:     }
                   16085: 
1.844     albertel 16086:     sub host_domain {
1.852     albertel 16087: 	&load_hosts_tab() if (!$loaded);
                   16088: 
1.844     albertel 16089: 	my ($lonid) = @_;
                   16090: 	return $hostdom{$lonid};
                   16091:     }
                   16092: 
1.841     albertel 16093:     sub all_domains {
1.852     albertel 16094: 	&load_hosts_tab() if (!$loaded);
                   16095: 
1.841     albertel 16096: 	my %seen;
                   16097: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   16098: 	return @uniq;
                   16099:     }
1.1074    raeburn  16100: 
                   16101:     sub internet_dom {
                   16102:         &load_hosts_tab() if (!$loaded);
                   16103: 
                   16104:         my ($lonid) = @_;
                   16105:         return $internetdom{$lonid};
                   16106:     }
1.1107    raeburn  16107: 
                   16108:     sub is_LC_dns {
                   16109:         &load_hosts_tab() if (!$loaded);
                   16110: 
                   16111:         my ($hostname) = @_;
                   16112:         return exists($LC_dns_serv{$hostname});
                   16113:     }
                   16114: 
1.1       albertel 16115: }
                   16116: 
1.847     albertel 16117: { 
                   16118:     my %iphost;
1.856     albertel 16119:     my %name_to_ip;
                   16120:     my %lonid_to_ip;
1.869     albertel 16121: 
1.847     albertel 16122:     sub get_hosts_from_ip {
                   16123: 	my ($ip) = @_;
                   16124: 	my %iphosts = &get_iphost();
                   16125: 	if (ref($iphosts{$ip})) {
                   16126: 	    return @{$iphosts{$ip}};
                   16127: 	}
                   16128: 	return;
1.839     albertel 16129:     }
1.864     albertel 16130:     
                   16131:     sub reset_hosts_ip_info {
                   16132: 	undef(%iphost);
                   16133: 	undef(%name_to_ip);
                   16134: 	undef(%lonid_to_ip);
                   16135:     }
1.856     albertel 16136: 
                   16137:     sub get_host_ip {
                   16138: 	my ($lonid) = @_;
                   16139: 	if (exists($lonid_to_ip{$lonid})) {
                   16140: 	    return $lonid_to_ip{$lonid};
                   16141: 	}
                   16142: 	my $name=&hostname($lonid);
                   16143:    	my $ip = gethostbyname($name);
                   16144: 	return if (!$ip || length($ip) ne 4);
                   16145: 	$ip=inet_ntoa($ip);
                   16146: 	$name_to_ip{$name}   = $ip;
                   16147: 	$lonid_to_ip{$lonid} = $ip;
                   16148: 	return $ip;
                   16149:     }
1.847     albertel 16150:     
                   16151:     sub get_iphost {
1.1293    raeburn  16152: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 16153: 
1.869     albertel 16154: 	if (!$ignore_cache) {
                   16155: 	    if (%iphost) {
                   16156: 		return %iphost;
                   16157: 	    }
                   16158: 	    my ($ip_info,$cached)=
1.1494    raeburn  16159: 		&is_cached_new('iphost','iphost');
1.869     albertel 16160: 	    if ($cached) {
                   16161: 		%iphost      = %{$ip_info->[0]};
                   16162: 		%name_to_ip  = %{$ip_info->[1]};
                   16163: 		%lonid_to_ip = %{$ip_info->[2]};
                   16164: 		return %iphost;
                   16165: 	    }
                   16166: 	}
1.894     albertel 16167: 
                   16168: 	# get yesterday's info for fallback
                   16169: 	my %old_name_to_ip;
                   16170: 	my ($ip_info,$cached)=
1.1495    raeburn  16171: 	    &is_cached_new('iphost','iphost');
1.894     albertel 16172: 	if ($cached) {
                   16173: 	    %old_name_to_ip = %{$ip_info->[1]};
                   16174: 	}
                   16175: 
1.1293    raeburn  16176: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 16177: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 16178: 	    my $ip;
                   16179: 	    if (!exists($name_to_ip{$name})) {
                   16180: 		$ip = gethostbyname($name);
                   16181: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 16182: 		    if (defined($old_name_to_ip{$name})) {
                   16183: 			$ip = $old_name_to_ip{$name};
                   16184: 			&logthis("Can't find $name defaulting to old $ip");
                   16185: 		    } else {
                   16186: 			&logthis("Name $name no IP found");
                   16187: 			next;
                   16188: 		    }
                   16189: 		} else {
                   16190: 		    $ip=inet_ntoa($ip);
1.847     albertel 16191: 		}
                   16192: 		$name_to_ip{$name} = $ip;
                   16193: 	    } else {
                   16194: 		$ip = $name_to_ip{$name};
1.653     albertel 16195: 	    }
1.888     albertel 16196: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   16197: 		$lonid_to_ip{$id} = $ip;
                   16198: 	    }
                   16199: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 16200: 	}
1.1293    raeburn  16201:         unless ($nocache) {
                   16202: 	    &do_cache_new('iphost','iphost',
                   16203: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   16204: 		          48*60*60);
                   16205:         }
1.869     albertel 16206: 
1.847     albertel 16207: 	return %iphost;
1.598     albertel 16208:     }
                   16209: 
1.992     raeburn  16210:     #
                   16211:     #  Given a DNS returns the loncapa host name for that DNS 
                   16212:     # 
                   16213:     sub host_from_dns {
                   16214:         my ($dns) = @_;
                   16215:         my @hosts;
                   16216:         my $ip;
                   16217: 
1.993     raeburn  16218:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  16219:             $ip = $name_to_ip{$dns};
                   16220:         }
                   16221:         if (!$ip) {
                   16222:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   16223:             if (length($ip) == 4) { 
                   16224: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   16225:             }
                   16226:         }
                   16227:         if ($ip) {
                   16228: 	    @hosts = get_hosts_from_ip($ip);
                   16229: 	    return $hosts[0];
                   16230:         }
                   16231:         return undef;
1.986     foxr     16232:     }
1.992     raeburn  16233: 
1.1074    raeburn  16234:     sub get_internet_names {
                   16235:         my ($lonid) = @_;
                   16236:         return if ($lonid eq '');
                   16237:         my ($idnref,$cached)=
1.1494    raeburn  16238:             &is_cached_new('internetnames',$lonid);
1.1074    raeburn  16239:         if ($cached) {
                   16240:             return $idnref;
                   16241:         }
                   16242:         my $ip = &get_host_ip($lonid);
                   16243:         my @hosts = &get_hosts_from_ip($ip);
                   16244:         my %iphost = &get_iphost();
                   16245:         my (@idns,%seen);
                   16246:         foreach my $id (@hosts) {
                   16247:             my $dom = &host_domain($id);
                   16248:             my $prim_id = &domain($dom,'primary');
                   16249:             my $prim_ip = &get_host_ip($prim_id);
                   16250:             next if ($seen{$prim_ip});
                   16251:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   16252:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   16253:                     my $intdom = &internet_dom($id);
                   16254:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   16255:                         push(@idns,$intdom);
                   16256:                     }
                   16257:                 }
                   16258:             }
                   16259:             $seen{$prim_ip} = 1;
                   16260:         }
1.1219    raeburn  16261:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  16262:     }
                   16263: 
1.986     foxr     16264: }
                   16265: 
1.1079    raeburn  16266: sub all_loncaparevs {
1.1249    raeburn  16267:     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  16268: }
                   16269: 
1.1227    raeburn  16270: # ---------------------------------------------------------- Read loncaparev table
                   16271: {
                   16272:     sub load_loncaparevs { 
                   16273:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  16274:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  16275:                 while (my $configline=<$config>) {
                   16276:                     chomp($configline);
                   16277:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   16278:                     $loncaparevs{$hostid}=$loncaparev;
                   16279:                 }
                   16280:                 close($config);
                   16281:             }
                   16282:         }
                   16283:     }
                   16284: }
                   16285: 
                   16286: # ---------------------------------------------------------- Read serverhostID table
                   16287: {
                   16288:     sub load_serverhomeIDs {
                   16289:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  16290:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  16291:                 while (my $configline=<$config>) {
                   16292:                     chomp($configline);
                   16293:                     my ($name,$id)=split(/:/,$configline);
                   16294:                     $serverhomeIDs{$name}=$id;
                   16295:                 }
                   16296:                 close($config);
                   16297:             }
                   16298:         }
                   16299:     }
                   16300: }
                   16301: 
                   16302: 
1.862     albertel 16303: BEGIN {
                   16304: 
                   16305: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   16306:     unless ($readit) {
                   16307: {
                   16308:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   16309:     %perlvar = (%perlvar,%{$configvars});
                   16310: }
                   16311: 
                   16312: 
1.1       albertel 16313: # ------------------------------------------------------ Read spare server file
                   16314: {
1.1359    raeburn  16315:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 16316: 
                   16317:     while (my $configline=<$config>) {
                   16318:        chomp($configline);
1.284     matthew  16319:        if ($configline) {
1.784     albertel 16320: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 16321: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 16322: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 16323:        }
                   16324:     }
1.448     albertel 16325:     close($config);
1.1       albertel 16326: }
1.11      www      16327: # ------------------------------------------------------------ Read permissions
                   16328: {
1.1359    raeburn  16329:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      16330: 
                   16331:     while (my $configline=<$config>) {
1.448     albertel 16332: 	chomp($configline);
                   16333: 	if ($configline) {
                   16334: 	    my ($role,$perm)=split(/ /,$configline);
                   16335: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   16336: 	}
1.11      www      16337:     }
1.448     albertel 16338:     close($config);
1.11      www      16339: }
                   16340: 
                   16341: # -------------------------------------------- Read plain texts for permissions
                   16342: {
1.1359    raeburn  16343:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      16344: 
                   16345:     while (my $configline=<$config>) {
1.448     albertel 16346: 	chomp($configline);
                   16347: 	if ($configline) {
1.742     raeburn  16348: 	    my ($short,@plain)=split(/:/,$configline);
                   16349:             %{$prp{$short}} = ();
                   16350: 	    if (@plain > 0) {
                   16351:                 $prp{$short}{'std'} = $plain[0];
                   16352:                 for (my $i=1; $i<@plain; $i++) {
                   16353:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   16354:                 }
                   16355:             }
1.448     albertel 16356: 	}
1.135     www      16357:     }
1.448     albertel 16358:     close($config);
1.135     www      16359: }
                   16360: 
                   16361: # ---------------------------------------------------------- Read package table
                   16362: {
1.1359    raeburn  16363:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      16364: 
                   16365:     while (my $configline=<$config>) {
1.483     albertel 16366: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 16367: 	chomp($configline);
                   16368: 	my ($short,$plain)=split(/:/,$configline);
                   16369: 	my ($pack,$name)=split(/\&/,$short);
                   16370: 	if ($plain ne '') {
                   16371: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   16372: 	    $packagetab{$short}=$plain; 
                   16373: 	}
1.11      www      16374:     }
1.448     albertel 16375:     close($config);
1.329     matthew  16376: }
                   16377: 
1.1073    raeburn  16378: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  16379: 
                   16380: &load_loncaparevs();
1.1073    raeburn  16381: 
1.1074    raeburn  16382: # ---------------------------------------------------------- Read serverhostID table
                   16383: 
1.1227    raeburn  16384: &load_serverhomeIDs();
                   16385: 
                   16386: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  16387: {
                   16388:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   16389:     if (-e $file) {
                   16390:         my $parser = HTML::LCParser->new($file);
                   16391:         while (my $token = $parser->get_token()) {
                   16392:             if ($token->[0] eq 'S') {
                   16393:                 my $item = $token->[1];
                   16394:                 my $name = $token->[2]{'name'};
                   16395:                 my $value = $token->[2]{'value'};
1.1285    raeburn  16396:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  16397:                 my $namematch = $token->[2]{'namematch'};
                   16398:                 if ($item eq 'parameter') {
                   16399:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   16400:                         my $release = $parser->get_text();
                   16401:                         $release =~ s/(^\s*|\s*$ )//gx;
                   16402:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   16403:                     }
                   16404:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  16405:                     my $release = $parser->get_text();
                   16406:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  16407:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  16408:                 }
                   16409:             }
                   16410:         }
                   16411:     }
1.1073    raeburn  16412: }
                   16413: 
1.1138    raeburn  16414: # ---------------------------------------------------------- Read managers table
                   16415: {
                   16416:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  16417:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  16418:             while (my $configline=<$config>) {
                   16419:                 chomp($configline);
                   16420:                 next if ($configline =~ /^\#/);
                   16421:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   16422:                     $managerstab{$configline} = 1;
                   16423:                 }
                   16424:             }
                   16425:             close($config);
                   16426:         }
                   16427:     }
                   16428: }
                   16429: 
1.329     matthew  16430: # ------------- set up temporary directory
                   16431: {
1.1117    foxr     16432:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  16433: 
1.11      www      16434: }
                   16435: 
1.1405    raeburn  16436: # ------------- set default texengine (domain default overrides this)
                   16437: {
                   16438:     $deftex = LONCAPA::texengine();
                   16439: }
                   16440: 
1.1416    raeburn  16441: # ------------- set default minimum length for passwords for internal auth users
                   16442: {
                   16443:     $passwdmin = LONCAPA::passwd_min();
                   16444: }
                   16445: 
1.794     albertel 16446: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   16447: 				'compress_threshold'=> 20_000,
                   16448:  			        });
1.185     www      16449: 
1.281     www      16450: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      16451: $dumpcount=0;
1.958     www      16452: $locknum=0;
1.22      www      16453: 
1.163     harris41 16454: &logtouch();
1.672     albertel 16455: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      16456: $readit=1;
1.564     albertel 16457:     {
                   16458: 	use integer;
                   16459: 	my $test=(2**32)+1;
1.568     albertel 16460: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 16461: 	&logthis(" Detected 64bit platform ($_64bit)");
                   16462:     }
1.195     www      16463: }
1.1       albertel 16464: }
1.179     www      16465: 
1.1       albertel 16466: 1;
1.191     harris41 16467: __END__
                   16468: 
1.243     albertel 16469: =pod
                   16470: 
1.191     harris41 16471: =head1 NAME
                   16472: 
1.243     albertel 16473: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 16474: 
                   16475: =head1 SYNOPSIS
                   16476: 
1.243     albertel 16477: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 16478: 
                   16479:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   16480: 
1.243     albertel 16481: Common parameters:
                   16482: 
                   16483: =over 4
                   16484: 
                   16485: =item *
                   16486: 
                   16487: $uname : an internal username (if $cname expecting a course Id specifically)
                   16488: 
                   16489: =item *
                   16490: 
                   16491: $udom : a domain (if $cdom expecting a course's domain specifically)
                   16492: 
                   16493: =item *
                   16494: 
                   16495: $symb : a resource instance identifier
                   16496: 
                   16497: =item *
                   16498: 
                   16499: $namespace : the name of a .db file that contains the data needed or
                   16500: being set.
                   16501: 
                   16502: =back
                   16503: 
1.394     bowersj2 16504: =head1 OVERVIEW
1.191     harris41 16505: 
1.394     bowersj2 16506: lonnet provides subroutines which interact with the
                   16507: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   16508: about classes, users, and resources.
1.243     albertel 16509: 
                   16510: For many of these objects you can also use this to store data about
                   16511: them or modify them in various ways.
1.191     harris41 16512: 
1.394     bowersj2 16513: =head2 Symbs
1.191     harris41 16514: 
1.394     bowersj2 16515: To identify a specific instance of a resource, LON-CAPA uses symbols
                   16516: or "symbs"X<symb>. These identifiers are built from the URL of the
                   16517: map, the resource number of the resource in the map, and the URL of
                   16518: the resource itself. The latter is somewhat redundant, but might help
                   16519: if maps change.
                   16520: 
                   16521: An example is
                   16522: 
                   16523:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   16524: 
                   16525: The respective map entry is
                   16526: 
                   16527:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   16528:   title="Problem 2">
                   16529:  </resource>
                   16530: 
                   16531: Symbs are used by the random number generator, as well as to store and
                   16532: restore data specific to a certain instance of for example a problem.
                   16533: 
                   16534: =head2 Storing And Retrieving Data
                   16535: 
                   16536: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   16537: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   16538: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   16539: is is the non-critical message twin of cstore. These functions are for
                   16540: handlers to store a perl hash to a user's permanent data space in an
                   16541: easy manner, and to retrieve it again on another call. It is expected
                   16542: that a handler would use this once at the beginning to retrieve data,
                   16543: and then again once at the end to send only the new data back.
                   16544: 
                   16545: The data is stored in the user's data directory on the user's
                   16546: homeserver under the ID of the course.
                   16547: 
                   16548: The hash that is returned by restore will have all of the previous
                   16549: value for all of the elements of the hash.
                   16550: 
                   16551: Example:
                   16552: 
                   16553:  #creating a hash
                   16554:  my %hash;
                   16555:  $hash{'foo'}='bar';
                   16556: 
                   16557:  #storing it
                   16558:  &Apache::lonnet::cstore(\%hash);
                   16559: 
                   16560:  #changing a value
                   16561:  $hash{'foo'}='notbar';
                   16562: 
                   16563:  #adding a new value
                   16564:  $hash{'bar'}='foo';
                   16565:  &Apache::lonnet::cstore(\%hash);
                   16566: 
                   16567:  #retrieving the hash
                   16568:  my %history=&Apache::lonnet::restore();
                   16569: 
                   16570:  #print the hash
                   16571:  foreach my $key (sort(keys(%history))) {
                   16572:    print("\%history{$key} = $history{$key}");
                   16573:  }
                   16574: 
                   16575: Will print out:
1.191     harris41 16576: 
1.394     bowersj2 16577:  %history{1:foo} = bar
                   16578:  %history{1:keys} = foo:timestamp
                   16579:  %history{1:timestamp} = 990455579
                   16580:  %history{2:bar} = foo
                   16581:  %history{2:foo} = notbar
                   16582:  %history{2:keys} = foo:bar:timestamp
                   16583:  %history{2:timestamp} = 990455580
                   16584:  %history{bar} = foo
                   16585:  %history{foo} = notbar
                   16586:  %history{timestamp} = 990455580
                   16587:  %history{version} = 2
                   16588: 
                   16589: Note that the special hash entries C<keys>, C<version> and
                   16590: C<timestamp> were added to the hash. C<version> will be equal to the
                   16591: total number of versions of the data that have been stored. The
                   16592: C<timestamp> attribute will be the UNIX time the hash was
                   16593: stored. C<keys> is available in every historical section to list which
                   16594: keys were added or changed at a specific historical revision of a
                   16595: hash.
                   16596: 
                   16597: B<Warning>: do not store the hash that restore returns directly. This
                   16598: will cause a mess since it will restore the historical keys as if the
                   16599: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 16600: 
1.394     bowersj2 16601: Calling convention:
1.191     harris41 16602: 
1.1225    raeburn  16603:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  16604:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 16605: 
1.394     bowersj2 16606: For more detailed information, see lonnet specific documentation.
1.191     harris41 16607: 
1.394     bowersj2 16608: =head1 RETURN MESSAGES
1.191     harris41 16609: 
1.394     bowersj2 16610: =over 4
1.191     harris41 16611: 
1.394     bowersj2 16612: =item * B<con_lost>: unable to contact remote host
1.191     harris41 16613: 
1.394     bowersj2 16614: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   16615: when the connection is brought back up
1.191     harris41 16616: 
1.394     bowersj2 16617: =item * B<con_failed>: unable to contact remote host and unable to save message
                   16618: for later delivery
1.191     harris41 16619: 
1.967     bisitz   16620: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 16621: 
1.394     bowersj2 16622: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 16623: that was requested
1.191     harris41 16624: 
1.243     albertel 16625: =back
1.191     harris41 16626: 
1.243     albertel 16627: =head1 PUBLIC SUBROUTINES
1.191     harris41 16628: 
1.243     albertel 16629: =head2 Session Environment Functions
1.191     harris41 16630: 
1.243     albertel 16631: =over 4
1.191     harris41 16632: 
1.394     bowersj2 16633: =item * 
                   16634: X<appenv()>
1.949     raeburn  16635: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 16636: the user envirnoment file, and will be restored for each access this
1.620     albertel 16637: user makes during this session, also modifies the %env for the current
1.949     raeburn  16638: process. Optional rolesarrayref - if defined contains a reference to an array
                   16639: of roles which are exempt from the restriction on modifying user.role entries 
                   16640: in the user's environment.db and in %env.    
1.191     harris41 16641: 
                   16642: =item *
1.394     bowersj2 16643: X<delenv()>
1.987     raeburn  16644: B<delenv($delthis,$regexp)>: removes all items from the session
                   16645: environment file that begin with $delthis. If the 
                   16646: optional second arg - $regexp - is true, $delthis is treated as a 
                   16647: regular expression, otherwise \Q$delthis\E is used. 
                   16648: The values are also deleted from the current processes %env.
1.191     harris41 16649: 
1.795     albertel 16650: =item * get_env_multiple($name) 
                   16651: 
                   16652: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   16653: values may be defined and end up as an array ref.
                   16654: 
                   16655: returns an array of values
                   16656: 
1.243     albertel 16657: =back
                   16658: 
                   16659: =head2 User Information
1.191     harris41 16660: 
1.243     albertel 16661: =over 4
1.191     harris41 16662: 
                   16663: =item *
1.394     bowersj2 16664: X<queryauthenticate()>
                   16665: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 16666: authentication scheme
                   16667: 
                   16668: =item *
1.394     bowersj2 16669: X<authenticate()>
1.1073    raeburn  16670: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 16671: authenticate user from domain's lib servers (first use the current
                   16672: one). C<$upass> should be the users password.
1.1073    raeburn  16673: $checkdefauth is optional (value is 1 if a check should be made to
                   16674:    authenticate user using default authentication method, and allow
                   16675:    account creation if username does not have account in the domain).
                   16676: $clientcancheckhost is optional (value is 1 if checking whether the
                   16677:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 16678: 
                   16679: =item *
1.394     bowersj2 16680: X<homeserver()>
                   16681: B<homeserver($uname,$udom)>: find the server which has
                   16682: the user's directory and files (there must be only one), this caches
                   16683: the answer, and also caches if there is a borken connection.
1.191     harris41 16684: 
                   16685: =item *
1.394     bowersj2 16686: X<idget()>
1.1300    raeburn  16687: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   16688: a list of student/employee IDs or clicker IDs
                   16689: (student/employee IDs are a unique resource in a domain, there must be 
                   16690: only 1 ID per username, and only 1 username per ID in a specific domain).
                   16691: clickerIDs are not necessarily unique, as students might share clickers.
                   16692: (returns hash: id=>name,id=>name)
1.191     harris41 16693: 
                   16694: =item *
1.394     bowersj2 16695: X<idrget()>
                   16696: B<idrget($udom,@unames)>: find the IDs behind a list of
                   16697: usernames (returns hash: name=>id,name=>id)
1.191     harris41 16698: 
                   16699: =item *
1.394     bowersj2 16700: X<idput()>
1.1300    raeburn  16701: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   16702: names and associated student/employee IDs or clicker IDs.
                   16703: 
                   16704: =item *
                   16705: X<iddel()>
                   16706: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   16707: student/employee ID or clicker ID username look-ups from domain.
                   16708: The homeserver ($uhome) and namespace ($namespace) are optional.
                   16709: If no $uhome is provided, it will be determined usig &homeserver()
                   16710: for each user.  If no $namespace is provided, the default is ids.
                   16711: 
                   16712: =item *
                   16713: X<updateclickers()>
                   16714: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   16715: clicker ID-to-username look-ups in clickers.db on library server.
                   16716: Permitted actions are add or del (i.e., add or delete). The 
                   16717: clickers.db contains clickerID as keys (escaped), and each corresponding
                   16718: value is an escaped comma-separated list of usernames (for whom the
                   16719: library server is the homeserver), who registered that particular ID.
                   16720: If $critical is true, the update will be sent via &critical, otherwise
                   16721: &reply() will be used.
1.191     harris41 16722: 
                   16723: =item *
1.394     bowersj2 16724: X<rolesinit()>
1.1169    droeschl 16725: B<rolesinit($udom,$username)>: get user privileges.
                   16726: returns user role, first access and timer interval hashes
1.243     albertel 16727: 
                   16728: =item *
1.1171    droeschl 16729: X<privileged()>
                   16730: B<privileged($username,$domain)>: returns a true if user has a
                   16731: privileged and active role (i.e. su or dc), false otherwise.
                   16732: 
                   16733: =item *
1.551     albertel 16734: X<getsection()>
                   16735: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 16736: course $cname, return section name/number or '' for "not in course"
                   16737: and '-1' for "no section"
                   16738: 
                   16739: =item *
1.394     bowersj2 16740: X<userenvironment()>
                   16741: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 16742: passed in @what from the requested user's environment, returns a hash
                   16743: 
1.858     raeburn  16744: =item * 
                   16745: X<userlog_query()>
1.859     albertel 16746: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   16747: activity.log file. %filters defines filters applied when parsing the
                   16748: log file. These can be start or end timestamps, or the type of action
                   16749: - log to look for Login or Logout events, check for Checkin or
                   16750: Checkout, role for role selection. The response is in the form
                   16751: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   16752: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  16753: 
1.243     albertel 16754: =back
                   16755: 
                   16756: =head2 User Roles
                   16757: 
                   16758: =over 4
                   16759: 
                   16760: =item *
                   16761: 
1.1284    raeburn  16762: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   16763: returns codes for allowed actions.
                   16764: 
                   16765: The first argument is required, all others are optional.
                   16766: 
                   16767: $priv is the privilege being checked.
                   16768: $uri contains additional information about what is being checked for access (e.g.,
                   16769: URL, course ID etc.). 
                   16770: $symb is the unique resource instance identifier in a course; if needed,
                   16771: but not provided, it will be retrieved via a call to &symbread(). 
                   16772: $role is the role for which a priv is being checked (only used if priv is evb). 
                   16773: $clientip is the user's IP address (only used when checking for access to portfolio 
                   16774: files).
                   16775: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   16776: prevents recursive calls to &allowed.
                   16777: 
1.243     albertel 16778:  F: full access
                   16779:  U,I,K: authentication modes (cxx only)
                   16780:  '': forbidden
                   16781:  1: user needs to choose course
                   16782:  2: browse allowed
1.766     albertel 16783:  A: passphrase authentication needed
1.1284    raeburn  16784:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  16785:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 16786: 
                   16787: =item *
                   16788: 
1.1192    raeburn  16789: constructaccess($url,$setpriv) : check for access to construction space URL
                   16790: 
                   16791: See if the owner domain and name in the URL match those in the
                   16792: expected environment.  If so, return three element list
                   16793: ($ownername,$ownerdomain,$ownerhome).
                   16794: 
                   16795: Otherwise return the null string.
                   16796: 
                   16797: If second argument 'setpriv' is true, it assigns the privileges,
                   16798: and returns the same three element list, unless the owner has
                   16799: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   16800: in which case the null string is returned.
                   16801: 
                   16802: =item *
                   16803: 
1.1326    raeburn  16804: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   16805: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   16806: for system, domain, and course level. $uname and $udom are optional (current
                   16807: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 16808: 
                   16809: =item *
                   16810: 
1.988     raeburn  16811: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   16812: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  16813: $type is Course (default) or Community.
1.988     raeburn  16814: If $forcedefault evaluates to true, text returned will be default 
                   16815: text for $type. Otherwise, if this is a course, the text returned 
                   16816: will be a custom name for the role (if defined in the course's 
                   16817: environment).  If no custom name is defined the default is returned.
                   16818:    
1.832     raeburn  16819: =item *
                   16820: 
1.1219    raeburn  16821: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  16822: All arguments are optional. Returns a hash of a roles, either for
                   16823: co-author/assistant author roles for a user's Construction Space
1.906     albertel 16824: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  16825: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   16826: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   16827: For each key, value is set to colon-separated start and end times for
                   16828: the role.  If no username and domain are specified, will default to
1.934     raeburn  16829: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  16830: of role statuses (active, future or previous), roles 
                   16831: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   16832: to restrict the list of roles reported. If no array ref is 
                   16833: provided for types, will default to return only active roles.
1.834     albertel 16834: 
1.1195    raeburn  16835: =item *
                   16836: 
                   16837: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  16838: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   16839: 
                   16840: Additional optional arguments are: $type (if role checking is to be restricted 
                   16841: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  16842: available roles) or future (roles available in the future), and
                   16843: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  16844: have active Domain Coordinator role in course's domain or in additional
                   16845: domains (specified in 'Domains to check for privileged users' in course
                   16846: environment -- set via:  Course Settings -> Classlists and staff listing).
                   16847: 
                   16848: =item *
                   16849: 
                   16850: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   16851: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   16852: $possdomains and $possroles are optional array refs -- to domains to check and
                   16853: roles to check.  If $possdomains is not specified, a dump will be done of the
                   16854: users' roles.db to check for a dc or su role in any domain. This can be
                   16855: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   16856: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   16857: this then allows &privileged_by_domain() to be used, which caches the identity
                   16858: of privileged users, eliminating the need for repeated calls to &dump().
                   16859: 
                   16860: =item *
                   16861: 
                   16862: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   16863: where the outer hash keys are domains specified in the $possdomains array ref,
                   16864: next inner hash keys are privileged roles specified in the $roles array ref,
                   16865: and the innermost hash contains key = value pairs for username:domain = end:start
                   16866: for active or future "privileged" users with that role in that domain. To avoid
                   16867: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   16868: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  16869: 
1.243     albertel 16870: =back
                   16871: 
                   16872: =head2 User Modification
                   16873: 
                   16874: =over 4
                   16875: 
                   16876: =item *
                   16877: 
1.957     raeburn  16878: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 16879: user for the level given by URL.  Optional start and end dates (leave empty
                   16880: string or zero for "no date")
1.191     harris41 16881: 
                   16882: =item *
                   16883: 
1.243     albertel 16884: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   16885: change a users, password, possible return values are: ok,
                   16886: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   16887: refused
1.191     harris41 16888: 
                   16889: =item *
                   16890: 
1.243     albertel 16891: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 16892: 
                   16893: =item *
                   16894: 
1.1058    raeburn  16895: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   16896:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   16897: 
                   16898: will update user information (firstname,middlename,lastname,generation,
                   16899: permanentemail), and if forceid is true, student/employee ID also.
                   16900: A user's institutional affiliation(s) can also be updated.
                   16901: User information fields will not be overwritten with empty entries 
                   16902: unless the field is included in the $candelete array reference.
                   16903: This array is included when a single user is modified via "Manage Users",
                   16904: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 16905: 
                   16906: =item *
                   16907: 
1.286     matthew  16908: modifystudent
                   16909: 
1.957     raeburn  16910: modify a student's enrollment and identification information.
1.1235    raeburn  16911: The course id is resolved based on the current user's environment.  
                   16912: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  16913: associated with a course.
                   16914: 
1.297     matthew  16915: This call is essentially a wrapper for lonnet::modifyuser and
                   16916: lonnet::modify_student_enrollment
1.286     matthew  16917: 
                   16918: Inputs: 
                   16919: 
                   16920: =over 4
                   16921: 
1.957     raeburn  16922: =item B<$udom> Student's loncapa domain
1.286     matthew  16923: 
1.957     raeburn  16924: =item B<$uname> Student's loncapa login name
1.286     matthew  16925: 
1.964     bisitz   16926: =item B<$uid> Student/Employee ID
1.286     matthew  16927: 
1.957     raeburn  16928: =item B<$umode> Student's authentication mode
1.286     matthew  16929: 
1.957     raeburn  16930: =item B<$upass> Student's password
1.286     matthew  16931: 
1.957     raeburn  16932: =item B<$first> Student's first name
1.286     matthew  16933: 
1.957     raeburn  16934: =item B<$middle> Student's middle name
1.286     matthew  16935: 
1.957     raeburn  16936: =item B<$last> Student's last name
1.286     matthew  16937: 
1.957     raeburn  16938: =item B<$gene> Student's generation
1.286     matthew  16939: 
1.957     raeburn  16940: =item B<$usec> Student's section in course
1.286     matthew  16941: 
                   16942: =item B<$end> Unix time of the roles expiration
                   16943: 
                   16944: =item B<$start> Unix time of the roles start date
                   16945: 
                   16946: =item B<$forceid> If defined, allow $uid to be changed
                   16947: 
                   16948: =item B<$desiredhome> server to use as home server for student
                   16949: 
1.957     raeburn  16950: =item B<$email> Student's permanent e-mail address
                   16951: 
                   16952: =item B<$type> Type of enrollment (auto or manual)
                   16953: 
1.963     raeburn  16954: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   16955: 
                   16956: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  16957: 
1.963     raeburn  16958: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  16959: 
1.963     raeburn  16960: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  16961: 
1.1216    raeburn  16962: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   16963: 
                   16964: =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  16965: 
1.286     matthew  16966: =back
1.297     matthew  16967: 
                   16968: =item *
                   16969: 
                   16970: modify_student_enrollment
                   16971: 
1.1235    raeburn  16972: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  16973: 'role.request.course' must be defined for this function to proceed.
                   16974: 
                   16975: Inputs:
                   16976: 
                   16977: =over 4
                   16978: 
1.1235    raeburn  16979: =item $udom, student's domain
1.297     matthew  16980: 
1.1235    raeburn  16981: =item $uname, student's name
1.297     matthew  16982: 
1.1235    raeburn  16983: =item $uid, student's user id
1.297     matthew  16984: 
1.1235    raeburn  16985: =item $first, student's first name
1.297     matthew  16986: 
                   16987: =item $middle
                   16988: 
                   16989: =item $last
                   16990: 
                   16991: =item $gene
                   16992: 
                   16993: =item $usec
                   16994: 
                   16995: =item $end
                   16996: 
                   16997: =item $start
                   16998: 
1.957     raeburn  16999: =item $type
                   17000: 
                   17001: =item $locktype
                   17002: 
                   17003: =item $cid
                   17004: 
                   17005: =item $selfenroll
                   17006: 
                   17007: =item $context
                   17008: 
1.1216    raeburn  17009: =item $credits, number of credits student will earn from this class
                   17010: 
1.1314    raeburn  17011: =item $instsec, institutional course section code for student
                   17012: 
1.297     matthew  17013: =back
                   17014: 
1.191     harris41 17015: 
                   17016: =item *
                   17017: 
1.243     albertel 17018: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   17019: custom role; give a custom role to a user for the level given by URL.  Specify
                   17020: name and domain of role author, and role name
1.191     harris41 17021: 
                   17022: =item *
                   17023: 
1.243     albertel 17024: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 17025: 
                   17026: =item *
                   17027: 
1.243     albertel 17028: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   17029: 
                   17030: =back
                   17031: 
                   17032: =head2 Course Infomation
                   17033: 
                   17034: =over 4
1.191     harris41 17035: 
                   17036: =item *
                   17037: 
1.1118    foxr     17038: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 17039: specified course id, including all environment settings for the
                   17040: course, the description of the course will be in the hash under the
                   17041: key 'description'
1.191     harris41 17042: 
1.1118    foxr     17043: $options is an optional parameter that if supplied is a hash reference that controls
                   17044: what how this function works.  It has the following key/values:
                   17045: 
                   17046: =over 4
                   17047: 
                   17048: =item freshen_cache
                   17049: 
                   17050: If defined, and the environment cache for the course is valid, it is 
                   17051: returned in the returned hash.
                   17052: 
                   17053: =item one_time
                   17054: 
                   17055: If defined, the last cache time is set to _now_
                   17056: 
                   17057: =item user
                   17058: 
                   17059: If defined, the supplied username is used instead of the current user.
                   17060: 
                   17061: 
                   17062: =back
                   17063: 
1.191     harris41 17064: =item *
                   17065: 
1.624     albertel 17066: resdata($name,$domain,$type,@which) : request for current parameter
                   17067: setting for a specific $type, where $type is either 'course' or 'user',
                   17068: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  17069: answers for 10 minutes.
1.243     albertel 17070: 
1.877     foxr     17071: =item *
                   17072: 
                   17073: get_courseresdata($courseid, $domain) : dump the entire course resource
                   17074: data base, returning a hash that is keyed by the resource name and has
                   17075: values that are the resource value.  I believe that the timestamps and
                   17076: versions are also returned.
                   17077: 
1.243     albertel 17078: =back
                   17079: 
                   17080: =head2 Course Modification
                   17081: 
                   17082: =over 4
1.191     harris41 17083: 
                   17084: =item *
                   17085: 
1.243     albertel 17086: writecoursepref($courseid,%prefs) : write preferences (environment
                   17087: database) for a course
1.191     harris41 17088: 
                   17089: =item *
                   17090: 
1.1011    raeburn  17091: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   17092: 
                   17093: =item *
                   17094: 
1.1038    raeburn  17095: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 17096: 
1.1167    droeschl 17097: =item *
                   17098: 
                   17099: is_course($courseid), is_course($cdom, $cnum)
                   17100: 
                   17101: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   17102: two component version $cdom, $cnum. It checks if the specified course exists.
                   17103: 
                   17104: Returns:
                   17105:     undef if the course doesn't exist, otherwise
                   17106:     in scalar context the combined courseid.
                   17107:     in list context the two components of the course identifier, domain and 
                   17108:     courseid.    
                   17109: 
1.243     albertel 17110: =back
                   17111: 
1.1401    raeburn  17112: =head2 Bubblesheet Configuration
                   17113: 
                   17114: =over 4
                   17115: 
                   17116: =item *
                   17117: 
                   17118: get_scantron_config($which)
                   17119: 
                   17120: $which - the name of the configuration to parse from the file.
                   17121: 
                   17122: Parses and returns the bubblesheet configuration line selected as a
                   17123: hash of configuration file fields.
                   17124: 
                   17125: 
                   17126: Returns:
                   17127:     If the named configuration is not in the file, an empty
                   17128:     hash is returned.
                   17129: 
                   17130:     a hash with the fields
                   17131:       name         - internal name for the this configuration setup
                   17132:       description  - text to display to operator that describes this config
                   17133:       CODElocation - if 0 or the string 'none'
                   17134:                           - no CODE exists for this config
                   17135:                      if -1 || the string 'letter'
                   17136:                           - a CODE exists for this config and is
                   17137:                             a string of letters
                   17138:                      Unsupported value (but planned for future support)
                   17139:                           if a positive integer
                   17140:                                - The CODE exists as the first n items from
                   17141:                                  the question section of the form
                   17142:                           if the string 'number'
                   17143:                                - The CODE exists for this config and is
                   17144:                                  a string of numbers
                   17145:       CODEstart   - (only matter if a CODE exists) column in the line where
                   17146:                      the CODE starts
                   17147:       CODElength  - length of the CODE
                   17148:       IDstart     - column where the student/employee ID starts
                   17149:       IDlength    - length of the student/employee ID info
                   17150:       Qstart      - column where the information from the bubbled
                   17151:                     'questions' start
                   17152:       Qlength     - number of columns comprising a single bubble line from
                   17153:                     the sheet. (usually either 1 or 10)
                   17154:       Qon         - either a single character representing the character used
                   17155:                     to signal a bubble was chosen in the positional setup, or
                   17156:                     the string 'letter' if the letter of the chosen bubble is
                   17157:                     in the final, or 'number' if a number representing the
                   17158:                     chosen bubble is in the file (1->A 0->J)
                   17159:       Qoff        - the character used to represent that a bubble was
                   17160:                     left blank
                   17161:       PaperID     - if the scanning process generates a unique number for each
                   17162:                     sheet scanned the column that this ID number starts in
                   17163:       PaperIDlength - number of columns that comprise the unique ID number
                   17164:                       for the sheet of paper
                   17165:       FirstName   - column that the first name starts in
                   17166:       FirstNameLength - number of columns that the first name spans
                   17167:       LastName    - column that the last name starts in
                   17168:       LastNameLength - number of columns that the last name spans
                   17169:       BubblesPerRow - number of bubbles available in each row used to
                   17170:                       bubble an answer. (If not specified, 10 assumed).
                   17171: 
                   17172: 
                   17173: =item *
                   17174: 
                   17175: get_scantronformat_file($cdom)
                   17176: 
                   17177: $cdom - the course's domain (optional); if not supplied, uses
                   17178: domain for current $env{'request.course.id'}.
                   17179: 
                   17180: Returns an array containing lines from the scantron format file for
                   17181: the domain of the course.
                   17182: 
                   17183: If a url for a custom.tab file is listed in domain's configuration.db,
                   17184: lines are from this file.
                   17185: 
                   17186: Otherwise, if a default.tab has been published in RES space by the
                   17187: domainconfig user, lines are from this file.
                   17188: 
                   17189: Otherwise, fall back to getting lines from the legacy file on the
                   17190: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   17191: 
                   17192: =back
                   17193: 
1.243     albertel 17194: =head2 Resource Subroutines
                   17195: 
                   17196: =over 4
1.191     harris41 17197: 
                   17198: =item *
                   17199: 
1.243     albertel 17200: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 17201: 
                   17202: =item *
                   17203: 
1.243     albertel 17204: repcopy($filename) : subscribes to the requested file, and attempts to
                   17205: replicate from the owning library server, Might return
1.607     raeburn  17206: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   17207: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 17208: resource. Expects the local filesystem pathname
                   17209: (/home/httpd/html/res/....)
                   17210: 
                   17211: =back
                   17212: 
                   17213: =head2 Resource Information
                   17214: 
                   17215: =over 4
1.191     harris41 17216: 
                   17217: =item *
                   17218: 
1.1228    raeburn  17219: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   17220: and returns the value of a variety of different possible values,
                   17221: $varname should be a request string, and the other parameters can be
                   17222: used to specify who and what one is asking about. Ordinarily, $cid 
                   17223: does not need to be specified, as it is retrived from 
                   17224: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   17225: within lonuserstate::loadmap() when initializing a course, before
                   17226: $env{'request.course.id'} has been set, so it needs to be provided
                   17227: in that one case.
1.243     albertel 17228: 
                   17229: Possible values for $varname are environment.lastname (or other item
                   17230: from the envirnment hash), user.name (or someother aspect about the
                   17231: user), resource.0.maxtries (or some other part and parameter of a
                   17232: resource)
1.204     albertel 17233: 
                   17234: =item *
                   17235: 
1.243     albertel 17236: directcondval($number) : get current value of a condition; reads from a state
                   17237: string
1.204     albertel 17238: 
                   17239: =item *
                   17240: 
1.243     albertel 17241: condval($condidx) : value of condition index based on state
1.204     albertel 17242: 
                   17243: =item *
                   17244: 
1.1362    raeburn  17245: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 17246: resource's metadata, $what should be either a specific key, or either
                   17247: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  17248: packages that this resource currently uses, the last 3 arguments are 
                   17249: only used internally for recursive metadata.
                   17250: 
                   17251: the toolsymb is only used where the uri is for an external tool (for which
                   17252: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 17253: 
1.1371    raeburn  17254: this function automatically caches all requests except any made recursively
                   17255: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   17256: defined).
1.191     harris41 17257: 
                   17258: =item *
                   17259: 
1.243     albertel 17260: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   17261: network of library servers; returns file handle of where SQL and regex results
                   17262: will be stored for query
1.191     harris41 17263: 
                   17264: =item *
                   17265: 
1.1282    raeburn  17266: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   17267: return symbolic list entry (all arguments optional). 
                   17268: 
                   17269: Args: filename is the filename (including path) for the file for which a symb 
                   17270: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   17271: to check access status if more than one resource was found in the bighash 
                   17272: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   17273: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   17274: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   17275: cause possible symbs to be checked to determine if they are subject to content
                   17276: blocking, if so they will not be included as possible symbs; possibles is a
                   17277: ref to a hash, which, as a side effect, will be populated with all possible 
                   17278: symbs (content blocking not tested).
                   17279:  
1.243     albertel 17280: returns the data handle
1.191     harris41 17281: 
                   17282: =item *
                   17283: 
1.1190    raeburn  17284: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   17285: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 17286: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  17287: on failure, user must be in a course, as it assumes the existence of
                   17288: the course initial hash, and uses $env('request.course.id'}.  The third
                   17289: arg is an optional reference to a scalar.  If this arg is passed in the 
                   17290: call to symbverify, it will be set to 1 if the symb has been set to be 
                   17291: encrypted; otherwise it will be null.  
1.191     harris41 17292: 
                   17293: =item *
                   17294: 
1.243     albertel 17295: symbclean($symb) : removes versions numbers from a symb, returns the
                   17296: cleaned symb
1.191     harris41 17297: 
                   17298: =item *
                   17299: 
1.243     albertel 17300: is_on_map($uri) : checks if the $uri is somewhere on the current
                   17301: course map, user must be in a course for it to work.
1.191     harris41 17302: 
                   17303: =item *
                   17304: 
1.243     albertel 17305: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 17306: 
                   17307: =item *
                   17308: 
1.243     albertel 17309: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   17310: a random seed, all arguments are optional, if they aren't sent it uses the
                   17311: environment to derive them. Note: if symb isn't sent and it can't get one
                   17312: from &symbread it will use the current time as its return value
1.191     harris41 17313: 
                   17314: =item *
                   17315: 
1.243     albertel 17316: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   17317: unfakeable, receipt
1.191     harris41 17318: 
                   17319: =item *
                   17320: 
1.620     albertel 17321: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 17322: 
                   17323: =item *
                   17324: 
1.243     albertel 17325: countacc($url) : count the number of accesses to a given URL
1.191     harris41 17326: 
                   17327: =item *
                   17328: 
1.243     albertel 17329: 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 17330: 
                   17331: =item *
                   17332: 
1.243     albertel 17333: 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 17334: 
                   17335: =item *
                   17336: 
1.243     albertel 17337: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 17338: 
                   17339: =item *
                   17340: 
1.243     albertel 17341: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   17342: forcing spreadsheet to reevaluate the resource scores next time.
                   17343: 
1.1195    raeburn  17344: =item * 
                   17345: 
1.1196    raeburn  17346: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   17347: when viewing in course context.
1.1195    raeburn  17348: 
1.1196    raeburn  17349:  input: six args -- filename (decluttered), course number, course domain,
                   17350:                     url, symb (if registered) and group (if this is a 
                   17351:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  17352: 
1.1196    raeburn  17353:  output: array of five scalars --
1.1195    raeburn  17354:          $cfile -- url for file editing if editable on current server
                   17355:          $home -- homeserver of resource (i.e., for author if published,
                   17356:                                           or course if uploaded.).
                   17357:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  17358:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   17359:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  17360: 
                   17361: =item *
                   17362: 
                   17363: is_course_upload($file,$cnum,$cdom)
                   17364: 
                   17365: Used in course context to determine if current file was uploaded to 
                   17366: the course (i.e., would be found in /userfiles/docs on the course's 
                   17367: homeserver.
                   17368: 
                   17369:   input: 3 args -- filename (decluttered), course number and course domain.
                   17370:   output: boolean -- 1 if file was uploaded.
                   17371: 
1.243     albertel 17372: =back
                   17373: 
                   17374: =head2 Storing/Retreiving Data
                   17375: 
                   17376: =over 4
1.191     harris41 17377: 
                   17378: =item *
                   17379: 
1.1269    raeburn  17380: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   17381: permanently for this url; hashref needs to be given and should be a \%hashname;
                   17382: the remaining args aren't required and if they aren't passed or are '' they will
                   17383: be derived from the env (with the exception of $laststore, which is an 
                   17384: optional arg used when a user's submission is stored in grading).
                   17385: $laststore is $version=$timestamp, where $version is the most recent version
                   17386: number retrieved for the corresponding $symb in the $namespace db file, and
                   17387: $timestamp is the timestamp for that transaction (UNIX time).
                   17388: $laststore is currently only passed when cstore() is called by 
                   17389: structuretags::finalize_storage().
1.191     harris41 17390: 
                   17391: =item *
                   17392: 
1.1269    raeburn  17393: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   17394: but uses critical subroutine
1.191     harris41 17395: 
                   17396: =item *
                   17397: 
1.243     albertel 17398: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   17399: all args are optional
1.191     harris41 17400: 
                   17401: =item *
                   17402: 
1.717     albertel 17403: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   17404: dumps the complete (or key matching regexp) namespace into a hash
                   17405: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   17406: normally &store()ed into
                   17407: 
                   17408: $range should be either an integer '100' (give me the first 100
                   17409:                                            matching records)
                   17410:               or be  two integers sperated by a - with no spaces
                   17411:                  '30-50' (give me the 30th through the 50th matching
                   17412:                           records)
                   17413: 
                   17414: 
                   17415: =item *
                   17416: 
1.1269    raeburn  17417: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 17418: replaces a &store() version of data with a replacement set of data
                   17419: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  17420: reference. If $tolog is true, the transaction is logged in the courselog
                   17421: with an action=PUTSTORE.
1.717     albertel 17422: 
                   17423: =item *
                   17424: 
1.243     albertel 17425: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   17426: works very similar to store/cstore, but all data is stored in a
                   17427: temporary location and can be reset using tmpreset, $storehash should
                   17428: be a hash reference, returns nothing on success
1.191     harris41 17429: 
                   17430: =item *
                   17431: 
1.243     albertel 17432: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   17433: similar to restore, but all data is stored in a temporary location and
                   17434: can be reset using tmpreset. Returns a hash of values on success,
                   17435: error string otherwise.
1.191     harris41 17436: 
                   17437: =item *
                   17438: 
1.243     albertel 17439: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   17440: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 17441: 
                   17442: =item *
                   17443: 
1.243     albertel 17444: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   17445: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 17446: 
                   17447: =item *
                   17448: 
1.243     albertel 17449: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   17450: namesp ($udom and $uname are optional)
1.191     harris41 17451: 
                   17452: =item *
                   17453: 
1.702     albertel 17454: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 17455: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 17456: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  17457: 
1.702     albertel 17458: $range should be either an integer '100' (give me the first 100
                   17459:                                            matching records)
                   17460:               or be  two integers sperated by a - with no spaces
                   17461:                  '30-50' (give me the 30th through the 50th matching
                   17462:                           records)
1.449     matthew  17463: =item *
                   17464: 
                   17465: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   17466: $store can be a scalar, an array reference, or if the amount to be 
                   17467: incremented is > 1, a hash reference.
                   17468: 
                   17469: ($udom and $uname are optional)
1.191     harris41 17470: 
                   17471: =item *
                   17472: 
1.243     albertel 17473: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   17474: ($udom and $uname are optional)
1.191     harris41 17475: 
                   17476: =item *
                   17477: 
1.243     albertel 17478: cput($namespace,$storehash,$udom,$uname) : critical put
                   17479: ($udom and $uname are optional)
1.191     harris41 17480: 
                   17481: =item *
                   17482: 
1.748     albertel 17483: newput($namespace,$storehash,$udom,$uname) :
                   17484: 
                   17485: Attempts to store the items in the $storehash, but only if they don't
                   17486: currently exist, if this succeeds you can be certain that you have 
                   17487: successfully created a new key value pair in the $namespace db.
                   17488: 
                   17489: 
                   17490: Args:
                   17491:  $namespace: name of database to store values to
                   17492:  $storehash: hashref to store to the db
                   17493:  $udom: (optional) domain of user containing the db
                   17494:  $uname: (optional) name of user caontaining the db
                   17495: 
                   17496: Returns:
                   17497:  'ok' -> succeeded in storing all keys of $storehash
                   17498:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   17499:                         least <key> already existed in the db (other
                   17500:                         requested keys may also already exist)
1.967     bisitz   17501:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 17502:  'con_lost' -> unable to contact request server
                   17503:  'refused' -> action was not allowed by remote machine
                   17504: 
                   17505: 
                   17506: =item *
                   17507: 
1.243     albertel 17508: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   17509: reference filled in from namesp (encrypts the return communication)
                   17510: ($udom and $uname are optional)
1.191     harris41 17511: 
                   17512: =item *
                   17513: 
1.243     albertel 17514: log($udom,$name,$home,$message) : write to permanent log for user; use
                   17515: critical subroutine
                   17516: 
1.806     raeburn  17517: =item *
                   17518: 
1.860     raeburn  17519: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   17520: array reference filled in from namespace found in domain level on either
                   17521: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  17522: 
                   17523: =item *
                   17524: 
1.860     raeburn  17525: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   17526: domain level either on specified domain server ($uhome) or primary domain 
                   17527: server ($udom and $uhome are optional)
1.806     raeburn  17528: 
1.943     raeburn  17529: =item * 
                   17530: 
1.1240    raeburn  17531: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   17532: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   17533: the target domain.
                   17534: 
                   17535: May also include additional key => value pairs for the following groups:
                   17536: 
                   17537: =over
                   17538: 
                   17539: =item
                   17540: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   17541: 
                   17542: =over
                   17543: 
                   17544: =item defaultquota, authorquota
                   17545: 
                   17546: =back
                   17547: 
                   17548: =item
                   17549: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   17550: portfolio for users).
                   17551: 
                   17552: =over
                   17553: 
                   17554: =item
                   17555: aboutme, blog, webdav, portfolio
                   17556: 
                   17557: =back
                   17558: 
                   17559: =item
                   17560: requestcourses: ability to request courses, and how requests are processed.
                   17561: 
                   17562: =over
                   17563: 
                   17564: =item
1.1305    raeburn  17565: official, unofficial, community, textbook, placement
1.1240    raeburn  17566: 
                   17567: =back
                   17568: 
                   17569: =item
                   17570: inststatus: types of institutional affiliation, and order in which they are displayed.
                   17571: 
                   17572: =over
                   17573: 
                   17574: =item
1.1256    raeburn  17575: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  17576: 
                   17577: =back
                   17578: 
                   17579: =item
                   17580: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   17581: for course's uploaded content.
                   17582: 
                   17583: =over
                   17584: 
                   17585: =item
1.1246    raeburn  17586: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  17587: communityquota, textbookquota, placementquota
1.1240    raeburn  17588: 
                   17589: =back
                   17590: 
                   17591: =item
                   17592: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   17593: on your servers.
                   17594: 
                   17595: =over
                   17596: 
                   17597: =item 
                   17598: remotesessions, hostedsessions
                   17599: 
                   17600: =back
                   17601: 
                   17602: =back
                   17603: 
                   17604: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   17605: utility to create a configuration.db file on a domain's primary library server 
                   17606: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   17607: -- corresponding values are authentication type (internal, krb4, krb5,
                   17608: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   17609: will be available. Values are retrieved from cache (if current), unless the
                   17610: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   17611: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   17612: 
                   17613: Typical usage:
1.943     raeburn  17614: 
1.1240    raeburn  17615: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  17616: 
1.243     albertel 17617: =back
                   17618: 
                   17619: =head2 Network Status Functions
                   17620: 
                   17621: =over 4
1.191     harris41 17622: 
                   17623: =item *
                   17624: 
1.1137    raeburn  17625: dirlist() : return directory list based on URI (first arg).
                   17626: 
                   17627: Inputs: 1 required, 5 optional.
                   17628: 
                   17629: =over
                   17630: 
                   17631: =item 
                   17632: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   17633: 
                   17634: =item
                   17635: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   17636: 
                   17637: =item
                   17638: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   17639: 
                   17640: =item
                   17641: $getpropath - boolean: 1 if prepend path using &propath(). 
                   17642: 
                   17643: =item
                   17644: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   17645: 
                   17646: =item 
                   17647: $alternateRoot - path to prepend in place of path from $uri.
                   17648: 
                   17649: =back
                   17650: 
                   17651: Returns: Array of up to two items.
                   17652: 
                   17653: =over
                   17654: 
                   17655: a reference to an array of files/subdirectories
                   17656: 
                   17657: =over
                   17658: 
                   17659: Each element in the array of files/subdirectories is a & separated list of
                   17660: item name and the result of running stat on the item.  If dirlist was requested
                   17661: for a file instead of a directory, the item name will be ''. For a directory 
                   17662: listing, if the item is a metadata file, the element will end &N&M 
                   17663: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   17664: default copyright set (1).  
                   17665: 
                   17666: =back
                   17667: 
                   17668: a scalar containing error condition (if encountered).
                   17669: 
                   17670: =over
                   17671: 
                   17672: =item 
                   17673: no_host (no homeserver identified for $username:$domain).
                   17674: 
                   17675: =item 
                   17676: no_such_host (server contacted for listing not identified as valid host).
                   17677: 
                   17678: =item 
                   17679: con_lost (connection to remote server failed).
                   17680: 
                   17681: =item 
                   17682: refused (invalid $username:$domain received on lond side).
                   17683: 
                   17684: =item 
                   17685: no_such_dir (directory at specified path on lond side does not exist). 
                   17686: 
                   17687: =item 
                   17688: empty (directory at specified path on lond side is empty).
                   17689: 
                   17690: =over
                   17691: 
                   17692: This is currently not encountered because the &ls3, &ls2, 
                   17693: &ls (_handler) routines on the lond side do not filter out
                   17694: . and .. from a directory listing. 
                   17695: 
                   17696: =back
                   17697: 
                   17698: =back
                   17699: 
                   17700: =back
1.191     harris41 17701: 
                   17702: =item *
                   17703: 
1.243     albertel 17704: spareserver() : find server with least workload from spare.tab
                   17705: 
1.986     foxr     17706: 
                   17707: =item *
                   17708: 
                   17709: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   17710: if there is no corresponding loncapa host.
                   17711: 
1.243     albertel 17712: =back
                   17713: 
1.986     foxr     17714: 
1.243     albertel 17715: =head2 Apache Request
                   17716: 
                   17717: =over 4
1.191     harris41 17718: 
                   17719: =item *
                   17720: 
1.243     albertel 17721: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   17722: localhost, posts hash
                   17723: 
                   17724: =back
                   17725: 
                   17726: =head2 Data to String to Data
                   17727: 
                   17728: =over 4
1.191     harris41 17729: 
                   17730: =item *
                   17731: 
1.243     albertel 17732: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   17733: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 17734: 
                   17735: =item *
                   17736: 
1.243     albertel 17737: hashref2str($hashref) : convert a hashref into a string complete with
                   17738: escaping and '=' and '&' separators, supports elements that are
                   17739: arrayrefs and hashrefs
1.191     harris41 17740: 
                   17741: =item *
                   17742: 
1.243     albertel 17743: arrayref2str($arrayref) : convert an arrayref into a string complete
                   17744: with escaping and '&' separators, supports elements that are arrayrefs
                   17745: and hashrefs
1.191     harris41 17746: 
                   17747: =item *
                   17748: 
1.243     albertel 17749: str2hash($string) : convert string to hash using unescaping and
                   17750: splitting on '=' and '&', supports elements that are arrayrefs and
                   17751: hashrefs
1.191     harris41 17752: 
                   17753: =item *
                   17754: 
1.243     albertel 17755: str2array($string) : convert string to hash using unescaping and
                   17756: splitting on '&', supports elements that are arrayrefs and hashrefs
                   17757: 
                   17758: =back
                   17759: 
                   17760: =head2 Logging Routines
                   17761: 
                   17762: 
                   17763: These routines allow one to make log messages in the lonnet.log and
                   17764: lonnet.perm logfiles.
1.191     harris41 17765: 
1.1119    foxr     17766: =over 4
                   17767: 
1.191     harris41 17768: =item *
                   17769: 
1.243     albertel 17770: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 17771: 
                   17772: =item *
                   17773: 
1.243     albertel 17774: logthis() : append message to the normal lonnet.log file, it gets
                   17775: preiodically rolled over and deleted.
1.191     harris41 17776: 
                   17777: =item *
                   17778: 
1.243     albertel 17779: logperm() : append a permanent message to lonnet.perm.log, this log
                   17780: file never gets deleted by any automated portion of the system, only
                   17781: messages of critical importance should go in here.
                   17782: 
1.1119    foxr     17783: 
1.243     albertel 17784: =back
                   17785: 
                   17786: =head2 General File Helper Routines
                   17787: 
                   17788: =over 4
1.191     harris41 17789: 
                   17790: =item *
                   17791: 
1.481     raeburn  17792: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   17793: (a) files in /uploaded
                   17794:   (i) If a local copy of the file exists - 
                   17795:       compares modification date of local copy with last-modified date for 
                   17796:       definitive version stored on home server for course. If local copy is 
                   17797:       stale, requests a new version from the home server and stores it. 
                   17798:       If the original has been removed from the home server, then local copy 
                   17799:       is unlinked.
                   17800:   (ii) If local copy does not exist -
                   17801:       requests the file from the home server and stores it. 
                   17802:   
                   17803:   If $caller is 'uploadrep':  
                   17804:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   17805:     for request for files originally uploaded via DOCS. 
                   17806:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   17807:   
                   17808:   Otherwise:
                   17809:      This indicates a call from the content generation phase of the request.
                   17810:      -  returns the entire contents of the file or -1.
                   17811:      
                   17812: (b) files in /res
                   17813:    - returns the entire contents of a file or -1; 
                   17814:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 17815: 
1.712     albertel 17816: 
                   17817: =item *
                   17818: 
                   17819: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   17820:                   reference
                   17821: 
                   17822: returns either a stat() list of data about the file or an empty list
                   17823: if the file doesn't exist or couldn't find out about it (connection
                   17824: problems or user unknown)
                   17825: 
1.191     harris41 17826: =item *
                   17827: 
1.243     albertel 17828: filelocation($dir,$file) : returns file system location of a file
                   17829: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   17830: directory that relative $file lookups are to looked in ($dir of /a/dir
                   17831: and a file of ../bob will become /a/bob)
1.191     harris41 17832: 
                   17833: =item *
                   17834: 
                   17835: hreflocation($dir,$file) : returns file system location or a URL; same as
                   17836: filelocation except for hrefs
                   17837: 
                   17838: =item *
                   17839: 
1.1261    raeburn  17840: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   17841: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 17842: 
1.243     albertel 17843: =back
                   17844: 
1.608     albertel 17845: =head2 Usererfile file routines (/uploaded*)
                   17846: 
                   17847: =over 4
                   17848: 
                   17849: =item *
                   17850: 
                   17851: userfileupload(): main rotine for putting a file in a user or course's
                   17852:                   filespace, arguments are,
                   17853: 
1.620     albertel 17854:  formname - required - this is the name of the element in $env where the
1.608     albertel 17855:            filename, and the contents of the file to create/modifed exist
1.620     albertel 17856:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   17857:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  17858:  context - if coursedoc, store the file in the course of the active role
                   17859:              of the current user; 
                   17860:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   17861:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 17862:  subdir - required - subdirectory to put the file in under ../userfiles/
                   17863:          if undefined, it will be placed in "unknown"
                   17864: 
                   17865:  (This routine calls clean_filename() to remove any dangerous
                   17866:  characters from the filename, and then calls finuserfileupload() to
                   17867:  complete the transaction)
                   17868: 
                   17869:  returns either the url of the uploaded file (/uploaded/....) if successful
                   17870:  and /adm/notfound.html if unsuccessful
                   17871: 
                   17872: =item *
                   17873: 
                   17874: clean_filename(): routine for cleaing a filename up for storage in
                   17875:                  userfile space, argument is:
                   17876: 
                   17877:  filename - proposed filename
                   17878: 
                   17879: returns: the new clean filename
                   17880: 
                   17881: =item *
                   17882: 
1.1090    raeburn  17883: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 17884: userspace, probably shouldn't be called directly
                   17885: 
                   17886:   docuname: username or courseid of destination for the file
                   17887:   docudom: domain of user/course of destination for the file
                   17888:   formname: same as for userfileupload()
1.1090    raeburn  17889:   fname: filename (including subdirectories) for the file
                   17890:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  17891:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  17892:   allfiles: reference to hash used to store objects found by parser
                   17893:   codebase: reference to hash used for codebases of java objects found by parser
                   17894:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   17895:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   17896:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   17897:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   17898:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   17899:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  17900:   mimetype: reference to scalar to accommodate mime type determined
                   17901:             from File::MMagic if $parser = parse.
1.608     albertel 17902: 
                   17903:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  17904:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   17905:  was 'overwrite').
                   17906:  
1.608     albertel 17907: 
                   17908: =item *
                   17909: 
                   17910: renameuserfile(): renames an existing userfile to a new name
                   17911: 
                   17912:   Args:
                   17913:    docuname: username or courseid of destination for the file
                   17914:    docudom: domain of user/course of destination for the file
                   17915:    old: current file name (including any subdirs under userfiles)
                   17916:    new: desired file name (including any subdirs under userfiles)
                   17917: 
                   17918: =item *
                   17919: 
                   17920: mkdiruserfile(): creates a directory is a userfiles dir
                   17921: 
                   17922:   Args:
                   17923:    docuname: username or courseid of destination for the file
                   17924:    docudom: domain of user/course of destination for the file
                   17925:    dir: dir to create (including any subdirs under userfiles)
                   17926: 
                   17927: =item *
                   17928: 
                   17929: removeuserfile(): removes a file that exists in userfiles
                   17930: 
                   17931:   Args:
                   17932:    docuname: username or courseid of destination for the file
                   17933:    docudom: domain of user/course of destination for the file
                   17934:    fname: filname to delete (including any subdirs under userfiles)
                   17935: 
                   17936: =item *
                   17937: 
                   17938: removeuploadedurl(): convience function for removeuserfile()
                   17939: 
                   17940:   Args:
                   17941:    url:  a full /uploaded/... url to delete
                   17942: 
1.747     albertel 17943: =item * 
                   17944: 
                   17945: get_portfile_permissions():
                   17946:   Args:
                   17947:     domain: domain of user or course contain the portfolio files
                   17948:     user: name of user or num of course contain the portfolio files
                   17949:   Returns:
                   17950:     hashref of a dump of the proper file_permissions.db
                   17951:    
                   17952: 
                   17953: =item * 
                   17954: 
                   17955: get_access_controls():
                   17956: 
                   17957: Args:
                   17958:   current_permissions: the hash ref returned from get_portfile_permissions()
                   17959:   group: (optional) the group you want the files associated with
                   17960:   file: (optional) the file you want access info on
                   17961: 
                   17962: Returns:
1.749     raeburn  17963:     a hash (keys are file names) of hashes containing
                   17964:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   17965:         values are XML containing access control settings (see below) 
1.747     albertel 17966: 
                   17967: Internal notes:
                   17968: 
1.749     raeburn  17969:  access controls are stored in file_permissions.db as key=value pairs.
                   17970:     key -> path to file/file_name\0uniqueID:scope_end_start
                   17971:         where scope -> public,guest,course,group,domains or users.
                   17972:               end -> UNIX time for end of access (0 -> no end date)
                   17973:               start -> UNIX time for start of access
                   17974: 
                   17975:     value -> XML description of access control
                   17976:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   17977:             <start></start>
                   17978:             <end></end>
                   17979: 
                   17980:             <password></password>  for scope type = guest
                   17981: 
                   17982:             <domain></domain>     for scope type = course or group
                   17983:             <number></number>
                   17984:             <roles id="">
                   17985:              <role></role>
                   17986:              <access></access>
                   17987:              <section></section>
                   17988:              <group></group>
                   17989:             </roles>
                   17990: 
                   17991:             <dom></dom>         for scope type = domains
                   17992: 
                   17993:             <users>             for scope type = users
                   17994:              <user>
                   17995:               <uname></uname>
                   17996:               <udom></udom>
                   17997:              </user>
                   17998:             </users>
                   17999:            </scope> 
                   18000:               
                   18001:  Access data is also aggregated for each file in an additional key=value pair:
                   18002:  key -> path to file/file_name\0accesscontrol 
                   18003:  value -> reference to hash
                   18004:           hash contains key = value pairs
                   18005:           where key = uniqueID:scope_end_start
                   18006:                 value = UNIX time record was last updated
                   18007: 
                   18008:           Used to improve speed of look-ups of access controls for each file.  
                   18009:  
                   18010:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   18011: 
1.1198    raeburn  18012: =item *
                   18013: 
1.749     raeburn  18014: modify_access_controls():
                   18015: 
                   18016: Modifies access controls for a portfolio file
                   18017: Args
                   18018: 1. file name
                   18019: 2. reference to hash of required changes,
                   18020: 3. domain
                   18021: 4. username
                   18022:   where domain,username are the domain of the portfolio owner 
                   18023:   (either a user or a course) 
                   18024: 
                   18025: Returns:
                   18026: 1. result of additions or updates ('ok' or 'error', with error message). 
                   18027: 2. result of deletions ('ok' or 'error', with error message).
                   18028: 3. reference to hash of any new or updated access controls.
                   18029: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   18030:    key = integer (inbound ID)
1.1198    raeburn  18031:    value = uniqueID
                   18032: 
                   18033: =item *
                   18034: 
                   18035: get_timebased_id():
                   18036: 
                   18037: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   18038: course via the Course Editor (e.g., folders, composite pages, 
                   18039: group bulletin boards).
                   18040: 
                   18041: Args: (first three required; six others optional)
                   18042: 
                   18043: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   18044:    docssequence, or name of group
                   18045: 
                   18046: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   18047:    e.g., num, boardids
                   18048: 
                   18049: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   18050:    file will be named nohist_namespace.db
                   18051: 
                   18052: 4. cdom: domain of course; default is current course domain from %env
                   18053: 
                   18054: 5. cnum: course number; default is current course number from %env
                   18055: 
                   18056: 6. idtype: set to concat if an additional digit is to be appended to the 
                   18057:    unix timestamp to form the suffix, if the plain timestamp is already
                   18058:    in use.  Default is to not do this, but simply increment the unix 
                   18059:    timestamp by 1 until a unique key is obtained.
                   18060: 
                   18061: 7. who: holder of locking key; defaults to user:domain for user.
                   18062: 
                   18063: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   18064:    retrying); default is 3.
                   18065: 
                   18066: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   18067: 
                   18068: Returns:
                   18069: 
                   18070: 1. suffix obtained (numeric)
                   18071: 
                   18072: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   18073: 
                   18074: 3. error: contains (localized) error message if an error occurred.
                   18075: 
1.747     albertel 18076: 
1.608     albertel 18077: =back
                   18078: 
1.243     albertel 18079: =head2 HTTP Helper Routines
                   18080: 
                   18081: =over 4
                   18082: 
1.191     harris41 18083: =item *
                   18084: 
                   18085: escape() : unpack non-word characters into CGI-compatible hex codes
                   18086: 
                   18087: =item *
                   18088: 
                   18089: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   18090: 
1.243     albertel 18091: =back
                   18092: 
                   18093: =head1 PRIVATE SUBROUTINES
                   18094: 
                   18095: =head2 Underlying communication routines (Shouldn't call)
                   18096: 
                   18097: =over 4
                   18098: 
                   18099: =item *
                   18100: 
                   18101: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   18102: 
                   18103: =item *
                   18104: 
                   18105: reply() : uses subreply to send a message to remote machine, logs all failures
                   18106: 
                   18107: =item *
                   18108: 
                   18109: critical() : passes a critical message to another server; if cannot
                   18110: get through then place message in connection buffer directory and
                   18111: returns con_delayed, if incapable of saving message, returns
                   18112: con_failed
                   18113: 
                   18114: =item *
                   18115: 
                   18116: reconlonc() : tries to reconnect lonc client processes.
                   18117: 
                   18118: =back
                   18119: 
                   18120: =head2 Resource Access Logging
                   18121: 
                   18122: =over 4
                   18123: 
                   18124: =item *
                   18125: 
                   18126: flushcourselogs() : flush (save) buffer logs and access logs
                   18127: 
                   18128: =item *
                   18129: 
                   18130: courselog($what) : save message for course in hash
                   18131: 
                   18132: =item *
                   18133: 
                   18134: courseacclog($what) : save message for course using &courselog().  Perform
                   18135: special processing for specific resource types (problems, exams, quizzes, etc).
                   18136: 
1.191     harris41 18137: =item *
                   18138: 
                   18139: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   18140: as a PerlChildExitHandler
1.243     albertel 18141: 
                   18142: =back
                   18143: 
                   18144: =head2 Other
                   18145: 
                   18146: =over 4
                   18147: 
                   18148: =item *
                   18149: 
                   18150: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 18151: 
                   18152: =back
                   18153: 
                   18154: =cut
1.877     foxr     18155: 

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