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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1491  ! raeburn     4: # $Id: lonnet.pm,v 1.1490 2022/09/13 02:32:58 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.1       albertel  418: # -------------------------------------------------- Non-critical communication
                    419: sub subreply {
                    420:     my ($cmd,$server)=@_;
1.838     albertel  421:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      422:     #
                    423:     #  With loncnew process trimming, there's a timing hole between lonc server
                    424:     #  process exit and the master server picking up the listen on the AF_UNIX
                    425:     #  socket.  In that time interval, a lock file will exist:
                    426: 
                    427:     my $lockfile=$peerfile.".lock";
                    428:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   429: 	sleep(0.1);
1.549     foxr      430:     }
                    431:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      432:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      433:     #
1.550     foxr      434:     #   We'll give the connection a few tries before abandoning it.  If
                    435:     #   connection is not possible, we'll con_lost back to the client.
                    436:     #   
                    437:     my $client;
                    438:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    439: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    440: 				      Type    => SOCK_STREAM,
                    441: 				      Timeout => 10);
1.869     albertel  442: 	if ($client) {
1.550     foxr      443: 	    last;		# Connected!
1.850     albertel  444: 	} else {
1.853     albertel  445: 	    &create_connection(&hostname($server),$server);
1.550     foxr      446: 	}
1.1289    damieng   447:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      448:     }
                    449:     my $answer;
                    450:     if ($client) {
1.704     albertel  451: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      452: 	$answer=<$client>;
                    453: 	if (!$answer) { $answer="con_lost"; }
                    454: 	chomp($answer);
                    455:     } else {
                    456: 	$answer = 'con_lost';	# Failed connection.
                    457:     }
1.1       albertel  458:     return $answer;
                    459: }
                    460: 
                    461: sub reply {
                    462:     my ($cmd,$server)=@_;
1.838     albertel  463:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  464:     my $answer=subreply($cmd,$server);
1.65      www       465:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396    raeburn   466:         my $logged = $cmd;
                    467:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    468:             my $subcmd = $1;
                    469:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    470:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462    raeburn   471:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
                    472:                 ($subcmd eq 'put')) {
1.1396    raeburn   473:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    474:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    475:                     splice(@rest,2,1,'Hidden');
                    476:                 } elsif ($subcmd eq 'passwd') {
                    477:                     splice(@rest,2,2,('Hidden','Hidden'));
                    478:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462    raeburn   479:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1396    raeburn   480:                     splice(@rest,3,1,'Hidden');
                    481:                 }
                    482:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    483:             }
                    484:         }
                    485:         &logthis("<font color=\"blue\">WARNING:".
                    486:                  " $logged to $server returned $answer</font>");
1.12      www       487:     }
1.1       albertel  488:     return $answer;
                    489: }
                    490: 
                    491: # ----------------------------------------------------------- Send USR1 to lonc
                    492: 
                    493: sub reconlonc {
1.891     albertel  494:     my ($lonid) = @_;
                    495:     if ($lonid) {
1.1295    raeburn   496:         my $hostname = &hostname($lonid);
1.891     albertel  497: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    498: 	if ($hostname && -e $peerfile) {
                    499: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    500: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    501: 					     Type    => SOCK_STREAM,
                    502: 					     Timeout => 10);
                    503: 	    if ($client) {
                    504: 		print $client ("reset_retries\n");
                    505: 		my $answer=<$client>;
                    506: 		#reset just this one.
                    507: 	    }
                    508: 	}
                    509: 	return;
                    510:     }
                    511: 
1.836     www       512:     &logthis("Trying to reconnect lonc");
1.1       albertel  513:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   514:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  515: 	my $loncpid=<$fh>;
                    516:         chomp($loncpid);
                    517:         if (kill 0 => $loncpid) {
                    518: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    519:             kill USR1 => $loncpid;
                    520:             sleep 1;
1.1295    raeburn   521:         } else {
1.12      www       522: 	    &logthis(
1.672     albertel  523:                "<font color=\"blue\">WARNING:".
1.12      www       524:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  525:         }
                    526:     } else {
1.836     www       527: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  528:     }
                    529: }
                    530: 
                    531: # ------------------------------------------------------ Critical communication
1.12      www       532: 
1.1       albertel  533: sub critical {
                    534:     my ($cmd,$server)=@_;
1.838     albertel  535:     unless (&hostname($server)) {
1.672     albertel  536:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       537:                " Critical message to unknown server ($server)</font>");
                    538:         return 'no_such_host';
                    539:     }
1.1       albertel  540:     my $answer=reply($cmd,$server);
                    541:     if ($answer eq 'con_lost') {
1.1295    raeburn   542: 	&reconlonc($server);
1.589     albertel  543: 	my $answer=reply($cmd,$server);
1.1       albertel  544:         if ($answer eq 'con_lost') {
                    545:             my $now=time;
                    546:             my $middlename=$cmd;
1.5       www       547:             $middlename=substr($middlename,0,16);
1.1       albertel  548:             $middlename=~s/\W//g;
                    549:             my $dfilename=
1.305     www       550:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    551:             $dumpcount++;
1.1       albertel  552:             {
1.448     albertel  553: 		my $dfh;
1.1359    raeburn   554: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  555: 		    print $dfh "$cmd\n"; 
                    556: 		    close($dfh);
                    557: 		}
1.1       albertel  558:             }
1.1288    damieng   559:             sleep 1;
1.1       albertel  560:             my $wcmd='';
                    561:             {
1.448     albertel  562: 		my $dfh;
1.1359    raeburn   563: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  564: 		    $wcmd=<$dfh>; 
                    565: 		    close($dfh);
                    566: 		}
1.1       albertel  567:             }
                    568:             chomp($wcmd);
1.7       www       569:             if ($wcmd eq $cmd) {
1.672     albertel  570: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       571:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  572:                 &logperm("D:$server:$cmd");
                    573: 	        return 'con_delayed';
                    574:             } else {
1.672     albertel  575:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       576:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  577:                 &logperm("F:$server:$cmd");
                    578:                 return 'con_failed';
                    579:             }
                    580:         }
                    581:     }
                    582:     return $answer;
1.405     albertel  583: }
                    584: 
1.755     albertel  585: # ------------------------------------------- check if return value is an error
                    586: 
                    587: sub error {
                    588:     my ($result) = @_;
1.756     albertel  589:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  590: 	if ($2 == 2) { return undef; }
                    591: 	return $1;
                    592:     }
                    593:     return undef;
                    594: }
                    595: 
1.783     albertel  596: sub convert_and_load_session_env {
                    597:     my ($lonidsdir,$handle)=@_;
                    598:     my @profile;
                    599:     {
1.917     albertel  600: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    601: 	if (!$opened) {
1.915     albertel  602: 	    return 0;
                    603: 	}
1.783     albertel  604: 	flock($idf,LOCK_SH);
                    605: 	@profile=<$idf>;
                    606: 	close($idf);
                    607:     }
                    608:     my %temp_env;
                    609:     foreach my $line (@profile) {
1.786     albertel  610: 	if ($line !~ m/=/) {
                    611: 	    return 0;
                    612: 	}
1.783     albertel  613: 	chomp($line);
                    614: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    615: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    616:     }
                    617:     unlink("$lonidsdir/$handle.id");
                    618:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    619: 	    0640)) {
                    620: 	%disk_env = %temp_env;
                    621: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    622: 	untie(%disk_env);
                    623:     }
1.786     albertel  624:     return 1;
1.783     albertel  625: }
                    626: 
1.374     www       627: # ------------------------------------------- Transfer profile into environment
1.780     albertel  628: my $env_loaded;
                    629: sub transfer_profile_to_env {
1.788     albertel  630:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    631:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       632: 
1.720     albertel  633:     if (!defined($lonidsdir)) {
                    634: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    635:     }
                    636:     if (!defined($handle)) {
                    637:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    638:     }
                    639: 
1.786     albertel  640:     my $convert;
                    641:     {
1.917     albertel  642:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    643: 	if (!$opened) {
1.915     albertel  644: 	    return;
                    645: 	}
1.786     albertel  646: 	flock($idf,LOCK_SH);
                    647: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    648: 		&GDBM_READER(),0640)) {
                    649: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    650: 	    untie(%disk_env);
                    651: 	} else {
                    652: 	    $convert = 1;
                    653: 	}
                    654:     }
                    655:     if ($convert) {
                    656: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    657: 	    &logthis("Failed to load session, or convert session.");
                    658: 	}
1.374     www       659:     }
1.783     albertel  660: 
1.786     albertel  661:     my %remove;
1.783     albertel  662:     while ( my $envname = each(%env) ) {
1.433     matthew   663:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    664:             if ($time < time-300) {
1.783     albertel  665:                 $remove{$key}++;
1.433     matthew   666:             }
                    667:         }
                    668:     }
1.783     albertel  669: 
1.619     albertel  670:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  671:     $env_loaded=1;
1.783     albertel  672:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   673:         &delenv($expired_key);
1.374     www       674:     }
1.1       albertel  675: }
                    676: 
1.916     albertel  677: # ---------------------------------------------------- Check for valid session 
                    678: sub check_for_valid_session {
1.1355    raeburn   679:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  680:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   681:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    682:     if ($name eq 'lonDAV') {
                    683:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    684:     } else {
                    685:         $lonidsdir=$r->dir_config('lonIDsDir');
                    686:         if ($name eq '') {
                    687:             $name = 'lonID';
                    688:         }
                    689:     }
                    690:     if ($name eq 'lonID') {
                    691:         $secure = 'lonSID';
1.1337    raeburn   692:         $linkname = 'lonLinkID';
                    693:         $pubname = 'lonPubID';
1.1378    raeburn   694:         if (exists($cookies{$secure})) {
                    695:             $lonid=$cookies{$secure};
                    696:         } elsif (exists($cookies{$name})) {
                    697:             $lonid=$cookies{$name};
1.1400    raeburn   698:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337    raeburn   699:             $lonid=$cookies{$linkname};
1.1378    raeburn   700:         } elsif (exists($cookies{$pubname})) {
                    701:             $lonid=$cookies{$pubname};
1.1337    raeburn   702:         }
1.1378    raeburn   703:     } else {
                    704:         $lonid=$cookies{$name};
1.1337    raeburn   705:     }
1.916     albertel  706:     return undef if (!$lonid);
                    707: 
                    708:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   709:     if (-l "$lonidsdir/$handle.id") {
                    710:         my $link = readlink("$lonidsdir/$handle.id");
                    711:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    712:             $handle = $1;
                    713:         }
1.1155    raeburn   714:     }
1.1355    raeburn   715:     if (!-e "$lonidsdir/$handle.id") {
                    716:         if ((ref($domref)) && ($name eq 'lonID') && 
                    717:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    718:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    719:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    720:                 $$domref = $possudom;
                    721:             }
                    722:         }
                    723:         return undef;
                    724:     }
1.916     albertel  725: 
1.917     albertel  726:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    727:     return undef if (!$opened);
1.916     albertel  728: 
                    729:     flock($idf,LOCK_SH);
                    730:     my %disk_env;
                    731:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    732: 	    &GDBM_READER(),0640)) {
                    733: 	return undef;	
                    734:     }
                    735: 
                    736:     if (!defined($disk_env{'user.name'})
                    737: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   738:         untie(%disk_env);
1.916     albertel  739: 	return undef;
                    740:     }
1.1245    raeburn   741: 
                    742:     if (ref($userhashref) eq 'HASH') {
                    743:         $userhashref->{'name'} = $disk_env{'user.name'};
                    744:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448    raeburn   745:         if ($disk_env{'request.role'}) {
                    746:             $userhashref->{'role'} = $disk_env{'request.role'};
                    747:         }
1.1361    raeburn   748:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   749:         if ($userhashref->{'lti'}) {
                    750:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    751:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    752:         }
1.1212    raeburn   753:     }
1.1394    raeburn   754:     untie(%disk_env);
1.1245    raeburn   755: 
1.916     albertel  756:     return $handle;
                    757: }
                    758: 
1.830     albertel  759: sub timed_flock {
                    760:     my ($file,$lock_type) = @_;
                    761:     my $failed=0;
                    762:     eval {
                    763: 	local $SIG{__DIE__}='DEFAULT';
                    764: 	local $SIG{ALRM}=sub {
                    765: 	    $failed=1;
                    766: 	    die("failed lock");
                    767: 	};
                    768: 	alarm(13);
                    769: 	flock($file,$lock_type);
                    770: 	alarm(0);
                    771:     };
                    772:     if ($failed) {
                    773: 	return undef;
                    774:     } else {
                    775: 	return 1;
                    776:     }
                    777: }
                    778: 
1.1392    raeburn   779: sub get_sessionfile_vars {
                    780:     my ($handle,$lonidsdir,$storearr) = @_;
                    781:     my %returnhash;
                    782:     unless (ref($storearr) eq 'ARRAY') {
                    783:         return %returnhash;
                    784:     }
                    785:     if (-l "$lonidsdir/$handle.id") {
                    786:         my $link = readlink("$lonidsdir/$handle.id");
                    787:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    788:             $handle = $1;
                    789:         }
                    790:     }
                    791:     if ((-e "$lonidsdir/$handle.id") &&
                    792:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    793:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    794:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    795:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    796:                 flock($idf,LOCK_SH);
                    797:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    798:                         &GDBM_READER(),0640)) {
                    799:                     foreach my $item (@{$storearr}) {
                    800:                         $returnhash{$item} = $disk_env{$item};
                    801:                     }
                    802:                     untie(%disk_env);
                    803:                 }
                    804:             }
                    805:         }
                    806:     }
                    807:     return %returnhash;
                    808: }
                    809: 
1.5       www       810: # ---------------------------------------------------------- Append Environment
                    811: 
                    812: sub appenv {
1.949     raeburn   813:     my ($newenv,$roles) = @_;
                    814:     if (ref($newenv) eq 'HASH') {
                    815:         foreach my $key (keys(%{$newenv})) {
                    816:             my $refused = 0;
                    817: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    818:                 $refused = 1;
                    819:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   820:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   821:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    822:                         $refused = 0;
                    823:                     }
                    824:                 }
                    825:             }
                    826:             if ($refused) {
                    827:                 &logthis("<font color=\"blue\">WARNING: ".
                    828:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    829:                          .'</font>');
                    830: 	        delete($newenv->{$key});
                    831:             } else {
                    832:                 $env{$key}=$newenv->{$key};
                    833:             }
                    834:         }
1.1376    raeburn   835:         my $lonids = $perlvar{'lonIDsDir'};
                    836:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    837:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    838:             if ($opened
                    839: 	        && &timed_flock($env_file,LOCK_EX)
                    840: 	        &&
                    841: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    842: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    843: 	        while (my ($key,$value) = each(%{$newenv})) {
                    844: 	            $disk_env{$key} = $value;
                    845: 	        }
                    846: 	        untie(%disk_env);
                    847:             }
1.35      www       848:         }
1.191     harris41  849:     }
1.56      www       850:     return 'ok';
                    851: }
                    852: # ----------------------------------------------------- Delete from Environment
                    853: 
                    854: sub delenv {
1.1104    raeburn   855:     my ($delthis,$regexp,$roles) = @_;
                    856:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    857:         my $refused = 1;
                    858:         if (ref($roles) eq 'ARRAY') {
                    859:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    860:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    861:                 $refused = 0;
                    862:             }
                    863:         }
                    864:         if ($refused) {
                    865:             &logthis("<font color=\"blue\">WARNING: ".
                    866:                      "Attempt to delete from environment ".$delthis);
                    867:             return 'error';
                    868:         }
1.56      www       869:     }
1.917     albertel  870:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    871:     if ($opened
1.915     albertel  872: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  873: 	&&
                    874: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    875: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  876: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   877: 	    if ($regexp) {
                    878:                 if ($key=~/^$delthis/) {
                    879:                     delete($env{$key});
                    880:                     delete($disk_env{$key});
                    881:                 } 
                    882:             } else {
                    883:                 if ($key=~/^\Q$delthis\E/) {
                    884: 		    delete($env{$key});
                    885: 		    delete($disk_env{$key});
                    886: 	        }
                    887:             }
1.448     albertel  888: 	}
1.783     albertel  889: 	untie(%disk_env);
1.5       www       890:     }
                    891:     return 'ok';
1.369     albertel  892: }
                    893: 
1.790     albertel  894: sub get_env_multiple {
                    895:     my ($name) = @_;
                    896:     my @values;
                    897:     if (defined($env{$name})) {
                    898:         # exists is it an array
                    899:         if (ref($env{$name})) {
                    900:             @values=@{ $env{$name} };
                    901:         } else {
                    902:             $values[0]=$env{$name};
                    903:         }
                    904:     }
                    905:     return(@values);
                    906: }
                    907: 
1.958     www       908: # ------------------------------------------------------------------- Locking
                    909: 
                    910: sub set_lock {
                    911:     my ($text)=@_;
                    912:     $locknum++;
                    913:     my $id=$$.'-'.$locknum;
                    914:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    915:              'session.lock.'.$id => $text});
                    916:     return $id;
                    917: }
                    918: 
                    919: sub get_locks {
                    920:     my $num=0;
                    921:     my %texts=();
                    922:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    923:        if ($lock=~/\w/) {
                    924:           $num++;
                    925:           $texts{$lock}=$env{'session.lock.'.$lock};
                    926:        }
                    927:    }
                    928:    return ($num,%texts);
                    929: }
                    930: 
                    931: sub remove_lock {
                    932:     my ($id)=@_;
                    933:     my $newlocks='';
                    934:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    935:        if (($lock=~/\w/) && ($lock ne $id)) {
                    936:           $newlocks.=','.$lock;
                    937:        }
                    938:     }
                    939:     &appenv({'session.locks' => $newlocks});
                    940:     &delenv('session.lock.'.$id);
                    941: }
                    942: 
                    943: sub remove_all_locks {
                    944:     my $activelocks=$env{'session.locks'};
                    945:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    946:        if ($lock=~/\w/) {
                    947:           &remove_lock($lock);
                    948:        }
                    949:     }
                    950: }
                    951: 
                    952: 
1.369     albertel  953: # ------------------------------------------ Find out current server userload
                    954: sub userload {
                    955:     my $numusers=0;
                    956:     {
                    957: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    958: 	my $filename;
                    959: 	my $curtime=time;
                    960: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  961: 	    next if ($filename eq '.' || $filename eq '..');
                    962: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   963:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  964: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  965: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  966: 	}
                    967: 	closedir(LONIDS);
                    968:     }
                    969:     my $userloadpercent=0;
                    970:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    971:     if ($maxuserload) {
1.371     albertel  972: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  973:     }
1.372     albertel  974:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  975:     return $userloadpercent;
1.283     www       976: }
                    977: 
1.1       albertel  978: # ------------------------------ Find server with least workload from spare.tab
1.11      www       979: 
1.1       albertel  980: sub spareserver {
1.1451    raeburn   981:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  982:     my $spare_server;
1.370     albertel  983:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  984:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    985:                                                      :  $userloadpercent;
1.1083    raeburn   986:     my ($uint_dom,$remotesessions);
                    987:     if (($udom ne '') && (&domain($udom) ne '')) {
                    988:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    989:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    990:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    991:         $remotesessions = $udomdefaults{'remotesessions'};
                    992:     }
1.1123    raeburn   993:     my $spareshash = &this_host_spares($udom);
                    994:     if (ref($spareshash) eq 'HASH') {
                    995:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    996:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   997:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    998:                                              $try_server));
1.1123    raeburn   999: 	        ($spare_server, $lowest_load) =
                   1000: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                   1001:             }
1.1083    raeburn  1002:         }
1.784     albertel 1003: 
1.1123    raeburn  1004:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                   1005: 
                   1006:         if (!$found_server) {
                   1007:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1008: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1009:                     next unless (&spare_can_host($udom,$uint_dom,
                   1010:                                                  $remotesessions,$try_server));
1.1123    raeburn  1011: 	            ($spare_server, $lowest_load) =
                   1012: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1013:                 }
                   1014: 	    }
                   1015:         }
1.784     albertel 1016:     }
                   1017: 
                   1018:     if (!$want_server_name) {
1.1001    raeburn  1019:         if (defined($spare_server)) {
                   1020:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1021:             if (defined($hostname)) {
1.1397    raeburn  1022:                 my $protocol = 'http';
                   1023:                 if ($protocol{$spare_server} eq 'https') {
                   1024:                     $protocol = $protocol{$spare_server};
                   1025:                 }
1.1451    raeburn  1026:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
                   1027:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn  1028: 	        $spare_server = $protocol.'://'.$hostname;
                   1029:             }
                   1030:         }
1.784     albertel 1031:     }
                   1032:     return $spare_server;
                   1033: }
                   1034: 
                   1035: sub compare_server_load {
1.1253    raeburn  1036:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1037: 
                   1038:     if ($required) {
                   1039:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1040:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1041:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1042:         if (($major eq '' && $minor eq '') ||
                   1043:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1044:             return ($spare_server,$lowest_load);
                   1045:         }
                   1046:     }
1.784     albertel 1047: 
                   1048:     my $loadans     = &reply('load',    $try_server);
                   1049:     my $userloadans = &reply('userload',$try_server);
                   1050: 
                   1051:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1052: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1053:     }
                   1054: 
                   1055:     my $load;
                   1056:     if ($loadans =~ /\d/) {
                   1057: 	if ($userloadans =~ /\d/) {
                   1058: 	    #both are numbers, pick the bigger one
                   1059: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1060: 		                              : $userloadans;
1.411     albertel 1061: 	} else {
1.784     albertel 1062: 	    $load = $loadans;
1.411     albertel 1063: 	}
1.784     albertel 1064:     } else {
                   1065: 	$load = $userloadans;
                   1066:     }
                   1067: 
                   1068:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1069: 	$spare_server = $try_server;
                   1070: 	$lowest_load  = $load;
1.370     albertel 1071:     }
1.784     albertel 1072:     return ($spare_server,$lowest_load);
1.202     matthew  1073: }
1.914     albertel 1074: 
                   1075: # --------------------------- ask offload servers if user already has a session
                   1076: sub find_existing_session {
                   1077:     my ($udom,$uname) = @_;
1.1123    raeburn  1078:     my $spareshash = &this_host_spares($udom);
                   1079:     if (ref($spareshash) eq 'HASH') {
                   1080:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1081:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1082:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1083:             }
                   1084:         }
                   1085:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1086:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1087:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1088:             }
                   1089:         }
1.914     albertel 1090:     }
                   1091:     return;
                   1092: }
                   1093: 
1.1411    raeburn  1094: sub delusersession {
                   1095:     my ($lonid,$udom,$uname) = @_;
                   1096:     my $uprimary_id = &domain($udom,'primary');
                   1097:     my $uintdom = &internet_dom($uprimary_id);
                   1098:     my $intdom = &internet_dom($lonid);
                   1099:     my $serverhomedom = &host_domain($lonid);
                   1100:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1101:         return &reply(join(':','delusersession',
                   1102:                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1103:     }
                   1104:     return;
                   1105: }
                   1106: 
1.1389    raeburn  1107: # check if user's browser sent load balancer cookie and server still has session
                   1108: # and is not overloaded.
                   1109: sub check_for_balancer_cookie {
                   1110:     my ($r,$update_mtime) = @_;
                   1111:     my ($otherserver,$cookie);
                   1112:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1113:     if (exists($cookies{'balanceID'})) {
                   1114:         my $balid = $cookies{'balanceID'};
                   1115:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1116:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1117:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1118:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1119:                 my ($possudom,$possuname) = ($1,$2);
                   1120:                 my $has_session = 0;
                   1121:                 if ((&domain($possudom) ne '') &&
                   1122:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1123:                     my $try_server;
                   1124:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1125:                     if ($opened) {
                   1126:                         flock($idf,LOCK_SH);
                   1127:                         while (my $line = <$idf>) {
                   1128:                             chomp($line);
                   1129:                             if (&hostname($line) ne '') {
                   1130:                                 $try_server = $line;
                   1131:                                 last;
                   1132:                             }
                   1133:                         }
                   1134:                         close($idf);
                   1135:                         if (($try_server) &&
                   1136:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1137:                             my $lowest_load = 30000;
                   1138:                             ($otherserver,$lowest_load) =
                   1139:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1140:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1141:                                 $has_session = 1;
                   1142:                             } else {
                   1143:                                 undef($otherserver);
                   1144:                             }
                   1145:                         }
                   1146:                     }
                   1147:                 }
                   1148:                 if ($has_session) {
                   1149:                     if ($update_mtime) {
                   1150:                         my $atime = my $mtime = time;
                   1151:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1152:                     }
                   1153:                 } else {
                   1154:                     unlink("$balancedir/$cookie.id");
                   1155:                 }
                   1156:             }
                   1157:         }
                   1158:     }
                   1159:     return ($otherserver,$cookie);
                   1160: }
                   1161: 
1.1431    raeburn  1162: sub updatebalcookie {
                   1163:     my ($cookie,$balancer,$lastentry)=@_;
                   1164:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1165:         my ($udom,$uname) = ($1,$2);
                   1166:         my $uprimary_id = &domain($udom,'primary');
                   1167:         my $uintdom = &internet_dom($uprimary_id);
                   1168:         my $intdom = &internet_dom($balancer);
                   1169:         my $serverhomedom = &host_domain($balancer);
                   1170:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1171:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1172:         }
                   1173:     }
                   1174:     return;
                   1175: }
                   1176: 
1.1389    raeburn  1177: sub delbalcookie {
                   1178:     my ($cookie,$balancer) =@_;
                   1179:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1180:         my ($udom,$uname) = ($1,$2);
                   1181:         my $uprimary_id = &domain($udom,'primary');
                   1182:         my $uintdom = &internet_dom($uprimary_id);
                   1183:         my $intdom = &internet_dom($balancer);
                   1184:         my $serverhomedom = &host_domain($balancer);
                   1185:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431    raeburn  1186:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389    raeburn  1187:         }
                   1188:     }
                   1189: }
                   1190: 
1.914     albertel 1191: # -------------------------------- ask if server already has a session for user
                   1192: sub has_user_session {
                   1193:     my ($lonid,$udom,$uname) = @_;
                   1194:     my $result = &reply(join(':','userhassession',
                   1195: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1196:     return 1 if ($result eq 'ok');
                   1197: 
                   1198:     return 0;
                   1199: }
                   1200: 
1.1076    raeburn  1201: # --------- determine least loaded server in a user's domain which allows login
                   1202: 
                   1203: sub choose_server {
1.1259    raeburn  1204:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1205:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1206:     my %servers = &get_servers($udom);
1.1076    raeburn  1207:     my $lowest_load = 30000;
1.1259    raeburn  1208:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1209:     if ($skiploadbal) {
                   1210:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1211:         unless (defined($cached)) {
                   1212:             my $cachetime = 60*60*24;
                   1213:             my %domconfig =
                   1214:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1215:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1216:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1217:                                            $cachetime);
                   1218:             }
                   1219:         }
                   1220:     }
1.1076    raeburn  1221:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1222:         if ($skiploadbal) {
                   1223:             if (ref($balancers) eq 'HASH') {
                   1224:                 next if (exists($balancers->{$lonhost}));
                   1225:             }
1.1389    raeburn  1226:         }
1.1115    raeburn  1227:         my $loginvia;
                   1228:         if ($checkloginvia) {
                   1229:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1230:             if ($loginvia) {
                   1231:                 my ($server,$path) = split(/:/,$loginvia);
                   1232:                 ($login_host, $lowest_load) =
1.1253    raeburn  1233:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1234:                 if ($login_host eq $server) {
                   1235:                     $portal_path = $path;
1.1151    raeburn  1236:                     $isredirect = 1;
1.1116    raeburn  1237:                 }
                   1238:             } else {
                   1239:                 ($login_host, $lowest_load) =
1.1253    raeburn  1240:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1241:                 if ($login_host eq $lonhost) {
                   1242:                     $portal_path = '';
1.1151    raeburn  1243:                     $isredirect = ''; 
1.1116    raeburn  1244:                 }
                   1245:             }
                   1246:         } else {
1.1076    raeburn  1247:             ($login_host, $lowest_load) =
1.1253    raeburn  1248:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1249:         }
                   1250:     }
                   1251:     if ($login_host ne '') {
1.1116    raeburn  1252:         $hostname = &hostname($login_host);
1.1076    raeburn  1253:     }
1.1331    raeburn  1254:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1255: }
                   1256: 
1.1420    raeburn  1257: sub get_course_sessions {
                   1258:     my ($cnum,$cdom,$lastactivity) = @_;
                   1259:     my %servers = &internet_dom_servers($cdom);
                   1260:     my %returnhash;
                   1261:     foreach my $server (sort(keys(%servers))) {
                   1262:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1263:         my @pairs=split(/\&/,$rep);
                   1264:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1265:             foreach my $item (@pairs) {
                   1266:                 my ($key,$value)=split(/=/,$item,2);
                   1267:                 $key = &unescape($key);
                   1268:                 next if ($key =~ /^error: 2 /);
                   1269:                 if (exists($returnhash{$key})) {
                   1270:                     next if ($value < $returnhash{$key});
                   1271:                 }
                   1272:                 $returnhash{$key}=$value;
                   1273:             }
                   1274:         }
                   1275:     }
                   1276:     return %returnhash;
                   1277: }
                   1278: 
1.202     matthew  1279: # --------------------------------------------- Try to change a user's password
                   1280: 
                   1281: sub changepass {
1.799     raeburn  1282:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1283:     $currentpass = &escape($currentpass);
                   1284:     $newpass     = &escape($newpass);
1.1030    raeburn  1285:     my $lonhost = $perlvar{'lonHostID'};
                   1286:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1287: 		       $server);
                   1288:     if (! $answer) {
                   1289: 	&logthis("No reply on password change request to $server ".
                   1290: 		 "by $uname in domain $udom.");
                   1291:     } elsif ($answer =~ "^ok") {
                   1292:         &logthis("$uname in $udom successfully changed their password ".
                   1293: 		 "on $server.");
                   1294:     } elsif ($answer =~ "^pwchange_failure") {
                   1295: 	&logthis("$uname in $udom was unable to change their password ".
                   1296: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1297: 		 "or pwchange");
                   1298:     } elsif ($answer =~ "^non_authorized") {
                   1299:         &logthis("$uname in $udom did not get their password correct when ".
                   1300: 		 "attempting to change it on $server.");
                   1301:     } elsif ($answer =~ "^auth_mode_error") {
                   1302:         &logthis("$uname in $udom attempted to change their password despite ".
                   1303: 		 "not being locally or internally authenticated on $server.");
                   1304:     } elsif ($answer =~ "^unknown_user") {
                   1305:         &logthis("$uname in $udom attempted to change their password ".
                   1306: 		 "on $server but were unable to because $server is not ".
                   1307: 		 "their home server.");
                   1308:     } elsif ($answer =~ "^refused") {
                   1309: 	&logthis("$server refused to change $uname in $udom password because ".
                   1310: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1311:     } elsif ($answer =~ "invalid_client") {
                   1312:         &logthis("$server refused to change $uname in $udom password because ".
                   1313:                  "it was a reset by e-mail originating from an invalid server.");
1.1408    raeburn  1314:     } elsif ($answer =~ "^prioruse") {
                   1315:        &logthis("$server refused to change $uname in $udom password because ".
                   1316:                 "the password had been used before");
1.202     matthew  1317:     }
                   1318:     return $answer;
1.1       albertel 1319: }
                   1320: 
1.169     harris41 1321: # ----------------------- Try to determine user's current authentication scheme
                   1322: 
                   1323: sub queryauthenticate {
                   1324:     my ($uname,$udom)=@_;
1.456     albertel 1325:     my $uhome=&homeserver($uname,$udom);
1.1484    raeburn  1326:     if ((!$uhome) || ($uhome eq 'no_host')) {
1.456     albertel 1327: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1328: 	return 'no_host';
                   1329:     }
                   1330:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1331:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1332: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1333:     }
1.456     albertel 1334:     return $answer;
1.169     harris41 1335: }
                   1336: 
1.1       albertel 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1338: 
1.1       albertel 1339: sub authenticate {
1.1073    raeburn  1340:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1341:     $upass=&escape($upass);
                   1342:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1343:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1344:     my $newhome;
1.836     www      1345:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1346: # Maybe the machine was offline and only re-appeared again recently?
                   1347:         &reconlonc();
                   1348: # One more
1.952     raeburn  1349: 	$uhome=&homeserver($uname,$udom,1);
                   1350:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1351:             if (defined(&domain($udom,'primary'))) {
                   1352:                 $newhome=&domain($udom,'primary');
                   1353:             }
                   1354:             if ($newhome ne '') {
                   1355:                 $uhome = $newhome;
                   1356:             }
                   1357:         }
1.836     www      1358: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1359: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1360: 	    return 'no_host';
                   1361:         }
1.1       albertel 1362:     }
1.1073    raeburn  1363:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1364:     if ($answer eq 'authorized') {
1.952     raeburn  1365:         if ($newhome) {
                   1366:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1367:             return 'no_account_on_host'; 
                   1368:         } else {
                   1369:             &logthis("User $uname at $udom authorized by $uhome");
                   1370:             return $uhome;
                   1371:         }
1.471     albertel 1372:     }
                   1373:     if ($answer eq 'non_authorized') {
                   1374: 	&logthis("User $uname at $udom rejected by $uhome");
1.1484    raeburn  1375: 	return 'no_host';
1.9       www      1376:     }
1.471     albertel 1377:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1378:     return 'no_host';
                   1379: }
                   1380: 
1.1491  ! raeburn  1381: sub can_switchserver {
        !          1382:     my ($udom,$home) = @_;
        !          1383:     my ($canswitch,@intdoms);
        !          1384:     my $internet_names = &get_internet_names($home);
        !          1385:     if (ref($internet_names) eq 'ARRAY') {
        !          1386:         @intdoms = @{$internet_names};
        !          1387:     }
        !          1388:     my $uint_dom = &internet_dom(&domain($udom,'primary'));
        !          1389:     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
        !          1390:         $canswitch = 1;
        !          1391:     } else {
        !          1392:          my $serverhomeID = &get_server_homeID(&hostname($home));
        !          1393:          my $serverhomedom = &host_domain($serverhomeID);
        !          1394:          my %defdomdefaults = &get_domain_defaults($serverhomedom);
        !          1395:          my %udomdefaults = &get_domain_defaults($udom);
        !          1396:          my $remoterev = &get_server_loncaparev('',$home);
        !          1397:          $canswitch = &can_host_session($udom,$home,$remoterev,
        !          1398:                                         $udomdefaults{'remotesessions'},
        !          1399:                                         $defdomdefaults{'hostedsessions'});
        !          1400:     }
        !          1401:     return $canswitch;
        !          1402: }
        !          1403: 
1.1073    raeburn  1404: sub can_host_session {
1.1074    raeburn  1405:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1406:     my $canhost = 1;
1.1074    raeburn  1407:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1408:     if (ref($remotesessions) eq 'HASH') {
                   1409:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1410:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1411:                 $canhost = 0;
                   1412:             } else {
                   1413:                 $canhost = 1;
                   1414:             }
                   1415:         }
                   1416:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1417:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1418:                 $canhost = 1;
                   1419:             } else {
                   1420:                 $canhost = 0;
                   1421:             }
                   1422:         }
                   1423:         if ($canhost) {
                   1424:             if ($remotesessions->{'version'} ne '') {
                   1425:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1426:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1427:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1428:                         my $major = $1;
                   1429:                         my $minor = $2;
                   1430:                         if (($major < $reqmajor ) ||
                   1431:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1432:                             $canhost = 0;
                   1433:                         }
                   1434:                     } else {
                   1435:                         $canhost = 0;
                   1436:                     }
                   1437:                 }
                   1438:             }
                   1439:         }
                   1440:     }
                   1441:     if ($canhost) {
                   1442:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1443:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1444:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1445:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1446:                 if (($uint_dom ne '') && 
                   1447:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1448:                     $canhost = 0;
                   1449:                 } else {
                   1450:                     $canhost = 1;
                   1451:                 }
                   1452:             }
                   1453:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1454:                 if (($uint_dom ne '') && 
                   1455:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1456:                     $canhost = 1;
                   1457:                 } else {
                   1458:                     $canhost = 0;
                   1459:                 }
                   1460:             }
                   1461:         }
                   1462:     }
                   1463:     return $canhost;
                   1464: }
                   1465: 
1.1083    raeburn  1466: sub spare_can_host {
                   1467:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1468:     my $canhost=1;
1.1279    raeburn  1469:     my $try_server_hostname = &hostname($try_server);
                   1470:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1471:     my $serverhomedom = &host_domain($serverhomeID);
                   1472:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1473:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1474:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1475:             $canhost = 0;
                   1476:         }
                   1477:     }
1.1439    raeburn  1478:     if ($canhost) {
                   1479:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1480:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1481:                 unless (&shared_institution($udom,$try_server)) {
                   1482:                     $canhost = 0;
                   1483:                 }
                   1484:             }
                   1485:         }
                   1486:     }
1.1279    raeburn  1487:     if (($canhost) && ($uint_dom)) {
                   1488:         my @intdoms;
                   1489:         my $internet_names = &get_internet_names($try_server);
                   1490:         if (ref($internet_names) eq 'ARRAY') {
                   1491:             @intdoms = @{$internet_names};
                   1492:         }
                   1493:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1494:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1495:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1496:                                          $remotesessions,
                   1497:                                          $defdomdefaults{'hostedsessions'});
                   1498:         }
1.1083    raeburn  1499:     }
                   1500:     return $canhost;
                   1501: }
                   1502: 
1.1123    raeburn  1503: sub this_host_spares {
                   1504:     my ($dom) = @_;
1.1126    raeburn  1505:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1506:     my @hosts = &current_machine_ids();
                   1507:     foreach my $lonhost (@hosts) {
                   1508:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1509:             $dom_in_use = $dom;
                   1510:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1511:             last;
                   1512:         }
                   1513:     }
1.1126    raeburn  1514:     if ($dom_in_use ne '') {
                   1515:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1516:     }
                   1517:     if (ref($result) ne 'HASH') {
                   1518:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1519:         $dom_in_use = &host_domain($lonhost_in_use);
                   1520:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1521:         if (ref($result) ne 'HASH') {
                   1522:             $result = \%spareid;
                   1523:         }
                   1524:     }
                   1525:     return $result;
                   1526: }
                   1527: 
                   1528: sub spares_for_offload  {
                   1529:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1530:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1531:     if (defined($cached)) {
                   1532:         return $result;
                   1533:     } else {
1.1126    raeburn  1534:         my $cachetime = 60*60*24;
                   1535:         my %domconfig =
                   1536:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1537:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1538:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1539:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1540:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1541:                 }
                   1542:             }
                   1543:         }
                   1544:     }
1.1126    raeburn  1545:     return;
1.1123    raeburn  1546: }
                   1547: 
1.1129    raeburn  1548: sub get_lonbalancer_config {
                   1549:     my ($servers) = @_;
                   1550:     my ($currbalancer,$currtargets);
                   1551:     if (ref($servers) eq 'HASH') {
                   1552:         foreach my $server (keys(%{$servers})) {
                   1553:             my %what = (
                   1554:                          spareid => 1,
                   1555:                          perlvar => 1,
                   1556:                        );
                   1557:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1558:             if ($result eq 'ok') {
                   1559:                 if (ref($returnhash) eq 'HASH') {
                   1560:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1561:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1562:                             $currbalancer = $server;
                   1563:                             $currtargets = {};
                   1564:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1565:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1566:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1567:                                 }
                   1568:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1569:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1570:                                 }
                   1571:                             }
                   1572:                             last;
                   1573:                         }
                   1574:                     }
                   1575:                 }
                   1576:             }
                   1577:         }
                   1578:     }
                   1579:     return ($currbalancer,$currtargets);
                   1580: }
                   1581: 
                   1582: sub check_loadbalancing {
1.1331    raeburn  1583:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1584:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1585:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1586:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1587:     my @hosts = &current_machine_ids();
1.1129    raeburn  1588:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1589:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1590:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1591:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1592:     my $domneedscache;
1.1129    raeburn  1593:     my $cachetime = 60*60*24;
                   1594: 
                   1595:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1596:         $dom_in_use = $udom;
                   1597:         $homeintdom = 1;
                   1598:     } else {
                   1599:         $dom_in_use = $serverhomedom;
                   1600:     }
                   1601:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1602:     unless (defined($cached)) {
                   1603:         my %domconfig =
                   1604:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1605:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1606:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1607:         } else {
                   1608:             $domneedscache = $dom_in_use;
1.1129    raeburn  1609:         }
                   1610:     }
                   1611:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1612:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1613:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1614:         if ($is_balancer) {
                   1615:             if (ref($currrules) eq 'HASH') {
                   1616:                 if ($homeintdom) {
                   1617:                     if ($uname ne '') {
                   1618:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1619:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1620:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1621:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1622:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1623:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1624:                             }
                   1625:                         }
                   1626:                         if ($rule_in_effect eq '') {
                   1627:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1628:                             if ($userenv{'inststatus'} ne '') {
                   1629:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1630:                                 my ($othertitle,$usertypes,$types) =
                   1631:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1632:                                 if (ref($types) eq 'ARRAY') {
                   1633:                                     foreach my $type (@{$types}) {
                   1634:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1635:                                             if (exists($currrules->{$type})) {
                   1636:                                                 $rule_in_effect = $currrules->{$type};
                   1637:                                             }
                   1638:                                         }
                   1639:                                     }
                   1640:                                 }
                   1641:                             } else {
                   1642:                                 if (exists($currrules->{'default'})) {
                   1643:                                     $rule_in_effect = $currrules->{'default'};
                   1644:                                 }
                   1645:                             }
                   1646:                         }
                   1647:                     } else {
                   1648:                         if (exists($currrules->{'default'})) {
                   1649:                             $rule_in_effect = $currrules->{'default'};
                   1650:                         }
                   1651:                     }
                   1652:                 } else {
                   1653:                     if ($currrules->{'_LC_external'} ne '') {
                   1654:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1655:                     }
                   1656:                 }
                   1657:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1658:                                                        $uname,$udom);
                   1659:             }
                   1660:         }
                   1661:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1662:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1663:         unless (defined($cached)) {
                   1664:             my %domconfig =
                   1665:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1666:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1667:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1668:             } else {
                   1669:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1670:             }
                   1671:         }
                   1672:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1673:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1674:                 &check_balancer_result($result,@hosts);
                   1675:             if ($is_balancer) {
1.1129    raeburn  1676:                 if (ref($currrules) eq 'HASH') {
                   1677:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1678:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1679:                     }
                   1680:                 }
                   1681:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1682:                                                        $uname,$udom);
                   1683:             }
                   1684:         } else {
                   1685:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1686:                 $is_balancer = 1;
                   1687:                 $offloadto = &this_host_spares($dom_in_use);
                   1688:             }
1.1307    raeburn  1689:             unless (defined($cached)) {
                   1690:                 $domneedscache = $serverhomedom;
                   1691:             }
1.1129    raeburn  1692:         }
                   1693:     } else {
                   1694:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1695:             $is_balancer = 1;
                   1696:             $offloadto = &this_host_spares($dom_in_use);
                   1697:         }
1.1307    raeburn  1698:         unless (defined($cached)) {
                   1699:             $domneedscache = $serverhomedom;
                   1700:         }
                   1701:     }
                   1702:     if ($domneedscache) {
                   1703:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1704:     }
1.1430    raeburn  1705:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176    raeburn  1706:         my $lowest_load = 30000;
                   1707:         if (ref($offloadto) eq 'HASH') {
                   1708:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1709:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1710:                     ($otherserver,$lowest_load) =
                   1711:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1712:                 }
1.1129    raeburn  1713:             }
1.1176    raeburn  1714:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1715: 
1.1176    raeburn  1716:             if (!$found_server) {
                   1717:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1718:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1719:                         ($otherserver,$lowest_load) =
                   1720:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1721:                     }
                   1722:                 }
                   1723:             }
                   1724:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1725:             if (@{$offloadto} == 1) {
                   1726:                 $otherserver = $offloadto->[0];
                   1727:             } elsif (@{$offloadto} > 1) {
                   1728:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1729:                     ($otherserver,$lowest_load) =
                   1730:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1731:                 }
                   1732:             }
                   1733:         }
1.1331    raeburn  1734:         unless ($caller eq 'login') {
                   1735:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1736:                 $is_balancer = 0;
                   1737:                 if ($uname ne '' && $udom ne '') {
                   1738:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1739:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1740:                                  'user.loadbalcheck.time' => time});
                   1741:                     }
1.1176    raeburn  1742:                 }
1.1129    raeburn  1743:             }
                   1744:         }
1.1430    raeburn  1745:     }
                   1746:     if (($is_balancer) && (!$homeintdom)) {
                   1747:         undef($setcookie);
1.1129    raeburn  1748:     }
1.1391    raeburn  1749:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1750: }
                   1751: 
1.1191    raeburn  1752: sub check_balancer_result {
                   1753:     my ($result,@hosts) = @_;
1.1391    raeburn  1754:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1755:     if (ref($result) eq 'HASH') {
                   1756:         if ($result->{'lonhost'} ne '') {
                   1757:             my $currbalancer = $result->{'lonhost'};
                   1758:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1759:                 $is_balancer = 1;
                   1760:                 $currtargets = $result->{'targets'};
                   1761:                 $currrules = $result->{'rules'};
                   1762:             }
1.1391    raeburn  1763:             $dom_balancers = $currbalancer;
1.1191    raeburn  1764:         } else {
1.1391    raeburn  1765:             if (keys(%{$result})) {
                   1766:                 foreach my $key (keys(%{$result})) {
                   1767:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1768:                         (ref($result->{$key}) eq 'HASH')) {
                   1769:                         $is_balancer = 1;
                   1770:                         $currrules = $result->{$key}{'rules'};
                   1771:                         $currtargets = $result->{$key}{'targets'};
                   1772:                         $setcookie = $result->{$key}{'cookie'};
                   1773:                         last;
                   1774:                     }
1.1191    raeburn  1775:                 }
1.1391    raeburn  1776:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1777:             }
                   1778:         }
                   1779:     }
1.1391    raeburn  1780:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1781: }
                   1782: 
1.1129    raeburn  1783: sub get_loadbalancer_targets {
                   1784:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1785:     my $offloadto;
1.1175    raeburn  1786:     if ($rule_in_effect eq 'none') {
                   1787:         return [$perlvar{'lonHostID'}];
                   1788:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1789:         $offloadto = $currtargets;
                   1790:     } else {
                   1791:         if ($rule_in_effect eq 'homeserver') {
                   1792:             my $homeserver = &homeserver($uname,$udom);
                   1793:             if ($homeserver ne 'no_host') {
                   1794:                 $offloadto = [$homeserver];
                   1795:             }
                   1796:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1797:             my %domconfig =
                   1798:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1799:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1800:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1801:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1802:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1803:                     }
                   1804:                 }
                   1805:             } else {
1.1178    raeburn  1806:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1807:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1808:                 if (&hostname($remotebalancer) ne '') {
                   1809:                     $offloadto = [$remotebalancer];
                   1810:                 }
                   1811:             }
                   1812:         } elsif (&hostname($rule_in_effect) ne '') {
                   1813:             $offloadto = [$rule_in_effect];
                   1814:         }
                   1815:     }
                   1816:     return $offloadto;
                   1817: }
                   1818: 
1.1127    raeburn  1819: sub internet_dom_servers {
                   1820:     my ($dom) = @_;
                   1821:     my (%uniqservers,%servers);
                   1822:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1823:     my @machinedoms = &machine_domains($primaryserver);
                   1824:     foreach my $mdom (@machinedoms) {
                   1825:         my %currservers = %servers;
                   1826:         my %server = &get_servers($mdom);
                   1827:         %servers = (%currservers,%server);
                   1828:     }
                   1829:     my %by_hostname;
                   1830:     foreach my $id (keys(%servers)) {
                   1831:         push(@{$by_hostname{$servers{$id}}},$id);
                   1832:     }
                   1833:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1834:         if (@{$by_hostname{$hostname}} > 1) {
                   1835:             my $match = 0;
                   1836:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1837:                 if (&host_domain($id) eq $dom) {
                   1838:                     $uniqservers{$id} = $hostname;
                   1839:                     $match = 1;
                   1840:                 }
                   1841:             }
                   1842:             unless ($match) {
                   1843:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1844:             }
                   1845:         } else {
                   1846:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1847:         }
                   1848:     }
                   1849:     return %uniqservers;
                   1850: }
                   1851: 
1.1347    raeburn  1852: sub trusted_domains {
                   1853:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1854:     my ($trusted,$untrusted);
1.1347    raeburn  1855:     if (&domain($calldom) eq '') {
1.1349    raeburn  1856:         return ($trusted,$untrusted);
1.1347    raeburn  1857:     }
1.1395    raeburn  1858:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1859:         return ($trusted,$untrusted);
1.1347    raeburn  1860:     }
                   1861:     my $callprimary = &domain($calldom,'primary');
                   1862:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1863:     if ($intcalldom eq '') {
1.1349    raeburn  1864:         return ($trusted,$untrusted);
1.1347    raeburn  1865:     }
                   1866: 
                   1867:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1868:     unless (defined($cached)) {
                   1869:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1870:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1871:         $trustconfig = $domconfig{'trust'};
                   1872:     }
                   1873:     if (ref($trustconfig)) {
                   1874:         my (%possexc,%possinc,@allexc,@allinc); 
                   1875:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1876:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1877:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1878:             }
                   1879:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1880:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1881:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1882:             }
                   1883:         }
                   1884:         if (keys(%possexc)) {
                   1885:             if (keys(%possinc)) {
                   1886:                 foreach my $key (sort(keys(%possexc))) {
                   1887:                     next if ($key eq $intcalldom);
                   1888:                     unless ($possinc{$key}) {
                   1889:                         push(@allexc,$key);
                   1890:                     }
                   1891:                 }
                   1892:             } else {
                   1893:                 @allexc = sort(keys(%possexc));
                   1894:             }
                   1895:         }
                   1896:         if (keys(%possinc)) {
                   1897:             $possinc{$intcalldom} = 1;
                   1898:             @allinc = sort(keys(%possinc));
                   1899:         }
                   1900:         if ((@allexc > 0) || (@allinc > 0)) {
                   1901:             my %doms_by_intdom;
                   1902:             my %allintdoms = &all_host_intdom();
                   1903:             my %alldoms = &all_host_domain();
                   1904:             foreach my $key (%allintdoms) {
                   1905:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1906:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1907:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1908:                     }
                   1909:                 } else {
                   1910:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1911:                 }
                   1912:             }
                   1913:             foreach my $exc (@allexc) {
                   1914:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1915:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1916:                 }
                   1917:             }
                   1918:             foreach my $inc (@allinc) {
                   1919:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1920:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1921:                 }
                   1922:             }
                   1923:         }
                   1924:     }
1.1349    raeburn  1925:     return ($trusted,$untrusted);
1.1347    raeburn  1926: }
                   1927: 
                   1928: sub will_trust {
                   1929:     my ($cmdtype,$domain,$possdom) = @_;
                   1930:     return 1 if ($domain eq $possdom);
                   1931:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1932:     my $willtrust; 
                   1933:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1934:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1935:             $willtrust = 1;
                   1936:         }
                   1937:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1938:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1939:             $willtrust = 1;
                   1940:         }
                   1941:     } else {
                   1942:         $willtrust = 1;
                   1943:     }
                   1944:     return $willtrust;
                   1945: }
                   1946: 
1.1       albertel 1947: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1948: 
1.599     albertel 1949: my %homecache;
1.1       albertel 1950: sub homeserver {
1.230     stredwic 1951:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1952:     my $index="$uname:$udom";
1.426     albertel 1953: 
1.599     albertel 1954:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1955: 
                   1956:     my %servers = &get_servers($udom,'library');
                   1957:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1958:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1959: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1960: 
                   1961: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1962: 	if ($answer eq 'found') {
                   1963: 	    delete($badServerCache{$tryserver}); 
                   1964: 	    return $homecache{$index}=$tryserver;
                   1965: 	} elsif ($answer eq 'no_host') {
                   1966: 	    $badServerCache{$tryserver}=1;
                   1967: 	}
1.1       albertel 1968:     }    
                   1969:     return 'no_host';
1.70      www      1970: }
                   1971: 
1.1300    raeburn  1972: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1973: 
                   1974: sub idget {
1.1300    raeburn  1975:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1976:     my %returnhash=();
1.1300    raeburn  1977:     my @ids=(); 
                   1978:     if (ref($idsref) eq 'ARRAY') {
                   1979:         @ids = @{$idsref};
                   1980:     } else {
                   1981:         return %returnhash; 
                   1982:     }
                   1983:     if ($namespace eq '') {
                   1984:         $namespace = 'ids';
                   1985:     }
1.70      www      1986:     
1.841     albertel 1987:     my %servers = &get_servers($udom,'library');
                   1988:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1989: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1990: 	if ($namespace eq 'ids') {
                   1991: 	    $idlist=~tr/A-Z/a-z/;
                   1992: 	}
                   1993: 	my $reply;
                   1994: 	if ($namespace eq 'ids') {
                   1995: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1996: 	} else {
                   1997: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1998: 	}
1.841     albertel 1999: 	my @answer=();
                   2000: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   2001: 	    @answer=split(/\&/,$reply);
                   2002: 	}                    ;
                   2003: 	my $i;
                   2004: 	for ($i=0;$i<=$#ids;$i++) {
                   2005: 	    if ($answer[$i]) {
1.1299    raeburn  2006: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  2007: 	    }
1.841     albertel 2008: 	}
1.1300    raeburn  2009:     }
1.70      www      2010:     return %returnhash;
                   2011: }
                   2012: 
                   2013: # ------------------------------------- Find the IDs behind a list of usernames
                   2014: 
                   2015: sub idrget {
                   2016:     my ($udom,@unames)=@_;
                   2017:     my %returnhash=();
1.800     albertel 2018:     foreach my $uname (@unames) {
                   2019:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 2020:     }
1.70      www      2021:     return %returnhash;
                   2022: }
                   2023: 
1.1300    raeburn  2024: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      2025: 
                   2026: sub idput {
1.1300    raeburn  2027:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      2028:     my %servers=();
1.1300    raeburn  2029:     my %ids=();
                   2030:     my %byid = ();
                   2031:     if (ref($idsref) eq 'HASH') {
                   2032:         %ids=%{$idsref};
                   2033:     }
                   2034:     if ($namespace eq '') {
                   2035:         $namespace = 'ids'; 
                   2036:     }
1.800     albertel 2037:     foreach my $uname (keys(%ids)) {
                   2038: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  2039:         if ($uhom eq '') {
                   2040:             $uhom=&homeserver($uname,$udom);
                   2041:         }
1.70      www      2042:         if ($uhom ne 'no_host') {
1.800     albertel 2043:             my $esc_unam=&escape($uname);
1.1300    raeburn  2044:             if ($namespace eq 'ids') {
                   2045:                 my $id=&escape($ids{$uname});
                   2046:                 $id=~tr/A-Z/a-z/;
                   2047:                 my $esc_unam=&escape($uname);
                   2048:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      2049:             } else {
1.1300    raeburn  2050:                 my @currids = split(/,/,$ids{$uname});
                   2051:                 foreach my $id (@currids) {
                   2052:                     $byid{$uhom}{$id} .= $uname.',';
                   2053:                 }
                   2054:             }
                   2055:         }
                   2056:     }
                   2057:     if ($namespace eq 'clickers') {
                   2058:         foreach my $server (keys(%byid)) {
                   2059:             if (ref($byid{$server}) eq 'HASH') {
                   2060:                 foreach my $id (keys(%{$byid{$server}})) {
                   2061:                     $byid{$server} =~ s/,$//;
                   2062:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   2063:                 }
1.70      www      2064:             }
                   2065:         }
1.191     harris41 2066:     }
1.800     albertel 2067:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2068:         $servers{$server} =~ s/\&$//;
                   2069:         if ($namespace eq 'ids') {     
                   2070:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   2071:         } else {
                   2072:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   2073:         }
1.191     harris41 2074:     }
1.344     www      2075: }
                   2076: 
1.1300    raeburn  2077: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  2078: 
                   2079: sub iddel {
1.1300    raeburn  2080:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  2081:     my %result=();
1.1300    raeburn  2082:     my %ids=();
                   2083:     my %byid = ();
                   2084:     if (ref($idshashref) eq 'HASH') {
                   2085:         %ids=%{$idshashref};
                   2086:     } else {
1.1231    raeburn  2087:         return %result;
                   2088:     }
1.1300    raeburn  2089:     if ($namespace eq '') {
                   2090:         $namespace = 'ids';
                   2091:     }
1.1231    raeburn  2092:     my %servers=();
1.1300    raeburn  2093:     while (my ($id,$unamestr) = each(%ids)) {
                   2094:         if ($namespace eq 'ids') {
                   2095:             my $uhom = $uhome;
                   2096:             if ($uhom eq '') { 
                   2097:                 $uhom=&homeserver($unamestr,$udom);
                   2098:             }
                   2099:             if ($uhom ne 'no_host') {
                   2100:                 $servers{$uhom}.='&'.&escape($id);
                   2101:             }
                   2102:          } else {
                   2103:             my @curritems = split(/,/,$ids{$id});
                   2104:             foreach my $uname (@curritems) {
                   2105:                 my $uhom = $uhome;
                   2106:                 if ($uhom eq '') {
                   2107:                     $uhom=&homeserver($uname,$udom);
                   2108:                 }
                   2109:                 if ($uhom ne 'no_host') { 
                   2110:                     $byid{$uhom}{$id} .= $uname.',';
                   2111:                 }
                   2112:             }
1.1231    raeburn  2113:         }
1.1300    raeburn  2114:     }
                   2115:     if ($namespace eq 'clickers') {
                   2116:         foreach my $server (keys(%byid)) {
                   2117:             if (ref($byid{$server}) eq 'HASH') {
                   2118:                 foreach my $id (keys(%{$byid{$server}})) {
                   2119:                     $byid{$server}{$id} =~ s/,$//;
                   2120:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2121:                 }
1.1231    raeburn  2122:             }
                   2123:         }
                   2124:     }
                   2125:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2126:         $servers{$server} =~ s/\&$//;
                   2127:         if ($namespace eq 'ids') {
                   2128:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2129:         } elsif ($namespace eq 'clickers') {
                   2130:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2131:         }
1.1231    raeburn  2132:     }
                   2133:     return %result;
                   2134: }
                   2135: 
1.1300    raeburn  2136: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2137: 
                   2138: sub updateclickers {
                   2139:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2140:     my %clickers;
                   2141:     if (ref($idshashref) eq 'HASH') {
                   2142:         %clickers=%{$idshashref};
                   2143:     } else {
                   2144:         return;
                   2145:     }
                   2146:     my $items='';
                   2147:     foreach my $item (keys(%clickers)) {
                   2148:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2149:     }
                   2150:     $items=~s/\&$//;
                   2151:     my $request = "updateclickers:$udom:$action:$items";
                   2152:     if ($critical) {
                   2153:         return &critical($request,$uhome);
                   2154:     } else {
                   2155:         return &reply($request,$uhome);
                   2156:     }
                   2157: }
                   2158: 
1.1023    raeburn  2159: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2160: sub dump_dom {
1.1165    droeschl 2161:     my ($namespace, $udom, $regexp) = @_;
                   2162: 
                   2163:     $udom ||= $env{'user.domain'};
                   2164: 
                   2165:     return () unless $udom;
                   2166: 
                   2167:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2168: }
                   2169: 
1.1023    raeburn  2170: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2171: 
                   2172: sub get_dom {
1.1462    raeburn  2173:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267    raeburn  2174:     return if ($udom eq 'public');
1.806     raeburn  2175:     my $items='';
                   2176:     foreach my $item (@$storearr) {
                   2177:         $items.=&escape($item).'&';
                   2178:     }
                   2179:     $items=~s/\&$//;
1.860     raeburn  2180:     if (!$udom) {
                   2181:         $udom=$env{'user.domain'};
1.1267    raeburn  2182:         return if ($udom eq 'public');
1.860     raeburn  2183:         if (defined(&domain($udom,'primary'))) {
                   2184:             $uhome=&domain($udom,'primary');
                   2185:         } else {
1.874     albertel 2186:             undef($uhome);
1.860     raeburn  2187:         }
                   2188:     } else {
                   2189:         if (!$uhome) {
                   2190:             if (defined(&domain($udom,'primary'))) {
                   2191:                 $uhome=&domain($udom,'primary');
                   2192:             }
                   2193:         }
                   2194:     }
                   2195:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2196:         my $rep;
1.1442    raeburn  2197:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2198:             # domain information is hosted on this machine
1.1462    raeburn  2199:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344    raeburn  2200:         } else {
1.1462    raeburn  2201:             if ($encrypt) {
1.1442    raeburn  2202:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2203:             } else {
                   2204:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2205:             }
1.1344    raeburn  2206:         }
1.866     raeburn  2207:         my %returnhash;
1.875     albertel 2208:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2209:             return %returnhash;
                   2210:         }
1.806     raeburn  2211:         my @pairs=split(/\&/,$rep);
                   2212:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2213:             return @pairs;
                   2214:         }
                   2215:         my $i=0;
                   2216:         foreach my $item (@$storearr) {
                   2217:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2218:             $i++;
                   2219:         }
                   2220:         return %returnhash;
                   2221:     } else {
1.880     banghart 2222:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2223:     }
                   2224: }
                   2225: 
                   2226: # -------------------------------------------- put items in domain db files 
                   2227: 
                   2228: sub put_dom {
1.1462    raeburn  2229:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  2230:     if (!$udom) {
                   2231:         $udom=$env{'user.domain'};
                   2232:         if (defined(&domain($udom,'primary'))) {
                   2233:             $uhome=&domain($udom,'primary');
                   2234:         } else {
1.874     albertel 2235:             undef($uhome);
1.860     raeburn  2236:         }
                   2237:     } else {
                   2238:         if (!$uhome) {
                   2239:             if (defined(&domain($udom,'primary'))) {
                   2240:                 $uhome=&domain($udom,'primary');
                   2241:             }
                   2242:         }
                   2243:     } 
                   2244:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2245:         my $items='';
                   2246:         foreach my $item (keys(%$storehash)) {
                   2247:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2248:         }
                   2249:         $items=~s/\&$//;
1.1462    raeburn  2250:         if ($encrypt) {
1.1344    raeburn  2251:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2252:         } else {
                   2253:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2254:         }
1.806     raeburn  2255:     } else {
1.860     raeburn  2256:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2257:     }
                   2258: }
                   2259: 
1.1023    raeburn  2260: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2261: sub newput_dom {
1.1023    raeburn  2262:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2263:     my $result;
                   2264:     if (!$udom) {
                   2265:         $udom=$env{'user.domain'};
                   2266:     }
1.1023    raeburn  2267:     if ($udom) {
                   2268:         my $uname = &get_domainconfiguser($udom);
                   2269:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2270:     }
                   2271:     return $result;
                   2272: }
                   2273: 
1.1023    raeburn  2274: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2275: sub del_dom {
1.1023    raeburn  2276:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2277:     if (ref($storearr) eq 'ARRAY') {
                   2278:         if (!$udom) {
                   2279:             $udom=$env{'user.domain'};
                   2280:         }
1.1023    raeburn  2281:         if ($udom) {
                   2282:             my $uname = &get_domainconfiguser($udom); 
                   2283:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2284:         }
                   2285:     }
                   2286: }
                   2287: 
1.1481    raeburn  2288: sub store_dom {
1.1482    raeburn  2289:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481    raeburn  2290:     $$storehash{'ip'}=&get_requestor_ip();
                   2291:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2292:     my $namevalue='';
                   2293:     foreach my $key (keys(%{$storehash})) {
                   2294:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2295:     }
                   2296:     $namevalue=~s/\&$//;
                   2297:     if (grep { $_ eq $home } current_machine_ids()) {
                   2298:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2299:     } else {
                   2300:         if ($namespace eq 'private') {
                   2301:             return 'refused';
1.1482    raeburn  2302:         } elsif ($encrypt) {
                   2303:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481    raeburn  2304:         } else {
1.1482    raeburn  2305:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481    raeburn  2306:         }
                   2307:     }
                   2308: }
                   2309: 
1.1482    raeburn  2310: sub restore_dom {
                   2311:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2312:     my $answer;
                   2313:     if (grep { $_ eq $home } current_machine_ids()) {
                   2314:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2315:     } elsif ($namespace ne 'private') {
                   2316:         if ($encrypt) {
                   2317:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2318:         } else {
                   2319:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2320:         }
                   2321:     }
                   2322:     my %returnhash=();
                   2323:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
                   2324:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2325:         foreach my $line (split(/\&/,$answer)) {
                   2326:             my ($name,$value)=split(/\=/,$line);
                   2327:             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2328:         }
                   2329:         my $version;
                   2330:         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2331:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2332:                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2333:             }
                   2334:         }
                   2335:     }
                   2336:     return %returnhash;
                   2337: }
                   2338: 
1.1023    raeburn  2339: # ----------------------------------construct domainconfig user for a domain 
                   2340: sub get_domainconfiguser {
                   2341:     my ($udom) = @_;
                   2342:     return $udom.'-domainconfig';
                   2343: }
                   2344: 
1.837     raeburn  2345: sub retrieve_inst_usertypes {
                   2346:     my ($udom) = @_;
                   2347:     my (%returnhash,@order);
1.989     raeburn  2348:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2349:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2350:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2351:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2352:     } else {
                   2353:         if (defined(&domain($udom,'primary'))) {
                   2354:             my $uhome=&domain($udom,'primary');
                   2355:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2356:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2357:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2358:                 return (\%returnhash,\@order);
                   2359:             }
                   2360:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2361:             my @pairs=split(/\&/,$hashitems);
                   2362:             foreach my $item (@pairs) {
                   2363:                 my ($key,$value)=split(/=/,$item,2);
                   2364:                 $key = &unescape($key);
                   2365:                 next if ($key =~ /^error: 2 /);
                   2366:                 $returnhash{$key}=&thaw_unescape($value);
                   2367:             }
                   2368:             my @esc_order = split(/\&/,$orderitems);
                   2369:             foreach my $item (@esc_order) {
                   2370:                 push(@order,&unescape($item));
                   2371:             }
                   2372:         } else {
1.1256    raeburn  2373:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2374:         }
1.1256    raeburn  2375:         return (\%returnhash,\@order);
1.837     raeburn  2376:     }
                   2377: }
                   2378: 
1.868     raeburn  2379: sub is_domainimage {
                   2380:     my ($url) = @_;
1.1468    raeburn  2381:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2382:         if (&domain($1) ne '') {
                   2383:             return '1';
                   2384:         }
                   2385:     }
                   2386:     return;
                   2387: }
                   2388: 
1.899     raeburn  2389: sub inst_directory_query {
                   2390:     my ($srch) = @_;
                   2391:     my $udom = $srch->{'srchdomain'};
                   2392:     my %results;
                   2393:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2394:     my $outcome;
1.899     raeburn  2395:     if ($homeserver ne '') {
1.1357    raeburn  2396:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2397:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2398:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2399:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2400:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2401:                     (($major == 2) && ($minor < 12))) {
                   2402:                     return;
                   2403:                 }
                   2404:             }
                   2405:         }
1.904     albertel 2406: 	my $queryid=&reply("querysend:instdirsearch:".
                   2407: 			   &escape($srch->{'srchby'}).':'.
                   2408: 			   &escape($srch->{'srchterm'}).':'.
                   2409: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2410: 	my $host=&hostname($homeserver);
                   2411: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2412: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2413: 	    return;
                   2414: 	}
                   2415: 	my $response = &get_query_reply($queryid);
                   2416: 	my $maxtries = 5;
                   2417: 	my $tries = 1;
                   2418: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2419: 	    $response = &get_query_reply($queryid);
                   2420: 	    $tries ++;
                   2421: 	}
                   2422: 
                   2423:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2424:             if ($response eq 'unavailable') {
                   2425:                 $outcome = $response;
                   2426:             } else {
                   2427:                 $outcome = 'ok';
                   2428:                 my @matches = split(/\n/,$response);
                   2429:                 foreach my $match (@matches) {
                   2430:                     my ($key,$value) = split(/=/,$match);
                   2431:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2432:                 }
1.899     raeburn  2433:             }
                   2434:         }
                   2435:     }
1.909     raeburn  2436:     return ($outcome,%results);
1.899     raeburn  2437: }
                   2438: 
                   2439: sub usersearch {
                   2440:     my ($srch) = @_;
                   2441:     my $dom = $srch->{'srchdomain'};
                   2442:     my %results;
                   2443:     my %libserv = &all_library();
                   2444:     my $query = 'usersearch';
                   2445:     foreach my $tryserver (keys(%libserv)) {
                   2446:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2447:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2448:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2449:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2450:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2451:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2452:                              (($major == 2) && ($minor < 12)));
                   2453:                 }
                   2454:             }
1.899     raeburn  2455:             my $host=&hostname($tryserver);
                   2456:             my $queryid=
1.911     raeburn  2457:                 &reply("querysend:".&escape($query).':'.
                   2458:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2459:                        &escape($srch->{'srchtype'}).':'.
                   2460:                        &escape($srch->{'srchterm'}),$tryserver);
                   2461:             if ($queryid !~/^\Q$host\E\_/) {
                   2462:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2463:                 next;
1.899     raeburn  2464:             }
                   2465:             my $reply = &get_query_reply($queryid);
                   2466:             my $maxtries = 1;
                   2467:             my $tries = 1;
                   2468:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2469:                 $reply = &get_query_reply($queryid);
                   2470:                 $tries ++;
                   2471:             }
                   2472:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2473:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2474:             } else {
1.911     raeburn  2475:                 my @matches;
                   2476:                 if ($reply =~ /\n/) {
                   2477:                     @matches = split(/\n/,$reply);
                   2478:                 } else {
                   2479:                     @matches = split(/\&/,$reply);
                   2480:                 }
1.899     raeburn  2481:                 foreach my $match (@matches) {
                   2482:                     my ($uname,$udom,%userhash);
1.911     raeburn  2483:                     foreach my $entry (split(/:/,$match)) {
                   2484:                         my ($key,$value) =
                   2485:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2486:                         $userhash{$key} = $value;
                   2487:                         if ($key eq 'username') {
                   2488:                             $uname = $value;
                   2489:                         } elsif ($key eq 'domain') {
                   2490:                             $udom = $value;
1.911     raeburn  2491:                         }
1.899     raeburn  2492:                     }
                   2493:                     $results{$uname.':'.$udom} = \%userhash;
                   2494:                 }
                   2495:             }
                   2496:         }
                   2497:     }
                   2498:     return %results;
                   2499: }
                   2500: 
1.912     raeburn  2501: sub get_instuser {
                   2502:     my ($udom,$uname,$id) = @_;
                   2503:     my $homeserver = &domain($udom,'primary');
                   2504:     my ($outcome,%results);
                   2505:     if ($homeserver ne '') {
                   2506:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2507:                            &escape($id).':'.&escape($udom),$homeserver);
                   2508:         my $host=&hostname($homeserver);
                   2509:         if ($queryid !~/^\Q$host\E\_/) {
                   2510:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2511:             return;
                   2512:         }
                   2513:         my $response = &get_query_reply($queryid);
                   2514:         my $maxtries = 5;
                   2515:         my $tries = 1;
                   2516:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2517:             $response = &get_query_reply($queryid);
                   2518:             $tries ++;
                   2519:         }
                   2520:         if (!&error($response) && $response ne 'refused') {
                   2521:             if ($response eq 'unavailable') {
                   2522:                 $outcome = $response;
                   2523:             } else {
                   2524:                 $outcome = 'ok';
                   2525:                 my @matches = split(/\n/,$response);
                   2526:                 foreach my $match (@matches) {
                   2527:                     my ($key,$value) = split(/=/,$match);
                   2528:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2529:                 }
                   2530:             }
                   2531:         }
                   2532:     }
                   2533:     my %userinfo;
                   2534:     if (ref($results{$uname}) eq 'HASH') {
                   2535:         %userinfo = %{$results{$uname}};
                   2536:     } 
                   2537:     return ($outcome,%userinfo);
                   2538: }
                   2539: 
1.1290    raeburn  2540: sub get_multiple_instusers {
                   2541:     my ($udom,$users,$caller) = @_;
                   2542:     my ($outcome,$results);
                   2543:     if (ref($users) eq 'HASH') {
                   2544:         my $count = keys(%{$users}); 
                   2545:         my $requested = &freeze_escape($users);
                   2546:         my $homeserver = &domain($udom,'primary');
                   2547:         if ($homeserver ne '') {
                   2548:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2549:             my $host=&hostname($homeserver);
                   2550:             if ($queryid !~/^\Q$host\E\_/) {
                   2551:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2552:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2553:                 return ($outcome,$results);
                   2554:             }
                   2555:             my $response = &get_query_reply($queryid);
                   2556:             my $maxtries = 5;
                   2557:             if ($count > 100) {
                   2558:                 $maxtries = 1+int($count/20);
                   2559:             }
                   2560:             my $tries = 1;
                   2561:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2562:                 $response = &get_query_reply($queryid);
                   2563:                 $tries ++;
                   2564:             }
                   2565:             if ($response eq '') {
                   2566:                 $results = {};
                   2567:                 foreach my $key (keys(%{$users})) {
                   2568:                     my ($uname,$id);
                   2569:                     if ($caller eq 'id') {
                   2570:                         $id = $key;
                   2571:                     } else {
                   2572:                         $uname = $key;
                   2573:                     }
                   2574:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2575:                     $outcome = $resp;
1.1290    raeburn  2576:                     if ($resp eq 'ok') {
                   2577:                         %{$results} = (%{$results}, %info);
                   2578:                     } else {
                   2579:                         last;
                   2580:                     }
                   2581:                 }
                   2582:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2583:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2584:                     $outcome = $response;
                   2585:                 } else {
1.1291    raeburn  2586:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2587:                     if ($outcome eq 'ok') {
                   2588:                         $results = &thaw_unescape($userdata); 
                   2589:                     }
                   2590:                 }
                   2591:             }
                   2592:         }
                   2593:     }
                   2594:     return ($outcome,$results);
                   2595: }
                   2596: 
1.912     raeburn  2597: sub inst_rulecheck {
1.923     raeburn  2598:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2599:     my %returnhash;
                   2600:     if ($udom ne '') {
                   2601:         if (ref($rules) eq 'ARRAY') {
                   2602:             @{$rules} = map {&escape($_);} (@{$rules});
                   2603:             my $rulestr = join(':',@{$rules});
                   2604:             my $homeserver=&domain($udom,'primary');
                   2605:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2606:                 my $response;
                   2607:                 if ($item eq 'username') {                
                   2608:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2609:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2610:                                               $homeserver));
1.923     raeburn  2611:                 } elsif ($item eq 'id') {
                   2612:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2613:                                               ':'.&escape($id).':'.$rulestr,
                   2614:                                               $homeserver));
1.945     raeburn  2615:                 } elsif ($item eq 'selfcreate') {
                   2616:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2617:                                                &escape($udom).':'.&escape($uname).
                   2618:                                               ':'.$rulestr,$homeserver));
1.1484    raeburn  2619:                 } elsif ($item eq 'unamemap') {
                   2620:                     $response=&unescape(&reply('instunamemapcheck:'.
                   2621:                                                &escape($udom).':'.&escape($uname).
                   2622:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2623:                 }
1.912     raeburn  2624:                 if ($response ne 'refused') {
                   2625:                     my @pairs=split(/\&/,$response);
                   2626:                     foreach my $item (@pairs) {
                   2627:                         my ($key,$value)=split(/=/,$item,2);
                   2628:                         $key = &unescape($key);
                   2629:                         next if ($key =~ /^error: 2 /);
                   2630:                         $returnhash{$key}=&thaw_unescape($value);
                   2631:                     }
                   2632:                 }
                   2633:             }
                   2634:         }
                   2635:     }
                   2636:     return %returnhash;
                   2637: }
                   2638: 
                   2639: sub inst_userrules {
1.923     raeburn  2640:     my ($udom,$check) = @_;
1.912     raeburn  2641:     my (%ruleshash,@ruleorder);
                   2642:     if ($udom ne '') {
                   2643:         my $homeserver=&domain($udom,'primary');
                   2644:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2645:             my $response;
                   2646:             if ($check eq 'id') {
                   2647:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2648:                                  $homeserver);
1.943     raeburn  2649:             } elsif ($check eq 'email') {
                   2650:                 $response=&reply('instemailrules:'.&escape($udom),
                   2651:                                  $homeserver);
1.1484    raeburn  2652:             } elsif ($check eq 'unamemap') {
                   2653:                 $response=&reply('unamemaprules:'.&escape($udom),
                   2654:                                  $homeserver); 
1.923     raeburn  2655:             } else {
                   2656:                 $response=&reply('instuserrules:'.&escape($udom),
                   2657:                                  $homeserver);
                   2658:             }
1.912     raeburn  2659:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2660:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2661:                 ($response ne 'no_such_host')) {
                   2662:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2663:                 my @pairs=split(/\&/,$hashitems);
                   2664:                 foreach my $item (@pairs) {
                   2665:                     my ($key,$value)=split(/=/,$item,2);
                   2666:                     $key = &unescape($key);
                   2667:                     next if ($key =~ /^error: 2 /);
                   2668:                     $ruleshash{$key}=&thaw_unescape($value);
                   2669:                 }
                   2670:                 my @esc_order = split(/\&/,$orderitems);
                   2671:                 foreach my $item (@esc_order) {
                   2672:                     push(@ruleorder,&unescape($item));
                   2673:                 }
                   2674:             }
                   2675:         }
                   2676:     }
                   2677:     return (\%ruleshash,\@ruleorder);
                   2678: }
                   2679: 
1.976     raeburn  2680: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2681: 
                   2682: sub get_domain_defaults {
1.1240    raeburn  2683:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2684:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2685:     my $cachetime = 60*60*24;
1.1240    raeburn  2686:     unless ($ignore_cache) {
                   2687:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2688:         if (defined($cached)) {
                   2689:             if (ref($result) eq 'HASH') {
                   2690:                 return %{$result};
                   2691:             }
1.943     raeburn  2692:         }
                   2693:     }
                   2694:     my %domdefaults;
                   2695:     my %domconfig =
1.989     raeburn  2696:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2697:                                   'requestcourses','inststatus',
1.1183    raeburn  2698:                                   'coursedefaults','usersessions',
1.1258    raeburn  2699:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2700:                                   'coursecategories','ssl','autoenroll',
1.1482    raeburn  2701:                                   'trust','helpsettings','wafproxy','ltisec'],$domain);
1.1305    raeburn  2702:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2703:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2704:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2705:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2706:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2707:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2708:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2709:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2710:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2711:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2712:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484    raeburn  2713:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2714:     } else {
                   2715:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2716:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2717:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2718:     }
1.976     raeburn  2719:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2720:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2721:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2722:         } else {
                   2723:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2724:         }
1.1177    raeburn  2725:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2726:         foreach my $item (@usertools) {
                   2727:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2728:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2729:             }
                   2730:         }
1.1229    raeburn  2731:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2732:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2733:         }
1.976     raeburn  2734:     }
1.985     raeburn  2735:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2736:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2737:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2738:         }
                   2739:     }
1.1183    raeburn  2740:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2741:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2742:     }
1.989     raeburn  2743:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2744:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2745:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2746:         }
                   2747:     }
1.1047    raeburn  2748:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2749:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2750:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476    raeburn  2751:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277    raeburn  2752:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2753:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2754:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2755:         }
1.1254    raeburn  2756:         foreach my $type (@coursetypes) {
                   2757:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2758:                 unless ($type eq 'community') {
                   2759:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2760:                 }
                   2761:             }
                   2762:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2763:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2764:             }
1.1277    raeburn  2765:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2766:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2767:                     $domdefaults{$type.'postsubtimeout'} = 
                   2768:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2769:                 }
                   2770:             }
1.1230    raeburn  2771:         }
1.1286    raeburn  2772:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2773:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2774:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2775:                 if (@clonecodes) {
                   2776:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2777:                 }
                   2778:             }
                   2779:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2780:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2781:         }
1.1356    raeburn  2782:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2783:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480    raeburn  2784:         }
                   2785:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2786:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2787:         }
1.1047    raeburn  2788:     }
1.1073    raeburn  2789:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2790:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2791:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2792:         }
                   2793:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2794:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2795:         }
1.1279    raeburn  2796:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2797:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2798:         }
1.1440    raeburn  2799:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439    raeburn  2800:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2801:         }
1.1073    raeburn  2802:     }
1.1254    raeburn  2803:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2804:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2805:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2806:                             'approval','limit');
                   2807:             foreach my $type (@coursetypes) {
                   2808:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2809:                     my @mgrdc = ();
                   2810:                     foreach my $item (@settings) {
                   2811:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2812:                             push(@mgrdc,$item);
                   2813:                         }
                   2814:                     }
                   2815:                     if (@mgrdc) {
                   2816:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2817:                     }
                   2818:                 }
                   2819:             }
                   2820:         }
                   2821:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2822:             foreach my $type (@coursetypes) {
                   2823:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2824:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2825:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2826:                     }
                   2827:                 }
                   2828:             }
                   2829:         }
                   2830:     }
1.1258    raeburn  2831:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2832:         $domdefaults{'catauth'} = 'std';
                   2833:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2834:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2835:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2836:         }
                   2837:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2838:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2839:         }
                   2840:     }
1.1315    raeburn  2841:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2842:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2843:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2844:         }
1.1338    raeburn  2845:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2846:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2847:         }
                   2848:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2849:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2850:         }
                   2851:     }
1.1320    raeburn  2852:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2853:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2854:         foreach my $prefix (@prefixes) {
                   2855:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2856:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2857:             }
                   2858:         }
                   2859:     }
1.1314    raeburn  2860:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2861:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477    raeburn  2862:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314    raeburn  2863:     }
1.1332    raeburn  2864:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2865:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2866:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2867:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2868:         }
                   2869:     }
1.1434    raeburn  2870:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449    raeburn  2871:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434    raeburn  2872:             if ($domconfig{'wafproxy'}{$item}) {
                   2873:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2874:             }
                   2875:         }
1.1482    raeburn  2876:     }
                   2877:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2878:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2879:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2880:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2881:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2882:         }
                   2883:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2884:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2885:                 $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2886:             }
                   2887:         }
                   2888:     }
1.1219    raeburn  2889:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2890:     return %domdefaults;
                   2891: }
                   2892: 
1.1412    raeburn  2893: sub get_dom_cats {
                   2894:     my ($dom) = @_;
                   2895:     return unless (&domain($dom));
                   2896:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2897:     unless (defined($cached)) {
                   2898:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2899:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2900:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2901:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2902:             } else {
                   2903:                 $cats = {};
                   2904:             }
                   2905:         } else {
                   2906:             $cats = {};
                   2907:         }
                   2908:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2909:     }
1.1413    raeburn  2910:     return $cats;
                   2911: }
                   2912: 
                   2913: sub get_dom_instcats {
                   2914:     my ($dom) = @_;
                   2915:     return unless (&domain($dom));
                   2916:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2917:     unless (defined($cached)) {
                   2918:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2919:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2920:         if ($totcodes > 0) {
                   2921:             my $caller = 'global';
                   2922:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2923:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2924:                 $instcats = {
                   2925:                                 codes => \%codes,
                   2926:                                 codetitles => \@codetitles,
                   2927:                                 cat_titles => \%cat_titles,
                   2928:                                 cat_order => \%cat_order,
                   2929:                             };
                   2930:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2931:             }
                   2932:         }
                   2933:     }
                   2934:     return $instcats;
                   2935: }
                   2936: 
                   2937: sub retrieve_instcodes {
                   2938:     my ($coursecodes,$dom) = @_;
                   2939:     my $totcodes;
                   2940:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2941:     foreach my $course (keys(%courses)) {
                   2942:         if (ref($courses{$course}) eq 'HASH') {
                   2943:             if ($courses{$course}{'inst_code'} ne '') {
                   2944:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2945:                 $totcodes ++;
                   2946:             }
                   2947:         }
                   2948:     }
                   2949:     return $totcodes;
1.1412    raeburn  2950: }
                   2951: 
1.1311    raeburn  2952: sub course_portal_url {
1.1451    raeburn  2953:     my ($cnum,$cdom,$r) = @_;
1.1311    raeburn  2954:     my $chome = &homeserver($cnum,$cdom);
                   2955:     my $hostname = &hostname($chome);
                   2956:     my $protocol = $protocol{$chome};
                   2957:     $protocol = 'http' if ($protocol ne 'https');
                   2958:     my %domdefaults = &get_domain_defaults($cdom);
                   2959:     my $firsturl;
                   2960:     if ($domdefaults{'portal_def'}) {
                   2961:         $firsturl = $domdefaults{'portal_def'};
                   2962:     } else {
1.1451    raeburn  2963:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2964:         $hostname = $alias if ($alias ne '');
1.1311    raeburn  2965:         $firsturl = $protocol.'://'.$hostname;
                   2966:     }
                   2967:     return $firsturl;
                   2968: }
                   2969: 
1.1407    raeburn  2970: # --------------------------------------------- Get domain config for passwords
                   2971: 
                   2972: sub get_passwdconf {
                   2973:     my ($dom) = @_;
                   2974:     my (%passwdconf,$gotconf,$lookup);
                   2975:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2976:     if (defined($cached)) {
                   2977:         if (ref($result) eq 'HASH') {
                   2978:             %passwdconf = %{$result};
                   2979:             $gotconf = 1;
                   2980:         }
                   2981:     }
                   2982:     unless ($gotconf) {
                   2983:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2984:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2985:             %passwdconf = %{$domconfig{'passwords'}};
                   2986:         }
                   2987:         my $cachetime = 24*60*60;
                   2988:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2989:     }
                   2990:     return %passwdconf;
                   2991: }
                   2992: 
1.344     www      2993: # --------------------------------------------------- Assign a key to a student
                   2994: 
                   2995: sub assign_access_key {
1.364     www      2996: #
                   2997: # a valid key looks like uname:udom#comments
                   2998: # comments are being appended
                   2999: #
1.498     www      3000:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   3001:     $kdom=
1.620     albertel 3002:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      3003:     $knum=
1.620     albertel 3004:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      3005:     $cdom=
1.620     albertel 3006:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3007:     $cnum=
1.620     albertel 3008:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3009:     $udom=$env{'user.name'} unless (defined($udom));
                   3010:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      3011:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      3012:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 3013:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      3014:                                                   # assigned to this person
                   3015:                                                   # - this should not happen,
1.345     www      3016:                                                   # unless something went wrong
                   3017:                                                   # the first time around
                   3018: # ready to assign
1.364     www      3019:         $logentry=$1.'; '.$logentry;
1.496     www      3020:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      3021:                                                  $kdom,$knum) eq 'ok') {
1.345     www      3022: # key now belongs to user
1.346     www      3023: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      3024:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  3025:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      3026:                 return 'ok';
                   3027:             } else {
                   3028:                 return 
                   3029:   'error: Count not permanently assign key, will need to be re-entered later.';
                   3030: 	    }
                   3031:         } else {
                   3032:             return 'error: Could not assign key, try again later.';
                   3033:         }
1.364     www      3034:     } elsif (!$existing{$ckey}) {
1.345     www      3035: # the key does not exist
                   3036: 	return 'error: The key does not exist';
                   3037:     } else {
                   3038: # the key is somebody else's
                   3039: 	return 'error: The key is already in use';
                   3040:     }
1.344     www      3041: }
                   3042: 
1.364     www      3043: # ------------------------------------------ put an additional comment on a key
                   3044: 
                   3045: sub comment_access_key {
                   3046: #
                   3047: # a valid key looks like uname:udom#comments
                   3048: # comments are being appended
                   3049: #
                   3050:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   3051:     $cdom=
1.620     albertel 3052:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      3053:     $cnum=
1.620     albertel 3054:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      3055:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   3056:     if ($existing{$ckey}) {
                   3057:         $existing{$ckey}.='; '.$logentry;
                   3058: # ready to assign
1.367     www      3059:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      3060:                                                  $cdom,$cnum) eq 'ok') {
                   3061: 	    return 'ok';
                   3062:         } else {
                   3063: 	    return 'error: Count not store comment.';
                   3064:         }
                   3065:     } else {
                   3066: # the key does not exist
                   3067: 	return 'error: The key does not exist';
                   3068:     }
                   3069: }
                   3070: 
1.344     www      3071: # ------------------------------------------------------ Generate a set of keys
                   3072: 
                   3073: sub generate_access_keys {
1.364     www      3074:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      3075:     $cdom=
1.620     albertel 3076:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3077:     $cnum=
1.620     albertel 3078:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      3079:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      3080:     unless (($cdom) && ($cnum)) { return 0; }
                   3081:     if ($number>10000) { return 0; }
                   3082:     sleep(2); # make sure don't get same seed twice
                   3083:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   3084:     my $total=0;
                   3085:     for (my $i=1;$i<=$number;$i++) {
                   3086:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   3087:                   sprintf("%lx",int(100000*rand)).'-'.
                   3088:                   sprintf("%lx",int(100000*rand));
                   3089:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   3090:        $newkey=~s/0/h/g; # and also 0 and O
                   3091:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   3092:        if ($existing{$newkey}) {
                   3093:            $i--;
                   3094:        } else {
1.364     www      3095: 	  if (&put('accesskeys',
                   3096:               { $newkey => '# generated '.localtime().
1.620     albertel 3097:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      3098:                            '; '.$logentry },
                   3099: 		   $cdom,$cnum) eq 'ok') {
1.344     www      3100:               $total++;
                   3101: 	  }
                   3102:        }
                   3103:     }
1.620     albertel 3104:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      3105:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   3106:     return $total;
                   3107: }
                   3108: 
                   3109: # ------------------------------------------------------- Validate an accesskey
                   3110: 
                   3111: sub validate_access_key {
                   3112:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   3113:     $cdom=
1.620     albertel 3114:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3115:     $cnum=
1.620     albertel 3116:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3117:     $udom=$env{'user.domain'} unless (defined($udom));
                   3118:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      3119:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 3120:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      3121: }
                   3122: 
                   3123: # ------------------------------------- Find the section of student in a course
1.652     albertel 3124: sub devalidate_getsection_cache {
                   3125:     my ($udom,$unam,$courseid)=@_;
                   3126:     my $hashid="$udom:$unam:$courseid";
                   3127:     &devalidate_cache_new('getsection',$hashid);
                   3128: }
1.298     matthew  3129: 
1.815     albertel 3130: sub courseid_to_courseurl {
                   3131:     my ($courseid) = @_;
                   3132:     #already url style courseid
                   3133:     return $courseid if ($courseid =~ m{^/});
                   3134: 
                   3135:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3136: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3137: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3138: 	return "/$cdom/$cnum";
                   3139:     }
                   3140: 
                   3141:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   3142:     if (exists($courseinfo{'num'})) {
                   3143: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3144:     }
                   3145: 
                   3146:     return undef;
                   3147: }
                   3148: 
1.298     matthew  3149: sub getsection {
                   3150:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3151:     my $cachetime=1800;
1.551     albertel 3152: 
                   3153:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3154:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3155:     if (defined($cached)) { return $result; }
                   3156: 
1.298     matthew  3157:     my %Pending; 
                   3158:     my %Expired;
                   3159:     #
                   3160:     # Each role can either have not started yet (pending), be active, 
                   3161:     #    or have expired.
                   3162:     #
                   3163:     # If there is an active role, we are done.
                   3164:     #
                   3165:     # If there is more than one role which has not started yet, 
                   3166:     #     choose the one which will start sooner
                   3167:     # If there is one role which has not started yet, return it.
                   3168:     #
                   3169:     # If there is more than one expired role, choose the one which ended last.
                   3170:     # If there is a role which has expired, return it.
                   3171:     #
1.815     albertel 3172:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3173:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3174:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3175:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3176:         my $section=$1;
                   3177:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3178:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3179:         my $now=time;
1.548     albertel 3180:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3181:             $Expired{$end}=$section;
                   3182:             next;
                   3183:         }
1.548     albertel 3184:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3185:             $Pending{$start}=$section;
                   3186:             next;
                   3187:         }
1.599     albertel 3188:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3189:     }
                   3190:     #
                   3191:     # Presumedly there will be few matching roles from the above
                   3192:     # loop and the sorting time will be negligible.
                   3193:     if (scalar(keys(%Pending))) {
                   3194:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3195:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3196:     } 
                   3197:     if (scalar(keys(%Expired))) {
                   3198:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3199:         my $time = pop(@sorted);
1.599     albertel 3200:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3201:     }
1.599     albertel 3202:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3203: }
1.70      www      3204: 
1.599     albertel 3205: sub save_cache {
                   3206:     &purge_remembered();
1.722     albertel 3207:     #&Apache::loncommon::validate_page();
1.620     albertel 3208:     undef(%env);
1.780     albertel 3209:     undef($env_loaded);
1.599     albertel 3210: }
1.452     albertel 3211: 
1.599     albertel 3212: my $to_remember=-1;
                   3213: my %remembered;
                   3214: my %accessed;
                   3215: my $kicks=0;
                   3216: my $hits=0;
1.849     albertel 3217: sub make_key {
                   3218:     my ($name,$id) = @_;
1.872     albertel 3219:     if (length($id) > 65 
                   3220: 	&& length(&escape($id)) > 200) {
                   3221: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3222:     }
1.849     albertel 3223:     return &escape($name.':'.$id);
                   3224: }
                   3225: 
1.599     albertel 3226: sub devalidate_cache_new {
                   3227:     my ($name,$id,$debug) = @_;
                   3228:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3229:     my $remembered_id=$name.':'.$id;
1.849     albertel 3230:     $id=&make_key($name,$id);
1.599     albertel 3231:     $memcache->delete($id);
1.1319    damieng  3232:     delete($remembered{$remembered_id});
                   3233:     delete($accessed{$remembered_id});
1.599     albertel 3234: }
                   3235: 
                   3236: sub is_cached_new {
                   3237:     my ($name,$id,$debug) = @_;
1.1319    damieng  3238:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3239:     if (exists($remembered{$remembered_id})) {
                   3240: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3241: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3242: 	$hits++;
1.1319    damieng  3243: 	return ($remembered{$remembered_id},1);
1.599     albertel 3244:     }
1.1319    damieng  3245:     $id=&make_key($name,$id);
1.599     albertel 3246:     my $value = $memcache->get($id);
                   3247:     if (!(defined($value))) {
                   3248: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3249: 	return (undef,undef);
1.416     albertel 3250:     }
1.599     albertel 3251:     if ($value eq '__undef__') {
                   3252: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3253: 	$value=undef;
                   3254:     }
1.1319    damieng  3255:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3256:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3257:     return ($value,1);
                   3258: }
                   3259: 
                   3260: sub do_cache_new {
                   3261:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3262:     my $remembered_id=$name.':'.$id;
1.849     albertel 3263:     $id=&make_key($name,$id);
1.599     albertel 3264:     my $setvalue=$value;
                   3265:     if (!defined($setvalue)) {
                   3266: 	$setvalue='__undef__';
                   3267:     }
1.623     albertel 3268:     if (!defined($time) ) {
                   3269: 	$time=600;
                   3270:     }
1.599     albertel 3271:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3272:     my $result = $memcache->set($id,$setvalue,$time);
                   3273:     if (! $result) {
1.872     albertel 3274: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3275: 	$memcache->disconnect_all();
1.872     albertel 3276:     }
1.600     albertel 3277:     # need to make a copy of $value
1.1319    damieng  3278:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3279:     return $value;
                   3280: }
                   3281: 
                   3282: sub make_room {
1.1319    damieng  3283:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3284: 
1.1319    damieng  3285:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3286:                                     : $value;
1.599     albertel 3287:     if ($to_remember<0) { return; }
1.1319    damieng  3288:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3289:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3290:     my $to_kick;
                   3291:     my $max_time=0;
                   3292:     foreach my $other (keys(%accessed)) {
                   3293: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3294: 	    $to_kick=$other;
                   3295: 	    $max_time=&tv_interval($accessed{$other});
                   3296: 	}
                   3297:     }
                   3298:     delete($remembered{$to_kick});
                   3299:     delete($accessed{$to_kick});
                   3300:     $kicks++;
                   3301:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3302:     return;
                   3303: }
                   3304: 
1.599     albertel 3305: sub purge_remembered {
1.604     albertel 3306:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3307:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3308:     undef(%remembered);
                   3309:     undef(%accessed);
1.428     albertel 3310: }
1.70      www      3311: # ------------------------------------- Read an entry from a user's environment
                   3312: 
                   3313: sub userenvironment {
                   3314:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3315:     my $items;
                   3316:     foreach my $item (@what) {
                   3317:         $items.=&escape($item).'&';
                   3318:     }
                   3319:     $items=~s/\&$//;
1.70      www      3320:     my %returnhash=();
1.1009    raeburn  3321:     my $uhome = &homeserver($unam,$udom);
                   3322:     unless ($uhome eq 'no_host') {
                   3323:         my @answer=split(/\&/, 
                   3324:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3325:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3326:             return %returnhash;
                   3327:         }
1.1009    raeburn  3328:         my $i;
                   3329:         for ($i=0;$i<=$#what;$i++) {
                   3330: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3331:         }
1.70      www      3332:     }
                   3333:     return %returnhash;
1.1       albertel 3334: }
                   3335: 
1.617     albertel 3336: # ---------------------------------------------------------- Get a studentphoto
                   3337: sub studentphoto {
                   3338:     my ($udom,$unam,$ext) = @_;
                   3339:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3340:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3341:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3342:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3343:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3344:             } else {
                   3345:                 my ($result,$perm_reqd)=
1.707     albertel 3346: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3347:                 if ($result eq 'ok') {
                   3348:                     if (!($perm_reqd eq 'yes')) {
                   3349:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3350:                     }
                   3351:                 }
                   3352:             }
                   3353:         }
                   3354:     } else {
                   3355:         my ($result,$perm_reqd) = 
1.707     albertel 3356: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3357:         if ($result eq 'ok') {
                   3358:             if (!($perm_reqd eq 'yes')) {
                   3359:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3360:             }
                   3361:         }
                   3362:     }
                   3363:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3364: }
                   3365: 
                   3366: sub retrievestudentphoto {
                   3367:     my ($udom,$unam,$ext,$type) = @_;
                   3368:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3369:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3370:     if ($ret eq 'ok') {
                   3371:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3372:         if ($type eq 'thumbnail') {
                   3373:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3374:         }
                   3375:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3376:         return $tokenurl;
                   3377:     } else {
                   3378:         if ($type eq 'thumbnail') {
                   3379:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3380:         } else { 
                   3381:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3382:         }
1.617     albertel 3383:     }
                   3384: }
                   3385: 
1.263     www      3386: # -------------------------------------------------------------------- New chat
                   3387: 
                   3388: sub chatsend {
1.724     raeburn  3389:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3390:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3391:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3392:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3393:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3394: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3395: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3396: }
                   3397: 
                   3398: # ------------------------------------------ Find current version of a resource
                   3399: 
                   3400: sub getversion {
                   3401:     my $fname=&clutter(shift);
1.1189    raeburn  3402:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3403:     return &currentversion(&filelocation('',$fname));
                   3404: }
                   3405: 
                   3406: sub currentversion {
                   3407:     my $fname=shift;
                   3408:     my $author=$fname;
                   3409:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3410:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3411:     my $home=&homeserver($uname,$udom);
1.292     www      3412:     if ($home eq 'no_host') { 
                   3413:         return -1; 
                   3414:     }
1.1112    www      3415:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3416:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3417: 	return -1;
                   3418:     }
1.1112    www      3419:     return $answer;
1.263     www      3420: }
                   3421: 
1.1111    www      3422: #
                   3423: # Return special version number of resource if set by override, empty otherwise
                   3424: #
                   3425: sub usedversion {
                   3426:     my $fname=shift;
                   3427:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3428:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3429:     if ($urlversion) { return $urlversion; }
                   3430:     return '';
                   3431: }
                   3432: 
1.1       albertel 3433: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3434: 
1.1       albertel 3435: sub subscribe {
                   3436:     my $fname=shift;
1.761     raeburn  3437:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3438:     $fname=~s/[\n\r]//g;
1.1       albertel 3439:     my $author=$fname;
                   3440:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3441:     my ($udom,$uname)=split(/\//,$author);
                   3442:     my $home=homeserver($uname,$udom);
1.335     albertel 3443:     if ($home eq 'no_host') {
                   3444:         return 'not_found';
1.1       albertel 3445:     }
                   3446:     my $answer=reply("sub:$fname",$home);
1.64      www      3447:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3448: 	$answer.=' by '.$home;
                   3449:     }
1.1       albertel 3450:     return $answer;
                   3451: }
                   3452:     
1.8       www      3453: # -------------------------------------------------------------- Replicate file
                   3454: 
                   3455: sub repcopy {
                   3456:     my $filename=shift;
1.23      www      3457:     $filename=~s/\/+/\//g;
1.1142    raeburn  3458:     my $londocroot = $perlvar{'lonDocRoot'};
                   3459:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3460:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3461:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3462: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3463: 	return &repcopy_userfile($filename);
                   3464:     }
1.532     albertel 3465:     $filename=~s/[\n\r]//g;
1.8       www      3466:     my $transname="$filename.in.transfer";
1.828     www      3467: # FIXME: this should flock
1.607     raeburn  3468:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3469:     my $remoteurl=subscribe($filename);
1.64      www      3470:     if ($remoteurl =~ /^con_lost by/) {
                   3471: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3472:            return 'unavailable';
1.8       www      3473:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3474: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3475: 	   return 'not_found';
1.64      www      3476:     } elsif ($remoteurl =~ /^rejected by/) {
                   3477: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3478:            return 'forbidden';
1.20      www      3479:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3480:            return 'ok';
1.8       www      3481:     } else {
1.290     www      3482:         my $author=$filename;
                   3483:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3484:         my ($udom,$uname)=split(/\//,$author);
                   3485:         my $home=homeserver($uname,$udom);
                   3486:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3487:            my @parts=split(/\//,$filename);
                   3488:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3489:            if ($path ne "$londocroot/res") {
1.8       www      3490:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3491: 	       return 'bad_request';
1.8       www      3492:            }
                   3493:            my $count;
                   3494:            for ($count=5;$count<$#parts;$count++) {
                   3495:                $path.="/$parts[$count]";
                   3496:                if ((-e $path)!=1) {
                   3497: 		   mkdir($path,0777);
                   3498:                }
                   3499:            }
                   3500:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3501:            my $response;
                   3502:            if ($remoteurl =~ m{/raw/}) {
                   3503:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3504:            } else {
                   3505:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3506:            }
1.8       www      3507:            if ($response->is_error()) {
                   3508: 	       unlink($transname);
                   3509:                my $message=$response->status_line;
1.672     albertel 3510:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3511:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3512:                return 'unavailable';
1.8       www      3513:            } else {
1.16      www      3514: 	       if ($remoteurl!~/\.meta$/) {
                   3515:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3516:                   my $mresponse;
                   3517:                   if ($remoteurl =~ m{/raw/}) {
                   3518:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3519:                   } else {
                   3520:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3521:                   }
1.16      www      3522:                   if ($mresponse->is_error()) {
                   3523: 		      unlink($filename.'.meta');
                   3524:                       &logthis(
1.672     albertel 3525:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3526:                   }
                   3527: 	       }
1.8       www      3528:                rename($transname,$filename);
1.607     raeburn  3529:                return 'ok';
1.8       www      3530:            }
1.290     www      3531:        }
1.8       www      3532:     }
1.330     www      3533: }
                   3534: 
1.1422    raeburn  3535: # ------------------------------------------------- Unsubscribe from a resource
                   3536: 
                   3537: sub unsubscribe {
                   3538:     my ($fname) = @_;
                   3539:     my $answer;
                   3540:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3541:     $fname=~s/[\n\r]//g;
                   3542:     my $author=$fname;
                   3543:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3544:     my ($udom,$uname)=split(/\//,$author);
                   3545:     my $home=homeserver($uname,$udom);
                   3546:     if ($home eq 'no_host') {
                   3547:         $answer = 'no_host';
                   3548:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3549:         $answer = 'home';
                   3550:     } else {
                   3551:         my $defdom = $perlvar{'lonDefDomain'};
                   3552:         if (&will_trust('content',$defdom,$udom)) {
                   3553:             $answer = reply("unsub:$fname",$home);
                   3554:         } else {
                   3555:             $answer = 'untrusted';
                   3556:         }
                   3557:     }
                   3558:     return $answer;
                   3559: }
                   3560: 
1.330     www      3561: # ------------------------------------------------ Get server side include body
                   3562: sub ssi_body {
1.381     albertel 3563:     my ($filelink,%form)=@_;
1.606     matthew  3564:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3565:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3566:     }
1.953     www      3567:     my $output='';
                   3568:     my $response;
1.980     raeburn  3569:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3570:        ($output,$response)=&externalssi($filelink);
1.953     www      3571:     } else {
1.1004    droeschl 3572:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3573:        $filelink .= 'inhibitmenu=yes';
1.953     www      3574:        ($output,$response)=&ssi($filelink,%form);
                   3575:     }
1.778     albertel 3576:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3577:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3578:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3579:     if (wantarray) {
                   3580:         return ($output, $response);
                   3581:     } else {
                   3582:         return $output;
                   3583:     }
1.8       www      3584: }
                   3585: 
1.15      www      3586: # --------------------------------------------------------- Server Side Include
                   3587: 
1.782     albertel 3588: sub absolute_url {
1.1447    raeburn  3589:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3590:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3591:     if ($host_name eq '') {
                   3592: 	$host_name = $ENV{'SERVER_NAME'};
                   3593:     }
1.1447    raeburn  3594:     if ($unalias) {
                   3595:         my $alias = &get_proxy_alias();
                   3596:         if ($alias eq $host_name) {
                   3597:             my $lonhost = $perlvar{'lonHostID'};
                   3598:             my $hostname = &hostname($lonhost);
                   3599:             my $lcproto; 
                   3600:             if (($keep_proto) || ($hostname eq '')) {
                   3601:                 $lcproto = $protocol;
                   3602:             } else {
                   3603:                 $lcproto = $protocol{$lonhost};
                   3604:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3605:                 $lcproto .= '://';
                   3606:             }
                   3607:             unless ($hostname eq '') {
                   3608:                 return $lcproto.$hostname;
                   3609:             }
                   3610:         }
                   3611:     }
1.782     albertel 3612:     return $protocol.$host_name;
                   3613: }
                   3614: 
1.942     foxr     3615: #
                   3616: #   Server side include.
                   3617: # Parameters:
                   3618: #  fn     Possibly encrypted resource name/id.
                   3619: #  form   Hash that describes how the rendering should be done
                   3620: #         and other things.
1.944     foxr     3621: # Returns:
1.950     raeburn  3622: #   Scalar context: The content of the response.
                   3623: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3624: #     
1.15      www      3625: sub ssi {
                   3626: 
1.944     foxr     3627:     my ($fn,%form)=@_;
1.1447    raeburn  3628:     my ($host,$request,$response);
                   3629:     $host = &absolute_url('',1);
1.711     albertel 3630: 
                   3631:     $form{'no_update_last_known'}=1;
1.895     albertel 3632:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3633:     if (%form) {
1.1447    raeburn  3634:       $request=new HTTP::Request('POST',$host.$fn);
1.1272    droeschl 3635:       $request->content(join('&',map { 
                   3636:             my $name = escape($_);
                   3637:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3638:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3639:             : &escape($form{$_}) );    
                   3640:         } keys(%form)));
1.23      www      3641:     } else {
1.1447    raeburn  3642:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3643:     }
                   3644: 
1.15      www      3645:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3646:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3647:     my $islocal;
                   3648:     if (($env{'request.course.id'}) &&
                   3649:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3650:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3651:         ($form{'grade_symb'} ne '') &&
                   3652:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3653:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3654:         $islocal = 1;
                   3655:     }
1.1447    raeburn  3656:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
                   3657:                                              '','','',$islocal);
1.1182    foxr     3658: 
1.944     foxr     3659:     if (wantarray) {
1.1345    raeburn  3660: 	return ($response->content, $response);
1.944     foxr     3661:     } else {
1.1345    raeburn  3662: 	return $response->content;
1.942     foxr     3663:     }
1.324     www      3664: }
                   3665: 
                   3666: sub externalssi {
                   3667:     my ($url)=@_;
                   3668:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3669:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3670:     if (wantarray) {
                   3671:         return ($response->content, $response);
                   3672:     } else {
                   3673:         return $response->content;
                   3674:     }
1.15      www      3675: }
1.254     www      3676: 
1.1354    raeburn  3677: 
                   3678: # If the local copy of a replicated resource is outdated, trigger a  
                   3679: # connection from the homeserver to flush the delayed queue. If no update 
                   3680: # happens, remove local copies of outdated resource (and corresponding
                   3681: # metadata file).
                   3682: 
1.1352    raeburn  3683: sub remove_stale_resfile {
                   3684:     my ($url) = @_;
1.1354    raeburn  3685:     my $removed;
1.1352    raeburn  3686:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3687:         my $audom = $1;
                   3688:         my $auname = $2;
1.1353    raeburn  3689:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3690:             my $homeserver = &homeserver($auname,$audom);
                   3691:             unless (($homeserver eq 'no_host') ||
                   3692:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3693:                 my $fname = &filelocation('',$url);
                   3694:                 if (-e $fname) {
                   3695:                     my $hostname = &hostname($homeserver);
                   3696:                     if ($hostname) {
1.1397    raeburn  3697:                         my $protocol = $protocol{$homeserver};
                   3698:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3699:                         my $uri = &declutter($url);
                   3700:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3701:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3702:                         if ($response->is_success()) {
                   3703:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3704:                             my $locmodtime = (stat($fname))[9];
                   3705:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3706:                                 my $stale;
                   3707:                                 my $answer = &reply('pong',$homeserver);
                   3708:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3709:                                     sleep(0.2);
                   3710:                                     $locmodtime = (stat($fname))[9];
                   3711:                                     if ($locmodtime < $remmodtime) {
                   3712:                                         my $posstransfer = $fname.'.in.transfer';
                   3713:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3714:                                             $removed = 1;
                   3715:                                         } else {
                   3716:                                             $stale = 1;
                   3717:                                         }
                   3718:                                     } else {
                   3719:                                         $removed = 1;
                   3720:                                     }
                   3721:                                 } else {
                   3722:                                     $stale = 1;
                   3723:                                 }
                   3724:                                 if ($stale) {
1.1421    raeburn  3725:                                     if (unlink($fname)) {
                   3726:                                         if ($uri!~/\.meta$/) {
                   3727:                                             if (-e $fname.'.meta') {
                   3728:                                                 unlink($fname.'.meta');
                   3729:                                             }
                   3730:                                         }
1.1422    raeburn  3731:                                         my $unsubresult = &unsubscribe($fname);
                   3732:                                         unless ($unsubresult eq 'ok') {
                   3733:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3734:                                         }
1.1421    raeburn  3735:                                         $removed = 1;
1.1354    raeburn  3736:                                     }
1.1352    raeburn  3737:                                 }
                   3738:                             }
                   3739:                         }
                   3740:                     }
                   3741:                 }
                   3742:             }
                   3743:         }
                   3744:     }
1.1354    raeburn  3745:     return $removed;
1.1352    raeburn  3746: }
                   3747: 
1.492     albertel 3748: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3749: 
                   3750: sub allowuploaded {
                   3751:     my ($srcurl,$url)=@_;
                   3752:     $url=&clutter(&declutter($url));
                   3753:     my $dir=$url;
                   3754:     $dir=~s/\/[^\/]+$//;
                   3755:     my %httpref=();
                   3756:     my $httpurl=&hreflocation('',$url);
                   3757:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3758:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3759: }
1.477     raeburn  3760: 
1.1193    raeburn  3761: #
                   3762: # Determine if the current user should be able to edit a particular resource,
                   3763: # when viewing in course context.
                   3764: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3765: #     Functions.
                   3766: # (b) When displaying folder contents in course editor, used to determine if
                   3767: #     "Edit" link will be displayed alongside resource.
                   3768: #
1.1196    raeburn  3769: #  input: six args -- filename (decluttered), course number, course domain,
                   3770: #                   url, symb (if registered) and group (if this is a group
                   3771: #                   item -- e.g., bulletin board, group page etc.).
                   3772: #  output: array of five scalars -- 
1.1193    raeburn  3773: #          $cfile -- url for file editing if editable on current server
                   3774: #          $home -- homeserver of resource (i.e., for author if published,
                   3775: #                                           or course if uploaded.).
                   3776: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3777: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3778: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3779: #
                   3780: 
                   3781: sub can_edit_resource {
1.1194    raeburn  3782:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3783:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3784: #
                   3785: # For aboutme pages user can only edit his/her own.
                   3786: #
1.1199    raeburn  3787:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3788:         my ($sdom,$sname) = ($1,$2);
                   3789:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3790:             $home = $env{'user.home'};
                   3791:             $cfile = $resurl;
                   3792:             if ($env{'form.forceedit'}) {
                   3793:                 $forceview = 1;
                   3794:             } else {
                   3795:                 $forceedit = 1;
                   3796:             }
                   3797:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3798:         } else {
                   3799:             return;
                   3800:         }
                   3801:     }
                   3802: 
                   3803:     if ($env{'request.course.id'}) {
                   3804:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3805:         if ($group ne '') {
                   3806: # if this is a group homepage or group bulletin board, check group privs
                   3807:             my $allowed = 0;
1.1197    raeburn  3808:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3809:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3810:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3811:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3812:                     $allowed = 1;
                   3813:                 }
1.1197    raeburn  3814:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3815:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3816:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3817:                     $allowed = 1;
                   3818:                 }
                   3819:             }
                   3820:             if ($allowed) {
                   3821:                 $home=&homeserver($cnum,$cdom);
                   3822:                 if ($env{'form.forceedit'}) {
                   3823:                     $forceview = 1;
                   3824:                 } else {
                   3825:                     $forceedit = 1;
                   3826:                 }
                   3827:                 $cfile = $resurl;
                   3828:             } else {
                   3829:                 return;
                   3830:             }
                   3831:         } else {
1.1208    raeburn  3832:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3833:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3834:                     return;
                   3835:                 }
                   3836:             } elsif (!$crsedit) {
1.1194    raeburn  3837: #
                   3838: # No edit allowed where CC has switched to student role.
                   3839: #
                   3840:                 return;
                   3841:             }
                   3842:         }
                   3843:     }
                   3844: 
1.1193    raeburn  3845:     if ($file ne '') {
                   3846:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3847:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3848:                 $uploaded = 1;
                   3849:                 $incourse = 1;
1.1193    raeburn  3850:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3851:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3852:                     if ($env{'form.forceedit'}) {
                   3853:                         $forceview = 1;
                   3854:                     } else {
                   3855:                         $forceedit = 1;
                   3856:                     }
1.1194    raeburn  3857:                 }
                   3858:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3859:                 $incourse = 1;
                   3860:                 if ($env{'form.forceedit'}) {
                   3861:                     $forceview = 1;
                   3862:                 } else {
                   3863:                     $forceedit = 1;
                   3864:                 }
                   3865:                 $cfile = $resurl;
                   3866:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3867:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3868:                     $incourse = 1;
                   3869:                     if ($env{'form.forceedit'}) {
                   3870:                         $forceview = 1;
                   3871:                     } else {
                   3872:                         $forceedit = 1;
                   3873:                     }
                   3874:                     $cfile = $resurl;
1.1199    raeburn  3875:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3876:                     $incourse = 1;
                   3877:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3878:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3879:                     $incourse = 1;
1.1199    raeburn  3880:                     if ($env{'form.forceedit'}) {
                   3881:                         $forceview = 1;
                   3882:                     } else {
                   3883:                         $forceedit = 1;
                   3884:                     }
                   3885:                     $cfile = $resurl;
1.1419    raeburn  3886:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3887:                     my ($map,$id,$res) = &decode_symb($symb);
                   3888:                     if ($map =~ /\.page$/) {
                   3889:                         $incourse = 1;
                   3890:                         if ($env{'form.forceedit'}) {
                   3891:                             $forceview = 1;
                   3892:                             $cfile = $map;
                   3893:                         } else {
                   3894:                             $forceedit = 1;
                   3895:                             $cfile =  '/adm/wrapper'.$resurl;
                   3896:                         }
                   3897:                     }
1.1343    raeburn  3898:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3899:                     $incourse = 1;
                   3900:                     if ($env{'form.forceedit'}) {
                   3901:                         $forceview = 1;
                   3902:                     } else {
                   3903:                         $forceedit = 1;
                   3904:                     }
                   3905:                     $cfile = $resurl;
1.1208    raeburn  3906:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3907:                     $incourse = 1;
                   3908:                     if ($env{'form.forceedit'}) {
                   3909:                         $forceview = 1;
                   3910:                     } else {
                   3911:                         $forceedit = 1;
                   3912:                     }
                   3913:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3914:                 }
                   3915:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3916:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3917:                 if (&is_on_map($template)) { 
                   3918:                     $incourse = 1;
                   3919:                     $forceview = 1;
                   3920:                     $cfile = $template;
1.1193    raeburn  3921:                 }
1.1199    raeburn  3922:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  3923:                 $incourse = 1;
                   3924:                 if ($env{'form.forceedit'}) {
                   3925:                     $forceview = 1;
                   3926:                 } else {
                   3927:                     $forceedit = 1;
                   3928:                 }
                   3929:                 $cfile = $resurl;
1.1343    raeburn  3930:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3931:                 $incourse = 1;
                   3932:                 if ($env{'form.forceedit'}) {
                   3933:                     $forceview = 1;
                   3934:                 } else {
                   3935:                     $forceedit = 1;
                   3936:                 }
                   3937:                 $cfile = $resurl;
1.1199    raeburn  3938:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3939:                 $incourse = 1;
                   3940:                 $forceview = 1;
                   3941:                 if ($symb) {
                   3942:                     my ($map,$id,$res)=&decode_symb($symb);
                   3943:                     $env{'request.symb'} = $symb;
                   3944:                     $cfile = &clutter($res);
                   3945:                 } else {
                   3946:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3947:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3948:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3949:                         $cfile = '/adm/wrapper'.$escfile;
                   3950:                     } else {
                   3951:                         $escfile =~ s{^http://}{};
                   3952:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3953:                     }
1.1199    raeburn  3954:                 }
1.1234    raeburn  3955:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3956:                 if ($env{'form.forceedit'}) {
                   3957:                     $forceview = 1;
                   3958:                 } else {
                   3959:                     $forceedit = 1;
                   3960:                 }
                   3961:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3962:             }
                   3963:         }
1.1194    raeburn  3964:         if ($uploaded || $incourse) {
                   3965:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3966:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3967:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3968:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3969:             # Check that the user has permission to edit this resource
                   3970:             my $setpriv = 1;
                   3971:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3972:             if (defined($cfudom)) {
                   3973:                 $home=&homeserver($cfuname,$cfudom);
                   3974:                 $cfile=$file;
                   3975:             }
                   3976:         }
1.1194    raeburn  3977:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3978:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3979:             my @ids=&current_machine_ids();
                   3980:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3981:                 $switchserver=1;
                   3982:             }
                   3983:         }
                   3984:     }
1.1194    raeburn  3985:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3986: }
                   3987: 
                   3988: sub is_course_upload {
                   3989:     my ($file,$cnum,$cdom) = @_;
                   3990:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3991:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3992:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3993:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3994:         return 1;
                   3995:     }
                   3996:     return;
                   3997: }
                   3998: 
1.1194    raeburn  3999: sub in_course {
1.1195    raeburn  4000:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   4001:     if ($hideprivileged) {
                   4002:         my $skipuser;
1.1219    raeburn  4003:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   4004:         my @possdoms = ($cdom);  
                   4005:         if ($coursehash{'checkforpriv'}) { 
                   4006:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   4007:         }
                   4008:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  4009:             $skipuser = 1;
                   4010:             if ($coursehash{'nothideprivileged'}) {
                   4011:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4012:                     my $user;
                   4013:                     if ($item =~ /:/) {
                   4014:                         $user = $item;
                   4015:                     } else {
                   4016:                         $user = join(':',split(/[\@]/,$item));
                   4017:                     }
                   4018:                     if ($user eq $uname.':'.$udom) {
                   4019:                         undef($skipuser);
                   4020:                         last;
                   4021:                     }
                   4022:                 }
                   4023:             }
                   4024:             if ($skipuser) {
                   4025:                 return 0;
                   4026:             }
                   4027:         }
                   4028:     }
1.1194    raeburn  4029:     $type ||= 'any';
                   4030:     if (!defined($cdom) || !defined($cnum)) {
                   4031:         my $cid  = $env{'request.course.id'};
                   4032:         $cdom = $env{'course.'.$cid.'.domain'};
                   4033:         $cnum = $env{'course.'.$cid.'.num'};
                   4034:     }
                   4035:     my $typesref;
1.1195    raeburn  4036:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  4037:         $typesref = ['active','previous','future'];
                   4038:     } elsif ($type eq 'previous' || $type eq 'future') {
                   4039:         $typesref = [$type];
                   4040:     }
                   4041:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   4042:                               $typesref,undef,[$cdom]);
                   4043:     my ($tmp) = keys(%roles);
                   4044:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   4045:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   4046:     if (@course_roles > 0) {
                   4047:         return 1;
                   4048:     }
                   4049:     return 0;
                   4050: }
                   4051: 
1.478     albertel 4052: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 4053: # input: action, courseID, current domain, intended
1.637     raeburn  4054: #        path to file, source of file, instruction to parse file for objects,
                   4055: #        ref to hash for embedded objects,
                   4056: #        ref to hash for codebase of java objects.
1.1095    raeburn  4057: #        reference to scalar to accommodate mime type determined
                   4058: #          from File::MMagic if $parser = parse.
1.637     raeburn  4059: #
1.485     raeburn  4060: # output: url to file (if action was uploaddoc), 
                   4061: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  4062: #
1.478     albertel 4063: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   4064: # course.
1.477     raeburn  4065: #
1.478     albertel 4066: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4067: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   4068: #          course's home server.
1.477     raeburn  4069: #
1.478     albertel 4070: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   4071: #          be copied from $source (current location) to 
                   4072: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4073: #         and will then be copied to
                   4074: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   4075: #         course's home server.
1.485     raeburn  4076: #
1.481     raeburn  4077: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 4078: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  4079: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4080: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   4081: #         in course's home server.
1.637     raeburn  4082: #
1.477     raeburn  4083: 
                   4084: sub process_coursefile {
1.1095    raeburn  4085:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   4086:         $mimetype)=@_;
1.477     raeburn  4087:     my $fetchresult;
1.638     albertel 4088:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  4089:     if ($action eq 'propagate') {
1.638     albertel 4090:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   4091: 			     $home);
1.481     raeburn  4092:     } else {
1.477     raeburn  4093:         my $fpath = '';
                   4094:         my $fname = $file;
1.478     albertel 4095:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  4096:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  4097:         my $filepath = &build_filepath($fpath);
1.481     raeburn  4098:         if ($action eq 'copy') {
                   4099:             if ($source eq '') {
                   4100:                 $fetchresult = 'no source file';
                   4101:                 return $fetchresult;
                   4102:             } else {
                   4103:                 my $destination = $filepath.'/'.$fname;
                   4104:                 rename($source,$destination);
                   4105:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4106:                                  $home);
1.481     raeburn  4107:             }
                   4108:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  4109:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 4110:             print $fh $env{'form.'.$source};
1.481     raeburn  4111:             close($fh);
1.637     raeburn  4112:             if ($parser eq 'parse') {
1.1024    raeburn  4113:                 my $mm = new File::MMagic;
1.1095    raeburn  4114:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   4115:                 if ($type eq 'text/html') {
1.1024    raeburn  4116:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   4117:                     unless ($parse_result eq 'ok') {
                   4118:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   4119:                     }
1.637     raeburn  4120:                 }
1.1095    raeburn  4121:                 if (ref($mimetype)) {
                   4122:                     $$mimetype = $type;
                   4123:                 } 
1.637     raeburn  4124:             }
1.477     raeburn  4125:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4126:                                  $home);
1.481     raeburn  4127:             if ($fetchresult eq 'ok') {
                   4128:                 return '/uploaded/'.$fpath.'/'.$fname;
                   4129:             } else {
                   4130:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4131:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  4132:                 return '/adm/notfound.html';
                   4133:             }
1.477     raeburn  4134:         }
                   4135:     }
1.485     raeburn  4136:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4137:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4138:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4139:     }
                   4140:     return $fetchresult;
                   4141: }
                   4142: 
1.637     raeburn  4143: sub build_filepath {
                   4144:     my ($fpath) = @_;
                   4145:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4146:     unless ($fpath eq '') {
                   4147:         my @parts=split('/',$fpath);
                   4148:         foreach my $part (@parts) {
                   4149:             $filepath.= '/'.$part;
                   4150:             if ((-e $filepath)!=1) {
                   4151:                 mkdir($filepath,0777);
                   4152:             }
                   4153:         }
                   4154:     }
                   4155:     return $filepath;
                   4156: }
                   4157: 
                   4158: sub store_edited_file {
1.638     albertel 4159:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4160:     my $file = $primary_url;
                   4161:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4162:     my $fpath = '';
                   4163:     my $fname = $file;
                   4164:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4165:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4166:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4167:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4168:     print $fh $content;
                   4169:     close($fh);
1.638     albertel 4170:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4171:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4172: 			  $home);
1.637     raeburn  4173:     if ($$fetchresult eq 'ok') {
                   4174:         return '/uploaded/'.$fpath.'/'.$fname;
                   4175:     } else {
1.638     albertel 4176:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4177: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4178:         return '/adm/notfound.html';
                   4179:     }
                   4180: }
                   4181: 
1.531     albertel 4182: sub clean_filename {
1.831     albertel 4183:     my ($fname,$args)=@_;
1.315     www      4184: # Replace Windows backslashes by forward slashes
1.257     www      4185:     $fname=~s/\\/\//g;
1.831     albertel 4186:     if (!$args->{'keep_path'}) {
                   4187:         # Get rid of everything but the actual filename
                   4188: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4189:     }
1.315     www      4190: # Replace spaces by underscores
                   4191:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4192: # Transliterate non-ascii text to ascii
                   4193:     my $lang = &Apache::lonlocal::current_language();
                   4194:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4195: # Replace all other weird characters by nothing
1.831     albertel 4196:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4197: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4198: # numbers
                   4199:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443    raeburn  4200: # Replace three or more adjacent underscores with one for consistency 
                   4201: # with loncfile::filename_check() so complete url can be extracted by
                   4202: # lonnet::decode_symb()
                   4203:     $fname=~s/_{3,}/_/g;
1.531     albertel 4204:     return $fname;
                   4205: }
1.1406    raeburn  4206: 
1.1051    raeburn  4207: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4208: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4209: # image with the same aspect ratio as the original, but with dimensions which do 
                   4210: # not exceed $resizewidth and $resizeheight.
                   4211:  
1.984     neumanie 4212: sub resizeImage {
1.1051    raeburn  4213:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4214:     my $ima = Image::Magick->new;
                   4215:     my $resized;
                   4216:     if (-e $img_path) {
                   4217:         $ima->Read($img_path);
                   4218:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4219:             my $width = $ima->Get('width');
                   4220:             my $height = $ima->Get('height');
                   4221:             if ($width > $resizewidth) {
                   4222: 	        my $factor = $width/$resizewidth;
                   4223:                 my $newheight = $height/$factor;
                   4224:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4225:                 $resized = 1;
                   4226:             }
                   4227:         }
                   4228:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4229:             my $width = $ima->Get('width');
                   4230:             my $height = $ima->Get('height');
                   4231:             if ($height > $resizeheight) {
                   4232:                 my $factor = $height/$resizeheight;
                   4233:                 my $newwidth = $width/$factor;
                   4234:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4235:                 $resized = 1;
                   4236:             }
                   4237:         }
                   4238:         if ($resized) {
                   4239:             $ima->Write($img_path);
                   4240:         }
                   4241:     }
                   4242:     return;
1.977     amueller 4243: }
                   4244: 
1.608     albertel 4245: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4246: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4247: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4248: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  4249: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  4250: #                   if 'coursedoc': upload to the current course
                   4251: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4252: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4253: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4254: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4255: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4256: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4257: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4258: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4259: #        $allfiles - reference to hash for embedded objects
                   4260: #        $codebase - reference to hash for codebase of java objects
                   4261: #        $desuname - username for permanent storage of uploaded file
                   4262: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4263: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4264: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4265: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4266: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4267: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4268: #                    from File::MMagic.
1.858     raeburn  4269: # 
1.686     albertel 4270: # output: url of file in userspace, or error: <message> 
                   4271: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4272: 
1.531     albertel 4273: sub userfileupload {
1.1090    raeburn  4274:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4275:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4276:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4277:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4278:     $fname=&clean_filename($fname);
1.1090    raeburn  4279:     # See if there is anything left
1.257     www      4280:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4281:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4282:     if ($fname =~ /^\./) {
                   4283:         my ($s,$usec) = &gettimeofday();
                   4284:         while (length($usec) < 6) {
                   4285:             $usec = '0'.$usec;
                   4286:         }
                   4287:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4288:     }
1.1090    raeburn  4289:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4290:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4291:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4292:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4293:         my $now = time;
1.1090    raeburn  4294:         my $filepath;
1.1095    raeburn  4295:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4296:              $filepath = 'tmp/helprequests/'.$now;
                   4297:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4298:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4299:                          '_'.$env{'user.domain'}.'/pending';
                   4300:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4301:             my ($docuname,$docudom);
1.1350    raeburn  4302:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4303:                 $docudom = $destudom;
                   4304:             } else {
                   4305:                 $docudom = $env{'user.domain'};
                   4306:             }
1.1350    raeburn  4307:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4308:                 $docuname = $destuname;
                   4309:             } else {
                   4310:                 $docuname = $env{'user.name'};
                   4311:             }
                   4312:             if (exists($env{'form.group'})) {
                   4313:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4314:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4315:             }
                   4316:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4317:             if ($context eq 'canceloverwrite') {
                   4318:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4319:                 if (-e  $tempfile) {
                   4320:                     my @info = stat($tempfile);
                   4321:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4322:                         unlink($tempfile);
                   4323:                     }
                   4324:                 }
                   4325:                 return;
1.523     raeburn  4326:             }
                   4327:         }
1.1090    raeburn  4328:         # Create the directory if not present
1.741     raeburn  4329:         my @parts=split(/\//,$filepath);
                   4330:         my $fullpath = $perlvar{'lonDaemons'};
                   4331:         for (my $i=0;$i<@parts;$i++) {
                   4332:             $fullpath .= '/'.$parts[$i];
                   4333:             if ((-e $fullpath)!=1) {
                   4334:                 mkdir($fullpath,0777);
                   4335:             }
                   4336:         }
1.1359    raeburn  4337:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4338:         print $fh $env{'form.'.$formname};
                   4339:         close($fh);
1.1090    raeburn  4340:         if ($context eq 'existingfile') {
                   4341:             my @info = stat($fullpath.'/'.$fname);
                   4342:             return ($fullpath.'/'.$fname,$info[9]);
                   4343:         } else {
                   4344:             return $fullpath.'/'.$fname;
                   4345:         }
1.523     raeburn  4346:     }
1.995     raeburn  4347:     if ($subdir eq 'scantron') {
                   4348:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4349:     } else {
1.995     raeburn  4350:         $fname="$subdir/$fname";
                   4351:     }
1.1090    raeburn  4352:     if ($context eq 'coursedoc') {
1.638     albertel 4353: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4354: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4355:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4356:             return &finishuserfileupload($docuname,$docudom,
                   4357: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4358: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4359:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4360:         } else {
1.1218    raeburn  4361:             if ($env{'form.folder'}) {
                   4362:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4363:             }
1.638     albertel 4364:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4365: 				       $fname,$formname,$parser,
1.1095    raeburn  4366: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4367:         }
1.719     banghart 4368:     } elsif (defined($destuname)) {
                   4369:         my $docuname=$destuname;
                   4370:         my $docudom=$destudom;
1.860     raeburn  4371: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4372: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4373:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4374:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4375:     } else {
1.638     albertel 4376:         my $docuname=$env{'user.name'};
                   4377:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4378:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4379:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4380:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4381:         }
1.860     raeburn  4382: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4383: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4384:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4385:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4386:     }
1.271     www      4387: }
                   4388: 
                   4389: sub finishuserfileupload {
1.860     raeburn  4390:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4391:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4392:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4393:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4394:   
1.860     raeburn  4395:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4396:     $file=$fname;
                   4397:     if ($fname=~m|/|) {
                   4398:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4399: 	$path.=$fnamepath.'/';
                   4400:     }
1.259     www      4401:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4402:     my $count;
                   4403:     for ($count=4;$count<=$#parts;$count++) {
                   4404:         $filepath.="/$parts[$count]";
                   4405:         if ((-e $filepath)!=1) {
                   4406: 	    mkdir($filepath,0777);
                   4407:         }
                   4408:     }
1.984     neumanie 4409: 
1.258     www      4410: # Save the file
                   4411:     {
1.1359    raeburn  4412: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4413: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4414: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4415: 	    return '/adm/notfound.html';
                   4416: 	}
1.1090    raeburn  4417:         if ($context eq 'overwrite') {
1.1117    foxr     4418:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4419:             my $target = $filepath.'/'.$file;
                   4420:             if (-e $source) {
                   4421:                 my @info = stat($source);
                   4422:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4423:                     unless (&File::Copy::move($source,$target)) {
                   4424:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4425:                         return "Moving from $source failed";
                   4426:                     }
                   4427:                 } else {
                   4428:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4429:                 }
                   4430:             } else {
                   4431:                 return "Temporary file: $source missing";
                   4432:             }
                   4433:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4434: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4435: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4436: 	    return '/adm/notfound.html';
                   4437: 	}
1.570     albertel 4438: 	close(FH);
1.1051    raeburn  4439:         if ($resizewidth && $resizeheight) {
                   4440:             my $mm = new File::MMagic;
                   4441:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4442:             if ($mime_type =~ m{^image/}) {
                   4443: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4444:             }  
1.977     amueller 4445: 	}
1.258     www      4446:     }
1.1152    raeburn  4447:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4448:         if (ref($mimetype)) {
                   4449:             if ($$mimetype eq '') {
                   4450:                 my $mm = new File::MMagic;
                   4451:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4452:                 $$mimetype = $type;
                   4453:             }
                   4454:         }
                   4455:     }
1.1401    raeburn  4456:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4457:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4458:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4459:                                                        $allfiles,$codebase);
                   4460:             unless ($parse_result eq 'ok') {
                   4461:                 &logthis('Failed to parse '.$filepath.$file.
                   4462: 	   	         ' for embedded media: '.$parse_result); 
                   4463:             }
1.637     raeburn  4464:         }
1.1401    raeburn  4465:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4466:         my $format = $env{'form.scantron_format'};
                   4467:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4468:     }
1.860     raeburn  4469:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4470:         my $input = $filepath.'/'.$file;
                   4471:         my $output = $filepath.'/'.'tn-'.$file;
                   4472:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4473:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4474:         system({$args[0]} @args);
1.860     raeburn  4475:         if (-e $filepath.'/'.'tn-'.$file) {
                   4476:             $fetchthumb  = 1; 
                   4477:         }
                   4478:     }
1.858     raeburn  4479:  
1.259     www      4480: # Notify homeserver to grep it
                   4481: #
1.984     neumanie 4482:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4483:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4484:     if ($fetchresult eq 'ok') {
1.860     raeburn  4485:         if ($fetchthumb) {
                   4486:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4487:             if ($thumbresult ne 'ok') {
                   4488:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4489:                          $docuhome.': '.$thumbresult);
                   4490:             }
                   4491:         }
1.259     www      4492: #
1.258     www      4493: # Return the URL to it
1.494     albertel 4494:         return '/uploaded/'.$path.$file;
1.263     www      4495:     } else {
1.494     albertel 4496:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4497: 		 ': '.$fetchresult);
1.263     www      4498:         return '/adm/notfound.html';
1.858     raeburn  4499:     }
1.493     albertel 4500: }
                   4501: 
1.637     raeburn  4502: sub extract_embedded_items {
1.961     raeburn  4503:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4504:     my @state = ();
1.1164    raeburn  4505:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4506:     my %javafiles = (
                   4507:                       codebase => '',
                   4508:                       code => '',
                   4509:                       archive => ''
                   4510:                     );
                   4511:     my %mediafiles = (
                   4512:                       src => '',
                   4513:                       movie => '',
                   4514:                      );
1.648     raeburn  4515:     my $p;
                   4516:     if ($content) {
                   4517:         $p = HTML::LCParser->new($content);
                   4518:     } else {
1.961     raeburn  4519:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4520:     }
1.641     albertel 4521:     while (my $t=$p->get_token()) {
1.640     albertel 4522: 	if ($t->[0] eq 'S') {
                   4523: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4524: 	    push(@state, $tagname);
1.648     raeburn  4525:             if (lc($tagname) eq 'allow') {
                   4526:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4527:             }
1.640     albertel 4528: 	    if (lc($tagname) eq 'img') {
                   4529: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4530: 	    }
1.886     albertel 4531: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4532:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4533:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4534:                 }
1.886     albertel 4535: 	    }
1.645     raeburn  4536:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4537:                 my $src;
1.645     raeburn  4538:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4539:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4540:                 } else {
1.1164    raeburn  4541:                     if ($attr->{'src'} ne '') {
                   4542:                         $src = $attr->{'src'};
                   4543:                         &add_filetype($allfiles,$src,'src');
                   4544:                     }
                   4545:                 }
                   4546:                 my $text = $p->get_trimmed_text();
                   4547:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4548:                     my @swfargs = split(/,/,$1);
                   4549:                     foreach my $item (@swfargs) {
                   4550:                         $item =~ s/["']//g;
                   4551:                         $item =~ s/^\s+//;
                   4552:                         $item =~ s/\s+$//;
                   4553:                     }
                   4554:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4555:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4556:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4557:                         } else {
                   4558:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4559:                         }
                   4560:                     }
1.645     raeburn  4561:                 }
                   4562:             }
                   4563:             if (lc($tagname) eq 'link') {
                   4564:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4565:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4566:                 }
                   4567:             }
1.640     albertel 4568: 	    if (lc($tagname) eq 'object' ||
                   4569: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4570: 		foreach my $item (keys(%javafiles)) {
                   4571: 		    $javafiles{$item} = '';
                   4572: 		}
1.1164    raeburn  4573:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4574:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4575:                 }
1.640     albertel 4576: 	    }
                   4577: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4578: 		my $name = lc($attr->{'name'});
                   4579: 		foreach my $item (keys(%javafiles)) {
                   4580: 		    if ($name eq $item) {
                   4581: 			$javafiles{$item} = $attr->{'value'};
                   4582: 			last;
                   4583: 		    }
                   4584: 		}
1.1164    raeburn  4585:                 my $pathfrom;
1.640     albertel 4586: 		foreach my $item (keys(%mediafiles)) {
                   4587: 		    if ($name eq $item) {
1.1164    raeburn  4588:                         $pathfrom = $attr->{'value'};
                   4589:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4590: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4591: 			last;
                   4592: 		    }
                   4593: 		}
1.1164    raeburn  4594:                 if ($name eq 'flashvars') {
                   4595:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4596:                 }
                   4597:                 if ($pathfrom ne '') {
                   4598:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4599:                                          $pathfrom);
                   4600:                 }
1.640     albertel 4601: 	    }
                   4602: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4603: 		foreach my $item (keys(%javafiles)) {
                   4604: 		    if ($attr->{$item}) {
                   4605: 			$javafiles{$item} = $attr->{$item};
                   4606: 			last;
                   4607: 		    }
                   4608: 		}
                   4609: 		foreach my $item (keys(%mediafiles)) {
                   4610: 		    if ($attr->{$item}) {
                   4611: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4612: 			last;
                   4613: 		    }
                   4614: 		}
1.1164    raeburn  4615:                 if (lc($tagname) eq 'embed') {
                   4616:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4617:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4618:                                              $attr->{'src'});
                   4619:                     }
                   4620:                 }
1.640     albertel 4621: 	    }
1.1243    raeburn  4622:             if (lc($tagname) eq 'iframe') {
                   4623:                 my $src = $attr->{'src'} ;
                   4624:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4625:                     &add_filetype($allfiles,$src,'src');
                   4626:                 } elsif ($src =~ m{^/}) {
                   4627:                     if ($env{'request.course.id'}) {
                   4628:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4629:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4630:                         my $url = &hreflocation('',$fullpath);
                   4631:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4632:                             my $relpath = $1;
                   4633:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4634:                                 &add_filetype($allfiles,$1,'src');
                   4635:                             }
                   4636:                         }
                   4637:                     }
                   4638:                 }
                   4639:             }
1.1164    raeburn  4640:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4641:                 pop(@state);
1.1164    raeburn  4642:             }
1.640     albertel 4643: 	} elsif ($t->[0] eq 'E') {
                   4644: 	    my ($tagname) = ($t->[1]);
                   4645: 	    if ($javafiles{'codebase'} ne '') {
                   4646: 		$javafiles{'codebase'} .= '/';
                   4647: 	    }  
                   4648: 	    if (lc($tagname) eq 'applet' ||
                   4649: 		lc($tagname) eq 'object' ||
                   4650: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4651: 		) {
                   4652: 		foreach my $item (keys(%javafiles)) {
                   4653: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4654: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4655: 			&add_filetype($allfiles,$file,$item);
                   4656: 		    }
                   4657: 		}
                   4658: 	    } 
                   4659: 	    pop @state;
                   4660: 	}
                   4661:     }
1.1164    raeburn  4662:     foreach my $id (sort(keys(%flashvars))) {
                   4663:         if ($shockwave{$id} ne '') {
                   4664:             my @pairs = split(/\&/,$flashvars{$id});
                   4665:             foreach my $pair (@pairs) {
                   4666:                 my ($key,$value) = split(/\=/,$pair);
                   4667:                 if ($key eq 'thumb') {
                   4668:                     &add_filetype($allfiles,$value,$key);
                   4669:                 } elsif ($key eq 'content') {
                   4670:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4671:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4672:                     if ($ext ne '') {
                   4673:                         &add_filetype($allfiles,$path.$value,$ext);
                   4674:                     }
                   4675:                 }
                   4676:             }
                   4677:         }
                   4678:     }
1.637     raeburn  4679:     return 'ok';
                   4680: }
                   4681: 
1.639     albertel 4682: sub add_filetype {
                   4683:     my ($allfiles,$file,$type)=@_;
                   4684:     if (exists($allfiles->{$file})) {
                   4685: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4686: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4687: 	}
                   4688:     } else {
                   4689: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4690:     }
                   4691: }
                   4692: 
1.1164    raeburn  4693: sub embedded_dependency {
                   4694:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4695:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4696:         if (($identifier ne '') &&
                   4697:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4698:             ($pathfrom ne '')) {
                   4699:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4700:             foreach my $dep (@{$related->{$identifier}}) {
                   4701:                 &add_filetype($allfiles,$path.$dep,'object');
                   4702:             }
                   4703:         }
                   4704:     }
                   4705:     return;
                   4706: }
                   4707: 
1.1401    raeburn  4708: sub bubblesheet_converter {
                   4709:     my ($cdom,$fullpath,$config,$format) = @_;
                   4710:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4711:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4712:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4713:         my (%csvcols,%csvoptions);
                   4714:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4715:             %csvcols = %{$config->{'fields'}};
                   4716:         }
                   4717:         if (ref($config->{'options'}) eq 'HASH') {
                   4718:             %csvoptions = %{$config->{'options'}};
                   4719:         }
1.1401    raeburn  4720:         my %csvbynum = reverse(%csvcols);
                   4721:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4722:         if (keys(%scantronconf)) {
                   4723:             my %bynum = (
                   4724:                           $scantronconf{CODEstart} => 'CODEstart',
                   4725:                           $scantronconf{IDstart}   => 'IDstart',
                   4726:                           $scantronconf{PaperID}   => 'PaperID',
                   4727:                           $scantronconf{FirstName} => 'FirstName',
                   4728:                           $scantronconf{LastName}  => 'LastName',
                   4729:                           $scantronconf{Qstart}    => 'Qstart',
                   4730:                         );
                   4731:             my @ordered;
                   4732:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4733:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4734:             }
                   4735:             my %mapstart = (
                   4736:                               CODEstart => 'CODE',
                   4737:                               IDstart   => 'ID',
                   4738:                               PaperID   => 'PaperID',
                   4739:                               FirstName => 'FirstName',
                   4740:                               LastName  => 'LastName',
                   4741:                               Qstart    => 'FirstQuestion',
                   4742:                            );
                   4743:             my %maplength = (
                   4744:                               CODEstart => 'CODElength',
                   4745:                               IDstart   => 'IDlength',
                   4746:                               PaperID   => 'PaperIDlength',
                   4747:                               FirstName => 'FirstNamelength',
                   4748:                               LastName  => 'LastNamelength',
                   4749:             );
                   4750:             if (open(my $fh,'<',$fullpath)) {
                   4751:                 my $output;
1.1403    raeburn  4752:                 my %lettdig = &letter_to_digits();
                   4753:                 my %diglett = reverse(%lettdig);
                   4754:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4755:                 my $num = 0;
1.1401    raeburn  4756:                 while (my $line=<$fh>) {
1.1404    raeburn  4757:                     $num ++;
                   4758:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4759:                     $line =~ s{[\r\n]+$}{};
                   4760:                     my %found;
1.1475    raeburn  4761:                     my @values = split(/,/,$line,-1);
1.1401    raeburn  4762:                     my ($qstart,$record);
                   4763:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4764:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4765:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4766:                             if ($values[$i] eq '') {
                   4767:                                 $values[$i] = $scantronconf{'Qoff'};
                   4768:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4769:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4770:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4771:                                 }
                   4772:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4773:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4774:                                     $values[$i] = $diglett{$values[$i]};
                   4775:                                 }
                   4776:                             } else {
                   4777:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4778:                                     my $digit;
                   4779:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4780:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4781:                                         if ($values[$i] eq 'J') {
                   4782:                                             $digit += $numletts;
                   4783:                                         }
                   4784:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4785:                                         $digit = $values[$i]-1;
                   4786:                                         if ($values[$i] eq '0') {
                   4787:                                             $digit += $numletts;
                   4788:                                         }
                   4789:                                     }
                   4790:                                     my $qval='';
                   4791:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4792:                                         if ($j == $digit) {
                   4793:                                             $qval .= $scantronconf{'Qon'};
                   4794:                                         } else {
                   4795:                                             $qval .= $scantronconf{'Qoff'};
                   4796:                                         }
                   4797:                                     }
                   4798:                                     $values[$i] = $qval;
                   4799:                                 }
                   4800:                             }
                   4801:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4802:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4803:                             }
                   4804:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4805:                             if ($numblank > 0) {
                   4806:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4807:                             }
1.1401    raeburn  4808:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4809:                                 $qstart = $i;
1.1403    raeburn  4810:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4811:                             } else {
1.1403    raeburn  4812:                                 $found{'FirstQuestion'} .= $values[$i];
                   4813:                             }
                   4814:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4815:                             if ($csvoptions{'rem'}) {
                   4816:                                 $values[$i] =~ s/^\s+//;
                   4817:                             }
                   4818:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4819:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4820:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4821:                                 }
                   4822:                             }
                   4823:                             $found{$csvbynum{$i}} = $values[$i];
                   4824:                         }
                   4825:                     }
                   4826:                     foreach my $item (@ordered) {
                   4827:                         my $currlength = 1+length($record);
                   4828:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4829:                         if ($numspaces > 0) {
                   4830:                             $record .= (' ' x $numspaces);
                   4831:                         }
                   4832:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4833:                             unless ($item eq 'Qstart') {
                   4834:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4835:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4836:                                 }
                   4837:                             }
                   4838:                             $record .= $found{$mapstart{$item}};
                   4839:                         }
                   4840:                     }
                   4841:                     $output .= "$record\n";
                   4842:                 }
                   4843:                 close($fh);
                   4844:                 if ($output) {
                   4845:                     if (open(my $fh,'>',$fullpath)) {
                   4846:                         print $fh $output;
                   4847:                         close($fh);
                   4848:                     }
                   4849:                 }
                   4850:             }
                   4851:         }
                   4852:         return;
                   4853:     }
                   4854: }
                   4855: 
1.1403    raeburn  4856: sub letter_to_digits {
                   4857:     my %lettdig = (
                   4858:                     A => 1,
                   4859:                     B => 2,
                   4860:                     C => 3,
                   4861:                     D => 4,
                   4862:                     E => 5,
                   4863:                     F => 6,
                   4864:                     G => 7,
                   4865:                     H => 8,
                   4866:                     I => 9,
                   4867:                     J => 0,
                   4868:                   );
                   4869:     return %lettdig;
                   4870: }
                   4871: 
1.1401    raeburn  4872: sub get_scantron_config {
                   4873:     my ($which,$cdom) = @_;
                   4874:     my @lines = &get_scantronformat_file($cdom);
                   4875:     my %config;
                   4876:     #FIXME probably should move to XML it has already gotten a bit much now
                   4877:     foreach my $line (@lines) {
                   4878:         my ($name,$descrip)=split(/:/,$line);
                   4879:         if ($name ne $which ) { next; }
                   4880:         chomp($line);
                   4881:         my @config=split(/:/,$line);
                   4882:         $config{'name'}=$config[0];
                   4883:         $config{'description'}=$config[1];
                   4884:         $config{'CODElocation'}=$config[2];
                   4885:         $config{'CODEstart'}=$config[3];
                   4886:         $config{'CODElength'}=$config[4];
                   4887:         $config{'IDstart'}=$config[5];
                   4888:         $config{'IDlength'}=$config[6];
                   4889:         $config{'Qstart'}=$config[7];
                   4890:         $config{'Qlength'}=$config[8];
                   4891:         $config{'Qoff'}=$config[9];
                   4892:         $config{'Qon'}=$config[10];
                   4893:         $config{'PaperID'}=$config[11];
                   4894:         $config{'PaperIDlength'}=$config[12];
                   4895:         $config{'FirstName'}=$config[13];
                   4896:         $config{'FirstNamelength'}=$config[14];
                   4897:         $config{'LastName'}=$config[15];
                   4898:         $config{'LastNamelength'}=$config[16];
                   4899:         $config{'BubblesPerRow'}=$config[17];
                   4900:         last;
                   4901:     }
                   4902:     return %config;
                   4903: }
                   4904: 
                   4905: sub get_scantronformat_file {
                   4906:     my ($cdom) = @_;
                   4907:     if ($cdom eq '') {
                   4908:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4909:     }
                   4910:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4911:     my $gottab = 0;
                   4912:     my @lines;
                   4913:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4914:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4915:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4916:             if ($formatfile ne '-1') {
                   4917:                 @lines = split("\n",$formatfile,-1);
                   4918:                 $gottab = 1;
                   4919:             }
                   4920:         }
                   4921:     }
                   4922:     if (!$gottab) {
                   4923:         my $confname = $cdom.'-domainconfig';
                   4924:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4925:         my $formatfile = &getfile($default);
                   4926:         if ($formatfile ne '-1') {
                   4927:             @lines = split("\n",$formatfile,-1);
                   4928:             $gottab = 1;
                   4929:         }
                   4930:     }
                   4931:     if (!$gottab) {
                   4932:         my @domains = &current_machine_domains();
                   4933:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4934:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4935:                 @lines = <$fh>;
                   4936:                 close($fh);
1.1403    raeburn  4937:             }
1.1401    raeburn  4938:         } else {
                   4939:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4940:                 @lines = <$fh>;
                   4941:                 close($fh);
                   4942:             }
                   4943:         }
1.1488    raeburn  4944:         chomp(@lines);
1.1401    raeburn  4945:     }
                   4946:     return @lines;
                   4947: }
                   4948: 
1.493     albertel 4949: sub removeuploadedurl {
1.984     neumanie 4950:     my ($url)=@_;	
                   4951:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4952:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4953: }
                   4954: 
                   4955: sub removeuserfile {
                   4956:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4957:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4958:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4959:     if ($result eq 'ok') {	
1.798     raeburn  4960:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4961:             my $metafile = $fname.'.meta';
                   4962:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4963: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4964:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4965:             my $sqlresult = 
1.823     albertel 4966:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4967:                                         'portfolio_metadata',$group,
                   4968:                                         'delete');
1.798     raeburn  4969:         }
                   4970:     }
                   4971:     return $result;
1.257     www      4972: }
1.15      www      4973: 
1.530     albertel 4974: sub mkdiruserfile {
                   4975:     my ($docuname,$docudom,$dir)=@_;
                   4976:     my $home=&homeserver($docuname,$docudom);
                   4977:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4978: }
                   4979: 
1.531     albertel 4980: sub renameuserfile {
                   4981:     my ($docuname,$docudom,$old,$new)=@_;
                   4982:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4983:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4984:                         &escape("$old").':'.&escape("$new"),$home);
                   4985:     if ($result eq 'ok') {
                   4986:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4987:             my $oldmeta = $old.'.meta';
                   4988:             my $newmeta = $new.'.meta';
                   4989:             my $metaresult = 
                   4990:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4991: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4992:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4993:             my $sqlresult = 
1.823     albertel 4994:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4995:                                         'portfolio_metadata',$group,
                   4996:                                         'delete');
1.798     raeburn  4997:         }
                   4998:     }
                   4999:     return $result;
1.531     albertel 5000: }
                   5001: 
1.14      www      5002: # ------------------------------------------------------------------------- Log
                   5003: 
                   5004: sub log {
                   5005:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      5006:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      5007: }
                   5008: 
                   5009: # ------------------------------------------------------------------ Course Log
1.352     www      5010: #
                   5011: # This routine flushes several buffers of non-mission-critical nature
                   5012: #
1.157     www      5013: 
                   5014: sub flushcourselogs {
1.352     www      5015:     &logthis('Flushing log buffers');
                   5016: #
                   5017: # course logs
                   5018: # This is a log of all transactions in a course, which can be used
                   5019: # for data mining purposes
                   5020: #
                   5021: # It also collects the courseid database, which lists last transaction
                   5022: # times and course titles for all courseids
                   5023: #
                   5024:     my %courseidbuffer=();
1.921     raeburn  5025:     foreach my $crsid (keys(%courselogs)) {
1.352     www      5026:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      5027: 		          &escape($courselogs{$crsid}),
                   5028: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      5029: 	    delete $courselogs{$crsid};
                   5030:         } else {
                   5031:             &logthis('Failed to flush log buffer for '.$crsid);
                   5032:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 5033:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      5034:                         " exceeded maximum size, deleting.</font>");
                   5035:                delete $courselogs{$crsid};
                   5036:             }
1.352     www      5037:         }
1.920     raeburn  5038:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  5039:             'description' => $coursedescrbuf{$crsid},
                   5040:             'inst_code'    => $courseinstcodebuf{$crsid},
                   5041:             'type'        => $coursetypebuf{$crsid},
                   5042:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  5043:         };
1.191     harris41 5044:     }
1.352     www      5045: #
                   5046: # Write course id database (reverse lookup) to homeserver of courses 
                   5047: # Is used in pickcourse
                   5048: #
1.840     albertel 5049:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  5050:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  5051:                                     $courseidbuffer{$crs_home},
                   5052:                                     $crs_home,'timeonly');
1.352     www      5053:     }
                   5054: #
                   5055: # File accesses
                   5056: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   5057: #
1.449     matthew  5058:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  5059:         if ($entry =~ /___count$/) {
                   5060:             my ($dom,$name);
1.807     albertel 5061:             ($dom,$name,undef)=
1.811     albertel 5062: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  5063:             if (! defined($dom) || $dom eq '' || 
                   5064:                 ! defined($name) || $name eq '') {
1.620     albertel 5065:                 my $cid = $env{'request.course.id'};
1.1472    raeburn  5066: #
                   5067: # FIXME 11/29/2021
                   5068: # Typo in rev. 1.458 (2003/12/09)??
                   5069: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   5070: #
                   5071: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   5072: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   5073: # in a nohist_accesscount.db file for the user rather than the course.
                   5074: #
                   5075: # That said there is a lot of noise in the data being stored.
                   5076: # So counts for prtspool/  and adm/ etc. are recorded.
                   5077: #
                   5078: # A review of which items ending '___count' are written to %accesshash should likely be 
                   5079: # made before deciding whether to set these to 'course.' instead of 'request.'
                   5080: #
                   5081: # Under the current scheme each user receives a nohist_accesscount.db file listing 
                   5082: # accesses for things which are not published resources, regardless of course, and
                   5083: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   5084: # anyone in the course for things which are not published resources.
                   5085: #
                   5086: # For an author, nohist_accesscount.db ends up having records for other items
                   5087: # mixed up with the legitimate access counts for the author's published resources.
                   5088: #
1.620     albertel 5089:                 $dom  = $env{'request.'.$cid.'.domain'};
                   5090:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  5091:             }
1.450     matthew  5092:             my $value = $accesshash{$entry};
                   5093:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   5094:             my %temphash=($url => $value);
1.449     matthew  5095:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   5096:             if ($result eq 'ok') {
                   5097:                 delete $accesshash{$entry};
                   5098:             }
                   5099:         } else {
1.811     albertel 5100:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      5101:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  5102:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  5103:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   5104:                 delete $accesshash{$entry};
                   5105:             }
1.185     www      5106:         }
1.191     harris41 5107:     }
1.352     www      5108: #
                   5109: # Roles
                   5110: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   5111: #
1.800     albertel 5112:     foreach my $entry (keys(%userrolehash)) {
1.351     www      5113:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      5114: 	    split(/\:/,$entry);
                   5115:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      5116:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      5117:                 $rudom,$runame) eq 'ok') {
                   5118: 	    delete $userrolehash{$entry};
                   5119:         }
                   5120:     }
1.662     raeburn  5121: #
1.1334    raeburn  5122: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5123: #
                   5124:     my %domrolebuffer = ();
1.1000    raeburn  5125:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5126:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5127:         if ($domrolebuffer{$rudom}) {
                   5128:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5129:                       '='.&escape($domainrolehash{$entry});
                   5130:         } else {
                   5131:             $domrolebuffer{$rudom}.=&escape($entry).
                   5132:                       '='.&escape($domainrolehash{$entry});
                   5133:         }
                   5134:         delete $domainrolehash{$entry};
                   5135:     }
                   5136:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  5137: 	my %servers;
                   5138: 	if (defined(&domain($dom,'primary'))) {
                   5139: 	    my $primary=&domain($dom,'primary');
                   5140: 	    my $hostname=&hostname($primary);
                   5141: 	    $servers{$primary} = $hostname;
                   5142: 	} else { 
                   5143: 	    %servers = &get_servers($dom,'library');
                   5144: 	}
1.841     albertel 5145: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  5146: 	    if (&reply('domroleput:'.$dom.':'.
                   5147: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5148: 		last;
                   5149: 	    } else {  
1.841     albertel 5150: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5151: 	    }
1.662     raeburn  5152:         }
                   5153:     }
1.186     www      5154:     $dumpcount++;
1.157     www      5155: }
                   5156: 
                   5157: sub courselog {
                   5158:     my $what=shift;
1.158     www      5159:     $what=time.':'.$what;
1.620     albertel 5160:     unless ($env{'request.course.id'}) { return ''; }
                   5161:     $coursedombuf{$env{'request.course.id'}}=
                   5162:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5163:     $coursenumbuf{$env{'request.course.id'}}=
                   5164:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5165:     $coursehombuf{$env{'request.course.id'}}=
                   5166:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5167:     $coursedescrbuf{$env{'request.course.id'}}=
                   5168:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5169:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5170:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5171:     $courseownerbuf{$env{'request.course.id'}}=
                   5172:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5173:     $coursetypebuf{$env{'request.course.id'}}=
                   5174:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5175:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5176: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5177:     } else {
1.620     albertel 5178: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5179:     }
1.620     albertel 5180:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5181: 	&flushcourselogs();
                   5182:     }
1.158     www      5183: }
                   5184: 
                   5185: sub courseacclog {
                   5186:     my $fnsymb=shift;
1.620     albertel 5187:     unless ($env{'request.course.id'}) { return ''; }
                   5188:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5189:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5190:         $what.=':POST';
1.583     matthew  5191:         # FIXME: Probably ought to escape things....
1.800     albertel 5192: 	foreach my $key (keys(%env)) {
                   5193:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5194:                 my $formitem = $1;
                   5195:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5196:                     $what.=':'.$formitem.'='.$env{$key};
                   5197:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5198:                     if ($formitem eq 'proctorpassword') {
1.1433    raeburn  5199:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5200:                     } else {
                   5201:                         $what.=':'.$formitem.'='.$env{$key};
                   5202:                     }
1.975     raeburn  5203:                 }
1.158     www      5204:             }
1.191     harris41 5205:         }
1.583     matthew  5206:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5207:         # FIXME: We should not be depending on a form parameter that someone
                   5208:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5209:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5210:             $what.= ':POST';
                   5211:             # FIXME: Probably ought to escape things....
                   5212:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5213:                                  'crsdiscuss') {
1.620     albertel 5214:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5215:             }
                   5216:         }
1.158     www      5217:     }
                   5218:     &courselog($what);
1.149     www      5219: }
                   5220: 
1.185     www      5221: sub countacc {
                   5222:     my $url=&declutter(shift);
1.458     matthew  5223:     return if (! defined($url) || $url eq '');
1.620     albertel 5224:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5225: #
                   5226: # Mark that this url was used in this course
                   5227: #
1.620     albertel 5228:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5229: #
                   5230: # Increase the access count for this resource in this child process
                   5231: #
1.281     www      5232:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5233:     $accesshash{$key}++;
1.185     www      5234: }
1.349     www      5235: 
1.361     www      5236: sub linklog {
                   5237:     my ($from,$to)=@_;
                   5238:     $from=&declutter($from);
                   5239:     $to=&declutter($to);
                   5240:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5241:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5242: }
1.1160    www      5243: 
                   5244: sub statslog {
                   5245:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5246:     if ($users<2) { return; }
                   5247:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5248:             'course'       => $env{'request.course.id'},
                   5249:             'sections'     => '"all"',
                   5250:             'num_students' => $users,
                   5251:             'part'         => $part,
                   5252:             'symb'         => $symb,
                   5253:             'mean_tries'   => $av_attempts,
                   5254:             'deg_of_diff'  => $degdiff});
                   5255:     foreach my $key (keys(%dynstore)) {
                   5256:         $accesshash{$key}=$dynstore{$key};
                   5257:     }
                   5258: }
1.361     www      5259:   
1.349     www      5260: sub userrolelog {
                   5261:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5262:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5263:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5264:        $userrolehash
                   5265:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5266:                     =$tend.':'.$tstart;
1.662     raeburn  5267:     }
1.1169    droeschl 5268:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5269:        $userrolehash
                   5270:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5271:                     =$tend.':'.$tstart;
                   5272:     }
1.1334    raeburn  5273:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5274:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5275:        $domainrolehash
                   5276:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5277:                     = $tend.':'.$tstart;
                   5278:     }
1.351     www      5279: }
                   5280: 
1.957     raeburn  5281: sub courserolelog {
                   5282:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  5283:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5284:         my $cdom = $1;
                   5285:         my $cnum = $2;
                   5286:         my $sec = $3;
                   5287:         my $namespace = 'rolelog';
                   5288:         my %storehash = (
                   5289:                            role    => $trole,
                   5290:                            start   => $tstart,
                   5291:                            end     => $tend,
                   5292:                            selfenroll => $selfenroll,
                   5293:                            context    => $context,
                   5294:                         );
                   5295:         if ($trole eq 'gr') {
                   5296:             $namespace = 'groupslog';
                   5297:             $storehash{'group'} = $sec;
                   5298:         } else {
                   5299:             $storehash{'section'} = $sec;
                   5300:         }
1.1188    raeburn  5301:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5302:                    $domain,$cnum,$cdom);
1.1184    raeburn  5303:         if (($trole ne 'st') || ($sec ne '')) {
                   5304:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5305:         }
                   5306:     }
                   5307:     return;
                   5308: }
                   5309: 
1.1184    raeburn  5310: sub domainrolelog {
                   5311:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5312:     if ($area =~ m{^/($match_domain)/$}) {
                   5313:         my $cdom = $1;
                   5314:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5315:         my $namespace = 'rolelog';
                   5316:         my %storehash = (
                   5317:                            role    => $trole,
                   5318:                            start   => $tstart,
                   5319:                            end     => $tend,
                   5320:                            context => $context,
                   5321:                         );
1.1188    raeburn  5322:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5323:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5324:     }
                   5325:     return;
                   5326: 
                   5327: }
                   5328: 
                   5329: sub coauthorrolelog {
                   5330:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5331:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5332:         my $audom = $1;
                   5333:         my $auname = $2;
                   5334:         my $namespace = 'rolelog';
                   5335:         my %storehash = (
                   5336:                            role    => $trole,
                   5337:                            start   => $tstart,
                   5338:                            end     => $tend,
                   5339:                            context => $context,
                   5340:                         );
1.1188    raeburn  5341:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5342:                    $domain,$auname,$audom);
1.1184    raeburn  5343:     }
                   5344:     return;
                   5345: }
                   5346: 
1.351     www      5347: sub get_course_adv_roles {
1.948     raeburn  5348:     my ($cid,$codes) = @_;
1.620     albertel 5349:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5350:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5351:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5352:     my %nothide=();
1.800     albertel 5353:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5354:         if ($user !~ /:/) {
                   5355: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5356:         } else {
                   5357:             $nothide{$user}=1;
                   5358:         }
1.470     www      5359:     }
1.1219    raeburn  5360:     my @possdoms = ($coursehash{'domain'});
                   5361:     if ($coursehash{'checkforpriv'}) {
                   5362:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5363:     }
1.351     www      5364:     my %returnhash=();
                   5365:     my %dumphash=
                   5366:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5367:     my $now=time;
1.997     raeburn  5368:     my %privileged;
1.1000    raeburn  5369:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5370: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5371:         if (($tstart) && ($tstart<0)) { next; }
                   5372:         if (($tend) && ($tend<$now)) { next; }
                   5373:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5374:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5375: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5376:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5377:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5378: 	if ($role eq 'cr') { next; }
1.948     raeburn  5379:         if ($codes) {
                   5380:             if ($section) { $role .= ':'.$section; }
                   5381:             if ($returnhash{$role}) {
                   5382:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5383:             } else {
                   5384:                 $returnhash{$role}=$username.':'.$domain;
                   5385:             }
1.351     www      5386:         } else {
1.988     raeburn  5387:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5388:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5389:             if ($returnhash{$key}) {
                   5390: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5391:             } else {
                   5392:                 $returnhash{$key}=$username.':'.$domain;
                   5393:             }
1.351     www      5394:         }
1.948     raeburn  5395:     }
1.400     www      5396:     return %returnhash;
                   5397: }
                   5398: 
                   5399: sub get_my_roles {
1.937     raeburn  5400:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5401:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5402:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5403:     my (%dumphash,%nothide);
1.1086    raeburn  5404:     if ($context eq 'userroles') {
1.1166    raeburn  5405:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5406:     } else {
1.1219    raeburn  5407:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5408:         if ($hidepriv) {
                   5409:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5410:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5411:                 if ($user !~ /:/) {
                   5412:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5413:                 } else {
                   5414:                     $nothide{$user} = 1;
                   5415:                 }
                   5416:             }
                   5417:         }
1.858     raeburn  5418:     }
1.400     www      5419:     my %returnhash=();
                   5420:     my $now=time;
1.999     raeburn  5421:     my %privileged;
1.800     albertel 5422:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5423:         my ($role,$tend,$tstart);
                   5424:         if ($context eq 'userroles') {
1.1149    raeburn  5425:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5426: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5427:         } else {
                   5428:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5429:         }
1.400     www      5430:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5431:         my $status = 'active';
1.939     raeburn  5432:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5433:             $status = 'previous';
                   5434:         } 
                   5435:         if (($tstart) && ($now<$tstart)) {
                   5436:             $status = 'future';
                   5437:         }
                   5438:         if (ref($types) eq 'ARRAY') {
                   5439:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5440:                 next;
                   5441:             } 
                   5442:         } else {
                   5443:             if ($status ne 'active') {
                   5444:                 next;
                   5445:             }
                   5446:         }
1.867     raeburn  5447:         my ($rolecode,$username,$domain,$section,$area);
                   5448:         if ($context eq 'userroles') {
1.1186    raeburn  5449:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5450:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5451:         } else {
                   5452:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5453:         }
1.832     raeburn  5454:         if (ref($roledoms) eq 'ARRAY') {
                   5455:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5456:                 next;
                   5457:             }
                   5458:         }
                   5459:         if (ref($roles) eq 'ARRAY') {
                   5460:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5461:                 if ($role =~ /^cr\//) {
                   5462:                     if (!grep(/^cr$/,@{$roles})) {
                   5463:                         next;
                   5464:                     }
1.1104    raeburn  5465:                 } elsif ($role =~ /^gr\//) {
                   5466:                     if (!grep(/^gr$/,@{$roles})) {
                   5467:                         next;
                   5468:                     }
1.922     raeburn  5469:                 } else {
                   5470:                     next;
                   5471:                 }
1.832     raeburn  5472:             }
1.867     raeburn  5473:         }
1.937     raeburn  5474:         if ($hidepriv) {
1.1219    raeburn  5475:             my @privroles = ('dc','su');
1.999     raeburn  5476:             if ($context eq 'userroles') {
1.1219    raeburn  5477:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5478:             } else {
1.1219    raeburn  5479:                 my $possdoms = [$domain];
                   5480:                 if (ref($roledoms) eq 'ARRAY') {
                   5481:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5482:                 }
1.1219    raeburn  5483:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5484:                     if (!$nothide{$username.':'.$domain}) {
                   5485:                         next;
                   5486:                     }
                   5487:                 }
1.937     raeburn  5488:             }
                   5489:         }
1.933     raeburn  5490:         if ($withsec) {
                   5491:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5492:                 $tstart.':'.$tend;
                   5493:         } else {
                   5494:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5495:         }
1.832     raeburn  5496:     }
1.373     www      5497:     return %returnhash;
1.399     www      5498: }
                   5499: 
1.1333    raeburn  5500: sub get_all_adhocroles {
                   5501:     my ($dom) = @_;
                   5502:     my @roles_by_num = ();
                   5503:     my %domdefaults = &get_domain_defaults($dom);
                   5504:     my (%description,%access_in_dom,%access_info);
                   5505:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5506:         my $count = 0;
                   5507:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5508:         my %ordered;
                   5509:         foreach my $role (sort(keys(%domcurrent))) {
                   5510:             my ($order,$desc,$access_in_dom);
                   5511:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5512:                 $order = $domcurrent{$role}{'order'};
                   5513:                 $desc = $domcurrent{$role}{'desc'};
                   5514:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5515:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5516:             }
                   5517:             if ($order eq '') {
                   5518:                 $order = $count;
                   5519:             }
                   5520:             $ordered{$order} = $role;
                   5521:             if ($desc ne '') {
                   5522:                 $description{$role} = $desc;
                   5523:             } else {
                   5524:                 $description{$role}= $role;
                   5525:             }
                   5526:             $count++;
                   5527:         }
                   5528:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5529:             push(@roles_by_num,$ordered{$item});
                   5530:         }
                   5531:     }
                   5532:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5533: }
                   5534: 
1.1332    raeburn  5535: sub get_my_adhocroles {
1.1333    raeburn  5536:     my ($cid,$checkreg) = @_;
                   5537:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5538:     if ($env{'request.course.id'} eq $cid) {
                   5539:         $cdom = $env{'course.'.$cid.'.domain'};
                   5540:         $cnum = $env{'course.'.$cid.'.num'};
                   5541:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5542:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5543:         $cdom = $1;
                   5544:         $cnum = $2;
                   5545:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5546:                                      $cdom,$cnum);
                   5547:     }
                   5548:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5549:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5550:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5551:         if ($rosterhash{$user} ne '') {
                   5552:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5553:             return ([],{}) if ($type eq 'auto');
                   5554:         }
                   5555:     }
                   5556:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5557:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5558:             my $then=$env{'user.login.time'};
                   5559:             my $update=$env{'user.update.time'};
1.1335    raeburn  5560:             if (!$update) {
                   5561:                 $update = $then;
                   5562:             }
                   5563:             my @liveroles;
1.1334    raeburn  5564:             foreach my $role ('dh','da') {
                   5565:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5566:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5567:                     my $limit = $update;
                   5568:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5569:                         $limit = $then;
                   5570:                     }
1.1335    raeburn  5571:                     my $activerole = 1;
                   5572:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5573:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5574:                     if ($activerole) {
                   5575:                         push(@liveroles,$role);
                   5576:                     }
1.1334    raeburn  5577:                 }
1.1332    raeburn  5578:             }
1.1335    raeburn  5579:             if (@liveroles) {
1.1332    raeburn  5580:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5581:                     my ($accessref,$accessinfo,%access_in_dom);
                   5582:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5583:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5584:                         if (@{$roles_by_num}) {
1.1332    raeburn  5585:                             my %settings;
                   5586:                             if ($env{'request.course.id'} eq $cid) {
                   5587:                                 foreach my $envkey (keys(%env)) {
                   5588:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5589:                                         $settings{$1} = $env{$envkey};
                   5590:                                     }
                   5591:                                 }
                   5592:                             } else {
                   5593:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5594:                             }
                   5595:                             my %setincrs;
                   5596:                             if ($settings{'internal.adhocaccess'}) {
                   5597:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5598:                             }
                   5599:                             my @statuses;
                   5600:                             if ($env{'environment.inststatus'}) {
                   5601:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5602:                             }
                   5603:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5604:                             if (ref($accessref) eq 'HASH') {
                   5605:                                 %access_in_dom = %{$accessref};
                   5606:                             }
                   5607:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5608:                                 my ($curraccess,@okstatus,@personnel);
                   5609:                                 if ($setincrs{$role}) {
                   5610:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5611:                                     if ($curraccess eq 'status') {
                   5612:                                         @okstatus = split(/\&/,$rest);
                   5613:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5614:                                         @personnel = split(/\&/,$rest);
                   5615:                                     }
                   5616:                                 } else {
                   5617:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5618:                                     if (ref($accessinfo) eq 'HASH') {
                   5619:                                         if ($curraccess eq 'status') {
                   5620:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5621:                                                 @okstatus = @{$accessinfo->{$role}};
                   5622:                                             }
                   5623:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5624:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5625:                                                 @personnel = @{$accessinfo->{$role}};
                   5626:                                             }
1.1332    raeburn  5627:                                         }
                   5628:                                     }
                   5629:                                 }
                   5630:                                 if ($curraccess eq 'none') {
                   5631:                                     next;
                   5632:                                 } elsif ($curraccess eq 'all') {
                   5633:                                     push(@possroles,$role);
1.1336    raeburn  5634:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5635:                                     if (grep(/^dh$/,@liveroles)) {
                   5636:                                         push(@possroles,$role);
                   5637:                                     } else {
                   5638:                                         next;
                   5639:                                     }
1.1336    raeburn  5640:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5641:                                     if (grep(/^da$/,@liveroles)) {
                   5642:                                         push(@possroles,$role);
                   5643:                                     } else {
                   5644:                                         next;
                   5645:                                     }
1.1332    raeburn  5646:                                 } elsif ($curraccess eq 'status') {
                   5647:                                     if (@okstatus) {
                   5648:                                         if (!@statuses) {
                   5649:                                             if (grep(/^default$/,@okstatus)) {
                   5650:                                                 push(@possroles,$role);
                   5651:                                             }
                   5652:                                         } else {
                   5653:                                             foreach my $status (@okstatus) {
                   5654:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5655:                                                     push(@possroles,$role);
                   5656:                                                     last;
                   5657:                                                 }
                   5658:                                             }
                   5659:                                         }
                   5660:                                     }
                   5661:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5662:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5663:                                         if ($curraccess eq 'exc') {
                   5664:                                             push(@possroles,$role);
                   5665:                                         }
                   5666:                                     } elsif ($curraccess eq 'inc') {
                   5667:                                         push(@possroles,$role);
                   5668:                                     }
                   5669:                                 }
                   5670:                             }
                   5671:                         }
                   5672:                     }
                   5673:                 }
                   5674:             }
                   5675:         }
                   5676:     }
1.1333    raeburn  5677:     unless (ref($description) eq 'HASH') {
                   5678:         if (ref($roles_by_num) eq 'ARRAY') {
                   5679:             my %desc;
                   5680:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5681:             $description = \%desc;
                   5682:         } else {
                   5683:             $description = {};
                   5684:         }
                   5685:     }
                   5686:     return (\@possroles,$description);
1.1332    raeburn  5687: }
                   5688: 
1.399     www      5689: # ----------------------------------------------------- Frontpage Announcements
                   5690: #
                   5691: #
                   5692: 
                   5693: sub postannounce {
                   5694:     my ($server,$text)=@_;
1.844     albertel 5695:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5696:     unless ($text=~/\w/) { $text=''; }
                   5697:     return &reply('setannounce:'.&escape($text),$server);
                   5698: }
                   5699: 
                   5700: sub getannounce {
1.448     albertel 5701: 
1.1359    raeburn  5702:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5703: 	my $announcement='';
1.800     albertel 5704: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5705: 	close($fh);
1.399     www      5706: 	if ($announcement=~/\w/) { 
                   5707: 	    return 
                   5708:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5709:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5710: 	} else {
                   5711: 	    return '';
                   5712: 	}
                   5713:     } else {
                   5714: 	return '';
                   5715:     }
1.351     www      5716: }
1.353     www      5717: 
                   5718: # ---------------------------------------------------------- Course ID routines
                   5719: # Deal with domain's nohist_courseid.db files
                   5720: #
                   5721: 
                   5722: sub courseidput {
1.921     raeburn  5723:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5724:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5725:     my $outcome;
                   5726:     if ($caller eq 'timeonly') {
                   5727:         my $cids = '';
                   5728:         foreach my $item (keys(%$storehash)) {
                   5729:             $cids.=&escape($item).'&';
                   5730:         }
                   5731:         $cids=~s/\&$//;
                   5732:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5733:                           $coursehome);       
                   5734:     } else {
                   5735:         my $items = '';
                   5736:         foreach my $item (keys(%$storehash)) {
                   5737:             $items.= &escape($item).'='.
                   5738:                      &freeze_escape($$storehash{$item}).'&';
                   5739:         }
                   5740:         $items=~s/\&$//;
                   5741:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5742:                           $coursehome);
1.918     raeburn  5743:     }
                   5744:     if ($outcome eq 'unknown_cmd') {
                   5745:         my $what;
                   5746:         foreach my $cid (keys(%$storehash)) {
                   5747:             $what .= &escape($cid).'=';
1.921     raeburn  5748:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5749:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5750:             }
                   5751:             $what =~ s/\:$/&/;
                   5752:         }
                   5753:         $what =~ s/\&$//;  
                   5754:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5755:     } else {
                   5756:         return $outcome;
                   5757:     }
1.353     www      5758: }
                   5759: 
                   5760: sub courseiddump {
1.921     raeburn  5761:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5762:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5763:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5764:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5765:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5766:     my $as_hash = 1;
                   5767:     my %returnhash;
                   5768:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5769:     my %libserv = &all_library();
                   5770:     foreach my $tryserver (keys(%libserv)) {
                   5771:         if ( (  $hostidflag == 1 
                   5772: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5773: 	     || (!defined($hostidflag)) ) {
                   5774: 
1.918     raeburn  5775: 	    if (($domfilter eq '') ||
                   5776: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5777:                 my $rep;
                   5778:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5779:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5780:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5781:                                 &escape($descfilter), &escape($instcodefilter), 
                   5782:                                 &escape($ownerfilter), &escape($coursefilter),
                   5783:                                 &escape($typefilter), &escape($regexp_ok), 
                   5784:                                 $as_hash, &escape($selfenrollonly), 
                   5785:                                 &escape($catfilter), $showhidden, $caller, 
                   5786:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5787:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5788:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5789:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5790:                 } else {
                   5791:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5792:                              $sincefilter.':'.&escape($descfilter).':'.
                   5793:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5794:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5795:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5796:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5797:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5798:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5799:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5800:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5801:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5802:                 }
                   5803:                      
1.918     raeburn  5804:                 my @pairs=split(/\&/,$rep);
                   5805:                 foreach my $item (@pairs) {
                   5806:                     my ($key,$value)=split(/\=/,$item,2);
                   5807:                     $key = &unescape($key);
                   5808:                     next if ($key =~ /^error: 2 /);
                   5809:                     my $result = &thaw_unescape($value);
                   5810:                     if (ref($result) eq 'HASH') {
                   5811:                         $returnhash{$key}=$result;
                   5812:                     } else {
1.921     raeburn  5813:                         my @responses = split(/:/,$value);
                   5814:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5815:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5816:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5817:                         }
1.1008    raeburn  5818:                     }
1.353     www      5819:                 }
                   5820:             }
                   5821:         }
                   5822:     }
                   5823:     return %returnhash;
                   5824: }
                   5825: 
1.1055    raeburn  5826: sub courselastaccess {
                   5827:     my ($cdom,$cnum,$hostidref) = @_;
                   5828:     my %returnhash;
                   5829:     if ($cdom && $cnum) {
                   5830:         my $chome = &homeserver($cnum,$cdom);
                   5831:         if ($chome ne 'no_host') {
                   5832:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5833:             &extract_lastaccess(\%returnhash,$rep);
                   5834:         }
                   5835:     } else {
                   5836:         if (!$cdom) { $cdom=''; }
                   5837:         my %libserv = &all_library();
                   5838:         foreach my $tryserver (keys(%libserv)) {
                   5839:             if (ref($hostidref) eq 'ARRAY') {
                   5840:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5841:             } 
                   5842:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5843:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5844:                 &extract_lastaccess(\%returnhash,$rep);
                   5845:             }
                   5846:         }
                   5847:     }
                   5848:     return %returnhash;
                   5849: }
                   5850: 
                   5851: sub extract_lastaccess {
                   5852:     my ($returnhash,$rep) = @_;
                   5853:     if (ref($returnhash) eq 'HASH') {
                   5854:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5855:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5856:                  $rep eq '') {
                   5857:             my @pairs=split(/\&/,$rep);
                   5858:             foreach my $item (@pairs) {
                   5859:                 my ($key,$value)=split(/\=/,$item,2);
                   5860:                 $key = &unescape($key);
                   5861:                 next if ($key =~ /^error: 2 /);
                   5862:                 $returnhash->{$key} = &thaw_unescape($value);
                   5863:             }
                   5864:         }
                   5865:     }
                   5866:     return;
                   5867: }
                   5868: 
1.658     raeburn  5869: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5870: 
                   5871: sub dcmailput {
1.685     raeburn  5872:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5873:     my $status = &Apache::lonnet::critical(
1.740     www      5874:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5875:        &escape($message),$server);
1.662     raeburn  5876:     return $status;
                   5877: }
                   5878: 
1.658     raeburn  5879: sub dcmaildump {
                   5880:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5881:     my %returnhash=();
1.846     albertel 5882: 
                   5883:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5884:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5885:                                                          &escape($enddate).':';
                   5886: 	my @esc_senders=map { &escape($_)} @$senders;
                   5887: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5888: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5889:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5890:             if (($key) && ($value)) {
                   5891:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5892:             }
                   5893:         }
                   5894:     }
                   5895:     return %returnhash;
                   5896: }
1.662     raeburn  5897: # ---------------------------------------------------------- Domain roles
                   5898: 
                   5899: sub get_domain_roles {
                   5900:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5901:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5902:         $startdate = '.';
                   5903:     }
1.1018    raeburn  5904:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5905:         $enddate = '.';
                   5906:     }
1.922     raeburn  5907:     my $rolelist;
                   5908:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5909:         $rolelist = join('&',@{$roles});
1.922     raeburn  5910:     }
1.662     raeburn  5911:     my %personnel = ();
1.841     albertel 5912: 
                   5913:     my %servers = &get_servers($dom,'library');
                   5914:     foreach my $tryserver (keys(%servers)) {
                   5915: 	%{$personnel{$tryserver}}=();
                   5916: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5917: 					    &escape($startdate).':'.
                   5918: 					    &escape($enddate).':'.
                   5919: 					    &escape($rolelist), $tryserver))) {
                   5920: 	    my ($key,$value) = split(/\=/,$line,2);
                   5921: 	    if (($key) && ($value)) {
                   5922: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5923: 	    }
                   5924: 	}
1.662     raeburn  5925:     }
                   5926:     return %personnel;
                   5927: }
1.658     raeburn  5928: 
1.1332    raeburn  5929: sub get_active_domroles {
                   5930:     my ($dom,$roles) = @_;
                   5931:     return () unless (ref($roles) eq 'ARRAY');
                   5932:     my $now = time;
                   5933:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5934:     my %domroles;
                   5935:     foreach my $server (keys(%dompersonnel)) {
                   5936:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5937:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5938:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5939:         }
                   5940:     }
                   5941:     return %domroles;
                   5942: }
                   5943: 
1.1057    www      5944: # ----------------------------------------------------------- Interval timing 
1.149     www      5945: 
1.1153    www      5946: {
                   5947: # Caches needed for speedup of navmaps
                   5948: # We don't want to cache this for very long at all (5 seconds at most)
                   5949: # 
                   5950: # The user for whom we cache
                   5951: my $cachedkey='';
                   5952: # The cached times for this user
                   5953: my %cachedtimes=();
                   5954: # When this was last done
1.1282    raeburn  5955: my $cachedtime='';
1.1153    www      5956: 
                   5957: sub load_all_first_access {
1.1308    raeburn  5958:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5959:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5960:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5961:         (!$ignorecache)) {
1.1154    raeburn  5962:         return;
                   5963:     }
                   5964:     $cachedtime=time;
                   5965:     $cachedkey=$uname.':'.$udom;
                   5966:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5967: }
                   5968: 
1.504     albertel 5969: sub get_first_access {
1.1308    raeburn  5970:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5971:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5972:     if ($argsymb) { $symb=$argsymb; }
                   5973:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5974:     if ($argmap) { $map = $argmap; }
1.926     albertel 5975:     if ($type eq 'course') {
                   5976: 	$res='course';
                   5977:     } elsif ($type eq 'map') {
1.588     albertel 5978: 	$res=&symbread($map);
                   5979:     } else {
                   5980: 	$res=$symb;
                   5981:     }
1.1308    raeburn  5982:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5983:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5984: }
                   5985: 
                   5986: sub set_first_access {
1.1162    raeburn  5987:     my ($type,$interval)=@_;
1.790     albertel 5988:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5989:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5990:     if ($type eq 'course') {
                   5991: 	$res='course';
                   5992:     } elsif ($type eq 'map') {
1.588     albertel 5993: 	$res=&symbread($map);
                   5994:     } else {
                   5995: 	$res=$symb;
                   5996:     }
1.1153    www      5997:     $cachedkey='';
1.1162    raeburn  5998:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5999:     if ($firstaccess) {
                   6000:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  6001:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   6002:                  "in $courseid");
1.1386    raeburn  6003:         return 'already_set';
                   6004:     } else {
1.1162    raeburn  6005:         my $start = time;
                   6006: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   6007:                           $udom,$uname);
                   6008:         if ($putres eq 'ok') {
                   6009:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   6010:                  $udom,$uname); 
                   6011:             &appenv(
                   6012:                      {
                   6013:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   6014:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   6015:                      }
                   6016:                   );
1.1365    raeburn  6017:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   6018:                 $cachedtimes{"$courseid\0$res"} = $start;
                   6019:             }
1.1386    raeburn  6020:         } elsif ($putres ne 'refused') {
                   6021:             &logthis("Result: $putres when attempting to set first access time ".
                   6022:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  6023:         }
                   6024:         return $putres;
1.505     albertel 6025:     }
                   6026:     return 'already_set';
1.504     albertel 6027: }
1.1153    www      6028: }
1.1282    raeburn  6029: 
1.110     www      6030: # --------------------------------------------- Set Expire Date for Spreadsheet
                   6031: 
                   6032: sub expirespread {
                   6033:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 6034:     my $cid=$env{'request.course.id'}; 
1.110     www      6035:     if ($cid) {
                   6036:        my $now=time;
                   6037:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6038:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6039:                             $env{'course.'.$cid.'.num'}.
1.110     www      6040: 	        	    ':nohist_expirationdates:'.
                   6041:                             &escape($key).'='.$now,
1.620     albertel 6042:                             $env{'course.'.$cid.'.home'})
1.110     www      6043:     }
                   6044:     return 'ok';
1.14      www      6045: }
                   6046: 
1.109     www      6047: # ----------------------------------------------------- Devalidate Spreadsheets
                   6048: 
                   6049: sub devalidate {
1.325     www      6050:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6051:     my $cid=$env{'request.course.id'}; 
1.109     www      6052:     if ($cid) {
1.391     matthew  6053:         # delete the stored spreadsheets for
                   6054:         # - the student level sheet of this user in course's homespace
                   6055:         # - the assessment level sheet for this resource 
                   6056:         #   for this user in user's homespace
1.553     albertel 6057: 	# - current conditional state info
1.325     www      6058: 	my $key=$uname.':'.$udom.':';
1.109     www      6059:         my $status=
1.299     matthew  6060: 	    &del('nohist_calculatedsheets',
1.391     matthew  6061: 		 [$key.'studentcalc:'],
1.620     albertel 6062: 		 $env{'course.'.$cid.'.domain'},
                   6063: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6064: 		.' '.
                   6065: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6066: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6067:         unless ($status eq 'ok ok') {
                   6068:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6069:                     $uname.' at '.$udom.' for '.
1.109     www      6070: 		    $symb.': '.$status);
1.133     albertel 6071:         }
1.553     albertel 6072: 	&delenv('user.state.'.$cid);
1.109     www      6073:     }
                   6074: }
                   6075: 
1.265     albertel 6076: sub get_scalar {
                   6077:     my ($string,$end) = @_;
                   6078:     my $value;
                   6079:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6080: 	$value = $1;
                   6081:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6082: 	$value = $1;
                   6083:     }
                   6084:     return &unescape($value);
                   6085: }
                   6086: 
                   6087: sub array2str {
                   6088:   my (@array) = @_;
                   6089:   my $result=&arrayref2str(\@array);
                   6090:   $result=~s/^__ARRAY_REF__//;
                   6091:   $result=~s/__END_ARRAY_REF__$//;
                   6092:   return $result;
                   6093: }
                   6094: 
1.204     albertel 6095: sub arrayref2str {
                   6096:   my ($arrayref) = @_;
1.265     albertel 6097:   my $result='__ARRAY_REF__';
1.204     albertel 6098:   foreach my $elem (@$arrayref) {
1.265     albertel 6099:     if(ref($elem) eq 'ARRAY') {
                   6100:       $result.=&arrayref2str($elem).'&';
                   6101:     } elsif(ref($elem) eq 'HASH') {
                   6102:       $result.=&hashref2str($elem).'&';
                   6103:     } elsif(ref($elem)) {
                   6104:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6105:     } else {
                   6106:       $result.=&escape($elem).'&';
                   6107:     }
                   6108:   }
                   6109:   $result=~s/\&$//;
1.265     albertel 6110:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6111:   return $result;
                   6112: }
                   6113: 
1.168     albertel 6114: sub hash2str {
1.204     albertel 6115:   my (%hash) = @_;
                   6116:   my $result=&hashref2str(\%hash);
1.265     albertel 6117:   $result=~s/^__HASH_REF__//;
                   6118:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6119:   return $result;
                   6120: }
                   6121: 
                   6122: sub hashref2str {
                   6123:   my ($hashref)=@_;
1.265     albertel 6124:   my $result='__HASH_REF__';
1.800     albertel 6125:   foreach my $key (sort(keys(%$hashref))) {
                   6126:     if (ref($key) eq 'ARRAY') {
                   6127:       $result.=&arrayref2str($key).'=';
                   6128:     } elsif (ref($key) eq 'HASH') {
                   6129:       $result.=&hashref2str($key).'=';
                   6130:     } elsif (ref($key)) {
1.265     albertel 6131:       $result.='=';
1.800     albertel 6132:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6133:     } else {
1.1132    raeburn  6134: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6135:     }
                   6136: 
1.800     albertel 6137:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6138:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6139:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6140:       $result.=&hashref2str($hashref->{$key}).'&';
                   6141:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6142:        $result.='&';
1.800     albertel 6143:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6144:     } else {
1.800     albertel 6145:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6146:     }
                   6147:   }
1.168     albertel 6148:   $result=~s/\&$//;
1.265     albertel 6149:   $result .= '__END_HASH_REF__';
1.168     albertel 6150:   return $result;
                   6151: }
                   6152: 
                   6153: sub str2hash {
1.265     albertel 6154:     my ($string)=@_;
                   6155:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6156:     return %$hash;
                   6157: }
                   6158: 
                   6159: sub str2hashref {
1.168     albertel 6160:   my ($string) = @_;
1.265     albertel 6161: 
                   6162:   my %hash;
                   6163: 
                   6164:   if($string !~ /^__HASH_REF__/) {
                   6165:       if (! ($string eq '' || !defined($string))) {
                   6166: 	  $hash{'error'}='Not hash reference';
                   6167:       }
                   6168:       return (\%hash, $string);
                   6169:   }
                   6170: 
                   6171:   $string =~ s/^__HASH_REF__//;
                   6172: 
                   6173:   while($string !~ /^__END_HASH_REF__/) {
                   6174:       #key
                   6175:       my $key='';
                   6176:       if($string =~ /^__HASH_REF__/) {
                   6177:           ($key, $string)=&str2hashref($string);
                   6178:           if(defined($key->{'error'})) {
                   6179:               $hash{'error'}='Bad data';
                   6180:               return (\%hash, $string);
                   6181:           }
                   6182:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6183:           ($key, $string)=&str2arrayref($string);
                   6184:           if($key->[0] eq 'Array reference error') {
                   6185:               $hash{'error'}='Bad data';
                   6186:               return (\%hash, $string);
                   6187:           }
                   6188:       } else {
                   6189:           $string =~ s/^(.*?)=//;
1.267     albertel 6190: 	  $key=&unescape($1);
1.265     albertel 6191:       }
                   6192:       $string =~ s/^=//;
                   6193: 
                   6194:       #value
                   6195:       my $value='';
                   6196:       if($string =~ /^__HASH_REF__/) {
                   6197:           ($value, $string)=&str2hashref($string);
                   6198:           if(defined($value->{'error'})) {
                   6199:               $hash{'error'}='Bad data';
                   6200:               return (\%hash, $string);
                   6201:           }
                   6202:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6203:           ($value, $string)=&str2arrayref($string);
                   6204:           if($value->[0] eq 'Array reference error') {
                   6205:               $hash{'error'}='Bad data';
                   6206:               return (\%hash, $string);
                   6207:           }
                   6208:       } else {
                   6209: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6210:       }
                   6211:       $string =~ s/^&//;
                   6212: 
                   6213:       $hash{$key}=$value;
1.204     albertel 6214:   }
1.265     albertel 6215: 
                   6216:   $string =~ s/^__END_HASH_REF__//;
                   6217: 
                   6218:   return (\%hash, $string);
1.204     albertel 6219: }
                   6220: 
                   6221: sub str2array {
1.265     albertel 6222:     my ($string)=@_;
                   6223:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6224:     return @$array;
                   6225: }
                   6226: 
                   6227: sub str2arrayref {
1.204     albertel 6228:   my ($string) = @_;
1.265     albertel 6229:   my @array;
                   6230: 
                   6231:   if($string !~ /^__ARRAY_REF__/) {
                   6232:       if (! ($string eq '' || !defined($string))) {
                   6233: 	  $array[0]='Array reference error';
                   6234:       }
                   6235:       return (\@array, $string);
                   6236:   }
                   6237: 
                   6238:   $string =~ s/^__ARRAY_REF__//;
                   6239: 
                   6240:   while($string !~ /^__END_ARRAY_REF__/) {
                   6241:       my $value='';
                   6242:       if($string =~ /^__HASH_REF__/) {
                   6243:           ($value, $string)=&str2hashref($string);
                   6244:           if(defined($value->{'error'})) {
                   6245:               $array[0] ='Array reference error';
                   6246:               return (\@array, $string);
                   6247:           }
                   6248:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6249:           ($value, $string)=&str2arrayref($string);
                   6250:           if($value->[0] eq 'Array reference error') {
                   6251:               $array[0] ='Array reference error';
                   6252:               return (\@array, $string);
                   6253:           }
                   6254:       } else {
                   6255: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6256:       }
                   6257:       $string =~ s/^&//;
                   6258: 
                   6259:       push(@array, $value);
1.191     harris41 6260:   }
1.265     albertel 6261: 
                   6262:   $string =~ s/^__END_ARRAY_REF__//;
                   6263: 
                   6264:   return (\@array, $string);
1.168     albertel 6265: }
                   6266: 
1.167     albertel 6267: # -------------------------------------------------------------------Temp Store
                   6268: 
1.168     albertel 6269: sub tmpreset {
                   6270:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6271:   if (!$symb) {
                   6272:     $symb=&symbread();
1.620     albertel 6273:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6274:   }
                   6275:   $symb=escape($symb);
                   6276: 
1.620     albertel 6277:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6278:   $namespace=~s/\//\_/g;
                   6279:   $namespace=~s/\W//g;
                   6280: 
1.620     albertel 6281:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6282:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6283:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6284:       $stuname=&get_requestor_ip();
1.591     albertel 6285:   }
1.1117    foxr     6286:   my $path=LONCAPA::tempdir();
1.168     albertel 6287:   my %hash;
                   6288:   if (tie(%hash,'GDBM_File',
                   6289: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6290: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6291:     foreach my $key (keys(%hash)) {
1.180     albertel 6292:       if ($key=~ /:$symb/) {
1.168     albertel 6293: 	delete($hash{$key});
                   6294:       }
                   6295:     }
                   6296:   }
                   6297: }
                   6298: 
1.167     albertel 6299: sub tmpstore {
1.168     albertel 6300:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6301: 
                   6302:   if (!$symb) {
                   6303:     $symb=&symbread();
1.620     albertel 6304:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6305:   }
                   6306:   $symb=escape($symb);
                   6307: 
                   6308:   if (!$namespace) {
                   6309:     # I don't think we would ever want to store this for a course.
                   6310:     # it seems this will only be used if we don't have a course.
1.620     albertel 6311:     #$namespace=$env{'request.course.id'};
1.168     albertel 6312:     #if (!$namespace) {
1.620     albertel 6313:       $namespace=$env{'request.state'};
1.168     albertel 6314:     #}
                   6315:   }
                   6316:   $namespace=~s/\//\_/g;
                   6317:   $namespace=~s/\W//g;
1.620     albertel 6318:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6319:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6320:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6321:       $stuname=&get_requestor_ip();
1.591     albertel 6322:   }
1.168     albertel 6323:   my $now=time;
                   6324:   my %hash;
1.1117    foxr     6325:   my $path=LONCAPA::tempdir();
1.168     albertel 6326:   if (tie(%hash,'GDBM_File',
                   6327: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6328: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6329:     $hash{"version:$symb"}++;
                   6330:     my $version=$hash{"version:$symb"};
                   6331:     my $allkeys=''; 
                   6332:     foreach my $key (keys(%$storehash)) {
                   6333:       $allkeys.=$key.':';
1.591     albertel 6334:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6335:     }
                   6336:     $hash{"$version:$symb:timestamp"}=$now;
                   6337:     $allkeys.='timestamp';
                   6338:     $hash{"$version:keys:$symb"}=$allkeys;
                   6339:     if (untie(%hash)) {
                   6340:       return 'ok';
                   6341:     } else {
                   6342:       return "error:$!";
                   6343:     }
                   6344:   } else {
                   6345:     return "error:$!";
                   6346:   }
                   6347: }
1.167     albertel 6348: 
1.168     albertel 6349: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6350: 
1.168     albertel 6351: sub tmprestore {
                   6352:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6353: 
1.168     albertel 6354:   if (!$symb) {
                   6355:     $symb=&symbread();
1.620     albertel 6356:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6357:   }
                   6358:   $symb=escape($symb);
                   6359: 
1.620     albertel 6360:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6361: 
1.620     albertel 6362:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6363:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6364:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6365:       $stuname=&get_requestor_ip();
1.591     albertel 6366:   }
1.168     albertel 6367:   my %returnhash;
                   6368:   $namespace=~s/\//\_/g;
                   6369:   $namespace=~s/\W//g;
                   6370:   my %hash;
1.1117    foxr     6371:   my $path=LONCAPA::tempdir();
1.168     albertel 6372:   if (tie(%hash,'GDBM_File',
                   6373: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6374: 	  &GDBM_READER(),0640)) {
1.168     albertel 6375:     my $version=$hash{"version:$symb"};
                   6376:     $returnhash{'version'}=$version;
                   6377:     my $scope;
                   6378:     for ($scope=1;$scope<=$version;$scope++) {
                   6379:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6380:       my @keys=split(/:/,$vkeys);
                   6381:       my $key;
                   6382:       $returnhash{"$scope:keys"}=$vkeys;
                   6383:       foreach $key (@keys) {
1.591     albertel 6384: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6385: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6386:       }
                   6387:     }
1.168     albertel 6388:     if (!(untie(%hash))) {
                   6389:       return "error:$!";
                   6390:     }
                   6391:   } else {
                   6392:     return "error:$!";
                   6393:   }
                   6394:   return %returnhash;
1.167     albertel 6395: }
                   6396: 
1.9       www      6397: # ----------------------------------------------------------------------- Store
                   6398: 
                   6399: sub store {
1.1269    raeburn  6400:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6401:     my $home='';
                   6402: 
1.168     albertel 6403:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6404: 
1.213     www      6405:     $symb=&symbclean($symb);
1.122     albertel 6406:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6407: 
1.620     albertel 6408:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6409:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6410: 
                   6411:     &devalidate($symb,$stuname,$domain);
1.109     www      6412: 
                   6413:     $symb=escape($symb);
1.187     www      6414:     if (!$namespace) { 
1.620     albertel 6415:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6416:           return ''; 
                   6417:        } 
                   6418:     }
1.620     albertel 6419:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6420: 
1.1434    raeburn  6421:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6422:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6423: 
1.12      www      6424:     my $namevalue='';
1.800     albertel 6425:     foreach my $key (keys(%$storehash)) {
                   6426:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6427:     }
1.12      www      6428:     $namevalue=~s/\&$//;
1.187     www      6429:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6430:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6431: }
                   6432: 
1.47      www      6433: # -------------------------------------------------------------- Critical Store
                   6434: 
                   6435: sub cstore {
1.1269    raeburn  6436:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6437:     my $home='';
                   6438: 
1.168     albertel 6439:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6440: 
1.213     www      6441:     $symb=&symbclean($symb);
1.122     albertel 6442:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6443: 
1.620     albertel 6444:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6445:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6446: 
                   6447:     &devalidate($symb,$stuname,$domain);
1.109     www      6448: 
                   6449:     $symb=escape($symb);
1.187     www      6450:     if (!$namespace) { 
1.620     albertel 6451:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6452:           return ''; 
                   6453:        } 
                   6454:     }
1.620     albertel 6455:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6456: 
1.1434    raeburn  6457:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6458:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6459: 
1.47      www      6460:     my $namevalue='';
1.800     albertel 6461:     foreach my $key (keys(%$storehash)) {
                   6462:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6463:     }
1.47      www      6464:     $namevalue=~s/\&$//;
1.187     www      6465:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6466:     return critical
1.1269    raeburn  6467:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6468: }
                   6469: 
1.9       www      6470: # --------------------------------------------------------------------- Restore
                   6471: 
                   6472: sub restore {
1.124     www      6473:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6474:     my $home='';
                   6475: 
1.168     albertel 6476:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6477: 
1.122     albertel 6478:     if (!$symb) {
1.1224    raeburn  6479:         return if ($namespace eq 'courserequests');
                   6480:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6481:     } else {
1.1224    raeburn  6482:         unless ($namespace eq 'courserequests') {
                   6483:             $symb=&escape(&symbclean($symb));
                   6484:         }
1.122     albertel 6485:     }
1.188     www      6486:     if (!$namespace) { 
1.620     albertel 6487:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6488:           return ''; 
                   6489:        } 
                   6490:     }
1.620     albertel 6491:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6492:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6493:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6494:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6495: 
1.12      www      6496:     my %returnhash=();
1.800     albertel 6497:     foreach my $line (split(/\&/,$answer)) {
                   6498: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6499:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6500:     }
1.75      www      6501:     my $version;
                   6502:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6503:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6504:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6505:        }
1.75      www      6506:     }
1.13      www      6507:     return %returnhash;
1.34      www      6508: }
                   6509: 
                   6510: # ---------------------------------------------------------- Course Description
1.1118    foxr     6511: #
                   6512: #  
1.34      www      6513: 
                   6514: sub coursedescription {
1.731     albertel 6515:     my ($courseid,$args)=@_;
1.34      www      6516:     $courseid=~s/^\///;
1.49      www      6517:     $courseid=~s/\_/\//g;
1.34      www      6518:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6519:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6520:     my $normalid=$cdomain.'_'.$cnum;
                   6521:     # need to always cache even if we get errors otherwise we keep 
                   6522:     # trying and trying and trying to get the course description.
                   6523:     my %envhash=();
                   6524:     my %returnhash=();
1.731     albertel 6525:     
                   6526:     my $expiretime=600;
                   6527:     if ($env{'request.course.id'} eq $normalid) {
                   6528: 	$expiretime=120;
                   6529:     }
                   6530: 
                   6531:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6532:     if (!$args->{'freshen_cache'}
                   6533: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6534: 	foreach my $key (keys(%env)) {
                   6535: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6536: 	    my ($setting) = $1;
                   6537: 	    $returnhash{$setting} = $env{$key};
                   6538: 	}
                   6539: 	return %returnhash;
                   6540:     }
                   6541: 
1.1118    foxr     6542:     # get the data again
                   6543: 
1.731     albertel 6544:     if (!$args->{'one_time'}) {
                   6545: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6546:     }
1.811     albertel 6547: 
1.34      www      6548:     if ($chome ne 'no_host') {
1.302     albertel 6549:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6550:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6551: 	   my $username = $env{'user.name'}; # Defult username
                   6552: 	   if(defined $args->{'user'}) {
                   6553: 	       $username = $args->{'user'};
                   6554: 	   }
1.129     albertel 6555:            $returnhash{'home'}= $chome;
                   6556: 	   $returnhash{'domain'} = $cdomain;
                   6557: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6558:            if (!defined($returnhash{'type'})) {
                   6559:                $returnhash{'type'} = 'Course';
                   6560:            }
1.130     albertel 6561:            while (my ($name,$value) = each %returnhash) {
1.53      www      6562:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6563:            }
1.270     www      6564:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6565:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6566: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6567:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6568:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6569:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6570:        }
                   6571:     }
1.731     albertel 6572:     if (!$args->{'one_time'}) {
1.949     raeburn  6573: 	&appenv(\%envhash);
1.731     albertel 6574:     }
1.302     albertel 6575:     return %returnhash;
1.461     www      6576: }
                   6577: 
1.1080    raeburn  6578: sub update_released_required {
                   6579:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6580:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6581:         $cid = $env{'request.course.id'};
                   6582:         $cdom = $env{'course.'.$cid.'.domain'};
                   6583:         $cnum = $env{'course.'.$cid.'.num'};
                   6584:         $chome = $env{'course.'.$cid.'.home'};
                   6585:     }
                   6586:     if ($needsrelease) {
                   6587:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6588:         my $needsupdate;
                   6589:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6590:             $needsupdate = 1;
                   6591:         } else {
                   6592:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6593:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6594:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6595:                 $needsupdate = 1;
                   6596:             }
                   6597:         }
                   6598:         if ($needsupdate) {
                   6599:             my %needshash = (
                   6600:                              'internal.releaserequired' => $needsrelease,
                   6601:                             );
                   6602:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6603:             if ($putresult eq 'ok') {
                   6604:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6605:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6606:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6607:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6608:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6609:                 }
                   6610:             }
                   6611:         }
                   6612:     }
                   6613:     return;
                   6614: }
                   6615: 
1.461     www      6616: # -------------------------------------------------See if a user is privileged
                   6617: 
                   6618: sub privileged {
1.1219    raeburn  6619:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6620:     my $now = time;
1.1219    raeburn  6621:     my $roles;
                   6622:     if (ref($possroles) eq 'ARRAY') {
                   6623:         $roles = $possroles; 
                   6624:     } else {
                   6625:         $roles = ['dc','su'];
                   6626:     }
                   6627:     if (ref($possdomains) eq 'ARRAY') {
                   6628:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6629:         foreach my $dom (@{$possdomains}) {
                   6630:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6631:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6632:                 foreach my $role (@{$roles}) {
                   6633:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6634:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6635:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6636:                             return 1 unless (($end && $end < $now) ||
                   6637:                                              ($start && $start > $now));
                   6638:                         }
                   6639:                     }
                   6640:                 }
                   6641:             }
                   6642:         }
                   6643:     } else {
                   6644:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6645:         my $now = time;
1.1170    droeschl 6646: 
1.1275    musolffc 6647:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6648:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6649:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6650:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6651:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6652:             }
1.1219    raeburn  6653:         }
                   6654:     }
                   6655:     return 0;
                   6656: }
1.1170    droeschl 6657: 
1.1219    raeburn  6658: sub privileged_by_domain {
                   6659:     my ($domains,$roles) = @_;
                   6660:     my %privileged = ();
                   6661:     my $cachetime = 60*60*24;
                   6662:     my $now = time;
                   6663:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6664:         return %privileged;
                   6665:     }
                   6666:     foreach my $dom (@{$domains}) {
                   6667:         next if (ref($privileged{$dom}) eq 'HASH');
                   6668:         my $needroles;
                   6669:         foreach my $role (@{$roles}) {
                   6670:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6671:             if (defined($cached)) {
                   6672:                 if (ref($result) eq 'HASH') {
                   6673:                     $privileged{$dom}{$role} = $result;
                   6674:                 }
                   6675:             } else {
                   6676:                 $needroles = 1;
                   6677:             }
                   6678:         }
                   6679:         if ($needroles) {
                   6680:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6681:             $privileged{$dom} = {};
                   6682:             foreach my $server (keys(%dompersonnel)) {
                   6683:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6684:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6685:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6686:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6687:                         next if ($end && $end < $now);
                   6688:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6689:                             $dompersonnel{$server}{$item};
                   6690:                     }
                   6691:                 }
                   6692:             }
                   6693:             if (ref($privileged{$dom}) eq 'HASH') {
                   6694:                 foreach my $role (@{$roles}) {
                   6695:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6696:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6697:                     } else {
                   6698:                         my %hash = ();
                   6699:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6700:                     }
                   6701:                 }
                   6702:             }
                   6703:         }
                   6704:     }
                   6705:     return %privileged;
1.9       www      6706: }
1.1       albertel 6707: 
1.103     harris41 6708: # -------------------------------------------------------- Get user privileges
1.11      www      6709: 
                   6710: sub rolesinit {
1.1169    droeschl 6711:     my ($domain, $username) = @_;
                   6712:     my %userroles = ('user.login.time' => time);
                   6713:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6714: 
                   6715:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6716:     # also, blocking can be triggered by an activating timer
                   6717:     # it's saved in the user's %env.
                   6718:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6719:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6720:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6721:         %timerintchk, %timerintenv);
                   6722: 
1.1162    raeburn  6723:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6724:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6725:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6726:     }
1.1169    droeschl 6727: 
1.1162    raeburn  6728:     foreach my $key (keys(%timerinterval)) {
                   6729:         my ($cid,$rest) = split(/\0/,$key);
                   6730:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6731:     }
1.1169    droeschl 6732: 
1.11      www      6733:     my %allroles=();
1.1162    raeburn  6734:     my %allgroups=();
1.11      www      6735: 
1.1274    raeburn  6736:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6737:         my $role = $rolesdump{$area};
                   6738:         $area =~ s/\_\w\w$//;
                   6739: 
                   6740:         my ($trole, $tend, $tstart, $group_privs);
                   6741: 
                   6742:         if ($role =~ /^cr/) {
                   6743:         # Custom role, defined by a user 
                   6744:         # e.g., user.role.cr/msu/smith/mynewrole
                   6745:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6746:                 $trole = $1;
                   6747:                 ($tend, $tstart) = split('_', $2);
                   6748:             } else {
                   6749:                 $trole = $role;
                   6750:             }
                   6751:         } elsif ($role =~ m|^gr/|) {
                   6752:         # Role of member in a group, defined within a course/community
                   6753:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6754:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6755:             next if $tstart eq '-1';
                   6756:             ($trole, $group_privs) = split(/\//, $trole);
                   6757:             $group_privs = &unescape($group_privs);
                   6758:         } else {
                   6759:         # Just a normal role, defined in roles.tab
                   6760:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6761:         }
                   6762: 
                   6763:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6764:                  $username);
                   6765:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6766: 
                   6767:         # role expired or not available yet?
                   6768:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6769:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6770: 
                   6771:         next if $area eq '' or $trole eq '';
                   6772: 
                   6773:         my $spec = "$trole.$area";
                   6774:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6775: 
                   6776:         if ($trole =~ /^cr\//) {
                   6777:         # Custom role, defined by a user
                   6778:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6779:         } elsif ($trole eq 'gr') {
                   6780:         # Role of a member in a group, defined within a course/community
                   6781:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6782:             next;
                   6783:         } else {
                   6784:         # Normal role, defined in roles.tab
                   6785:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6786:         }
                   6787: 
                   6788:         my $cid = $tdomain.'_'.$trest;
                   6789:         unless ($firstaccchk{$cid}) {
                   6790:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6791:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6792:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6793:                         $coursetimerstarts{$cid}{$item}; 
                   6794:                 }
                   6795:             }
                   6796:             $firstaccchk{$cid} = 1;
                   6797:         }
                   6798:         unless ($timerintchk{$cid}) {
                   6799:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6800:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6801:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6802:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6803:                 }
1.12      www      6804:             }
1.1169    droeschl 6805:             $timerintchk{$cid} = 1;
1.191     harris41 6806:         }
1.11      www      6807:     }
1.1169    droeschl 6808: 
1.1341    raeburn  6809:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6810:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6811:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6812:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6813: 
1.1162    raeburn  6814:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6815: }
                   6816: 
1.567     raeburn  6817: sub set_arearole {
1.1215    raeburn  6818:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6819:     unless ($nolog) {
1.567     raeburn  6820: # log the associated role with the area
1.1215    raeburn  6821:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6822:     }
1.743     albertel 6823:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6824: }
                   6825: 
                   6826: sub custom_roleprivs {
                   6827:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6828:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6829:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6830:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6831:         my ($rdummy,$roledef)=
                   6832:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6833:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6834:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6835:             if (defined($syspriv)) {
1.1043    raeburn  6836:                 if ($trest =~ /^$match_community$/) {
                   6837:                     $syspriv =~ s/bre\&S//; 
                   6838:                 }
1.567     raeburn  6839:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6840:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6841:             }
                   6842:             if ($tdomain ne '') {
                   6843:                 if (defined($dompriv)) {
                   6844:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6845:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6846:                 }
                   6847:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6848:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6849:                         my $rolename = $1;
                   6850:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6851:                     }
1.567     raeburn  6852:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6853:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6854:                 }
                   6855:             }
                   6856:         }
                   6857:     }
                   6858: }
                   6859: 
1.1332    raeburn  6860: sub course_adhocrole_privs {
                   6861:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6862:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6863:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6864:         my (%currprivs,%storeprivs);
                   6865:         foreach my $item (split(/:/,$coursepriv)) {
                   6866:             my ($priv,$restrict) = split(/\&/,$item);
                   6867:             $currprivs{$priv} = $restrict;
                   6868:         }
                   6869:         my (%possadd,%possremove,%full);
                   6870:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6871:             my ($priv,$restrict)=split(/\&/,$item);
                   6872:             $full{$priv} = $restrict;
                   6873:         }
                   6874:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490    raeburn  6875:             next if ($item eq '');
                   6876:             my ($rule,$rest) = split(/=/,$item);
                   6877:             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6878:             foreach my $priv (split(/:/,$rest)) {
                   6879:                 if ($priv ne '') {
                   6880:                     if ($rule eq 'off') {
                   6881:                         $possremove{$priv} = 1;
                   6882:                     } else {
                   6883:                         $possadd{$priv} = 1;
                   6884:                     }
                   6885:                 }
                   6886:             }
                   6887:         }
                   6888:         foreach my $priv (sort(keys(%full))) {
                   6889:             if (exists($currprivs{$priv})) {
                   6890:                 unless (exists($possremove{$priv})) {
                   6891:                     $storeprivs{$priv} = $currprivs{$priv};
                   6892:                 }
                   6893:             } elsif (exists($possadd{$priv})) {
                   6894:                 $storeprivs{$priv} = $full{$priv};
                   6895:             }
                   6896:         }
                   6897:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6898:     }
                   6899:     return $coursepriv;
1.1332    raeburn  6900: }
                   6901: 
1.678     raeburn  6902: sub group_roleprivs {
                   6903:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6904:     my $access = 1;
                   6905:     my $now = time;
                   6906:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6907:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6908:     if ($access) {
1.811     albertel 6909:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6910:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6911:     }
                   6912: }
1.567     raeburn  6913: 
                   6914: sub standard_roleprivs {
                   6915:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6916:     if (defined($pr{$trole.':s'})) {
                   6917:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6918:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6919:     }
                   6920:     if ($tdomain ne '') {
                   6921:         if (defined($pr{$trole.':d'})) {
                   6922:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6923:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6924:         }
                   6925:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6926:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6927:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6928:         }
                   6929:     }
                   6930: }
                   6931: 
                   6932: sub set_userprivs {
1.1064    raeburn  6933:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6934:     my $author=0;
                   6935:     my $adv=0;
1.1341    raeburn  6936:     my $rar=0;
1.678     raeburn  6937:     my %grouproles = ();
                   6938:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6939:         my @groupkeys; 
1.1000    raeburn  6940:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6941:             push(@groupkeys,$role);
                   6942:         }
                   6943:         if (ref($groups_roles) eq 'HASH') {
                   6944:             foreach my $key (keys(%{$groups_roles})) {
                   6945:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6946:                     push(@groupkeys,$key);
                   6947:                 }
                   6948:             }
                   6949:         }
                   6950:         if (@groupkeys > 0) {
                   6951:             foreach my $role (@groupkeys) {
                   6952:                 my ($trole,$area,$sec,$extendedarea);
                   6953:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6954:                     $trole = $1;
                   6955:                     $area = $2;
                   6956:                     $sec = $3;
                   6957:                     $extendedarea = $area.$sec;
                   6958:                     if (exists($$allgroups{$area})) {
                   6959:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6960:                             my $spec = $trole.'.'.$extendedarea;
                   6961:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6962:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6963:                         }
1.678     raeburn  6964:                     }
                   6965:                 }
                   6966:             }
                   6967:         }
                   6968:     }
1.800     albertel 6969:     foreach my $group (keys(%grouproles)) {
                   6970:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6971:     }
1.800     albertel 6972:     foreach my $role (keys(%{$allroles})) {
                   6973:         my %thesepriv;
1.941     raeburn  6974:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6975:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6976:             if ($item ne '') {
                   6977:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6978:                 if ($restrictions eq '') {
                   6979:                     $thesepriv{$privilege}='F';
                   6980:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6981:                     $thesepriv{$privilege}.=$restrictions;
                   6982:                 }
                   6983:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6984:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6985:             }
                   6986:         }
                   6987:         my $thesestr='';
1.1104    raeburn  6988:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6989: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6990: 	}
                   6991:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6992:     }
1.1341    raeburn  6993:     return ($author,$adv,$rar);
1.567     raeburn  6994: }
                   6995: 
1.994     raeburn  6996: sub role_status {
1.1104    raeburn  6997:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6998:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6999:         my ($one,$two) = split(m{\./},$rolekey,2);
                   7000:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  7001:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  7002:             $$where = '/'.$two;
1.994     raeburn  7003:             $$trolecode=$$role.'.'.$$where;
                   7004:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   7005:             $$tstatus='is';
1.1104    raeburn  7006:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  7007:                 $$tstatus='future';
1.1034    raeburn  7008:                 if ($$tstart<$now) {
                   7009:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  7010:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  7011:                             my (%allroles,%allgroups,$group_privs,
                   7012:                                 %groups_roles,@rolecodes);
1.1002    raeburn  7013:                             my %userroles = (
                   7014:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   7015:                             );
1.1064    raeburn  7016:                             @rolecodes = ('cm'); 
1.1002    raeburn  7017:                             my $spec=$$role.'.'.$$where;
                   7018:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   7019:                             if ($$role =~ /^cr\//) {
                   7020:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  7021:                                 push(@rolecodes,'cr');
1.1002    raeburn  7022:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  7023:                                 push(@rolecodes,$$role);
1.1002    raeburn  7024:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   7025:                                                     $env{'user.name'});
1.1064    raeburn  7026:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  7027:                                 (undef,my $group_privs) = split(/\//,$trole);
                   7028:                                 $group_privs = &unescape($group_privs);
                   7029:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  7030:                                 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  7031:                                 &get_groups_roles($tdomain,$trest,
                   7032:                                                   \%course_roles,\@rolecodes,
                   7033:                                                   \%groups_roles);
1.1002    raeburn  7034:                             } else {
1.1064    raeburn  7035:                                 push(@rolecodes,$$role);
1.1002    raeburn  7036:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7037:                             }
1.1341    raeburn  7038:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7039:                                                                    \%groups_roles);
1.1064    raeburn  7040:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  7041:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7042:                         }
                   7043:                     }
1.1034    raeburn  7044:                     $$tstatus = 'is';
1.1002    raeburn  7045:                 }
1.994     raeburn  7046:             }
                   7047:             if ($$tend) {
1.1104    raeburn  7048:                 if ($$tend<$update) {
1.994     raeburn  7049:                     $$tstatus='expired';
                   7050:                 } elsif ($$tend<$now) {
                   7051:                     $$tstatus='will_not';
                   7052:                 }
                   7053:             }
                   7054:         }
                   7055:     }
                   7056: }
                   7057: 
1.1104    raeburn  7058: sub get_groups_roles {
                   7059:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7060:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7061:                   (ref($rolecodes) eq 'ARRAY') && 
                   7062:                   (ref($groups_roles) eq 'HASH')); 
                   7063:     if (keys(%{$cdom_courseroles}) > 0) {
                   7064:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7065:         if ($cdom ne '' && $cnum ne '') {
                   7066:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7067:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7068:                     my $crsrole = $1;
                   7069:                     my $crssec = $2;
                   7070:                     if ($crsrole =~ /^cr/) {
                   7071:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7072:                             push(@{$rolecodes},'cr');
                   7073:                         }
                   7074:                     } else {
                   7075:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7076:                             push(@{$rolecodes},$crsrole);
                   7077:                         }
                   7078:                     }
                   7079:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7080:                     if ($crssec ne '') {
                   7081:                         $rolekey .= "/$crssec";
                   7082:                     }
                   7083:                     $rolekey .= './';
                   7084:                     $groups_roles->{$rolekey} = $rolecodes;
                   7085:                 }
                   7086:             }
                   7087:         }
                   7088:     }
                   7089:     return;
                   7090: }
                   7091: 
                   7092: sub delete_env_groupprivs {
                   7093:     my ($where,$courseroles,$possroles) = @_;
                   7094:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7095:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7096:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7097:         %{$courseroles->{$udom}} =
                   7098:             &get_my_roles('','','userroles',['active'],
                   7099:                           $possroles,[$udom],1);
                   7100:     }
                   7101:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7102:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7103:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7104:             my $area = '/'.$cdom.'/'.$cnum;
                   7105:             my $privkey = "user.priv.$crsrole.$area";
                   7106:             if ($crssec ne '') {
                   7107:                 $privkey .= '/'.$crssec;
                   7108:             }
                   7109:             $privkey .= ".$area/$group";
                   7110:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7111:         }
                   7112:     }
                   7113:     return;
                   7114: }
                   7115: 
1.994     raeburn  7116: sub check_adhoc_privs {
1.1329    raeburn  7117:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7118:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  7119:     if ($sec) {
                   7120:         $cckey .= '/'.$sec;
                   7121:     } 
1.1185    raeburn  7122:     my $setprivs;
1.994     raeburn  7123:     if ($env{$cckey}) {
                   7124:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7125:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7126:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  7127:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7128:             $setprivs = 1;
1.994     raeburn  7129:         }
                   7130:     } else {
1.1330    raeburn  7131:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7132:         $setprivs = 1;
1.994     raeburn  7133:     }
1.1185    raeburn  7134:     return $setprivs;
1.994     raeburn  7135: }
                   7136: 
                   7137: sub set_adhoc_privileges {
1.1326    raeburn  7138: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  7139:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7140:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  7141:     if ($sec ne '') {
                   7142:         $area .= '/'.$sec;
                   7143:     }
1.994     raeburn  7144:     my $spec = $role.'.'.$area;
                   7145:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  7146:                                   $env{'user.name'},1);
1.1326    raeburn  7147:     my %rolehash = ();
1.1332    raeburn  7148:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7149:         my $rolename = $1;
1.1326    raeburn  7150:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  7151:         my %domdef = &get_domain_defaults($dcdom);
                   7152:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7153:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7154:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7155:             }
                   7156:         }
1.1326    raeburn  7157:     } else {
                   7158:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7159:     }
1.1341    raeburn  7160:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7161:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  7162:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  7163:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7164:             ($caller eq 'tiny')) {
1.1088    raeburn  7165:         &appenv( {'request.role'        => $spec,
                   7166:                   'request.role.domain' => $dcdom,
1.1332    raeburn  7167:                   'request.course.sec'  => $sec,
1.1088    raeburn  7168:                  }
                   7169:                );
                   7170:         my $tadv=0;
                   7171:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7172:         &appenv({'request.role.adv'    => $tadv});
                   7173:     }
1.994     raeburn  7174: }
                   7175: 
1.12      www      7176: # --------------------------------------------------------------- get interface
                   7177: 
                   7178: sub get {
1.131     albertel 7179:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7180:    my $items='';
1.800     albertel 7181:    foreach my $item (@$storearr) {
                   7182:        $items.=&escape($item).'&';
1.191     harris41 7183:    }
1.12      www      7184:    $items=~s/\&$//;
1.620     albertel 7185:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7186:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7187:    my $uhome=&homeserver($uname,$udomain);
                   7188: 
1.133     albertel 7189:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7190:    my @pairs=split(/\&/,$rep);
1.273     albertel 7191:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7192:      return @pairs;
                   7193:    }
1.15      www      7194:    my %returnhash=();
1.42      www      7195:    my $i=0;
1.800     albertel 7196:    foreach my $item (@$storearr) {
                   7197:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7198:       $i++;
1.191     harris41 7199:    }
1.15      www      7200:    return %returnhash;
1.27      www      7201: }
                   7202: 
                   7203: # --------------------------------------------------------------- del interface
                   7204: 
                   7205: sub del {
1.133     albertel 7206:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7207:    my $items='';
1.800     albertel 7208:    foreach my $item (@$storearr) {
                   7209:        $items.=&escape($item).'&';
1.191     harris41 7210:    }
1.984     neumanie 7211: 
1.27      www      7212:    $items=~s/\&$//;
1.620     albertel 7213:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7214:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7215:    my $uhome=&homeserver($uname,$udomain);
                   7216:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7217: }
                   7218: 
                   7219: # -------------------------------------------------------------- dump interface
                   7220: 
1.1180    droeschl 7221: sub unserialize {
                   7222:     my ($rep, $escapedkeys) = @_;
                   7223: 
                   7224:     return {} if $rep =~ /^error/;
                   7225: 
                   7226:     my %returnhash=();
1.1252    raeburn  7227: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7228: 	    my ($key, $value) = split(/=/, $item, 2);
                   7229: 	    $key = unescape($key) unless $escapedkeys;
                   7230: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7231: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7232: 	}
                   7233:     #return %returnhash;
                   7234:     return \%returnhash;
                   7235: }        
                   7236: 
                   7237: # see Lond::dump_with_regexp
                   7238: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7239: sub dump {
1.1462    raeburn  7240:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7241:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7242:     if (!$uname) { $uname=$env{'user.name'}; }
                   7243:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7244: 
1.1266    raeburn  7245:     if ($regexp) {
                   7246:         $regexp=&escape($regexp);
                   7247:     } else {
                   7248:         $regexp='.';
                   7249:     }
1.1180    droeschl 7250:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7251:         # user is hosted on this machine
1.1266    raeburn  7252:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7253:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7254:         return %{unserialize($reply, $escapedkeys)};
                   7255:     }
1.1462    raeburn  7256:     my $rep;
                   7257:     if ($encrypt) {
                   7258:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463    raeburn  7259:     } else {
1.1462    raeburn  7260:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7261:     }
1.755     albertel 7262:     my @pairs=split(/\&/,$rep);
                   7263:     my %returnhash=();
1.1098    foxr     7264:     if (!($rep =~ /^error/ )) {
                   7265: 	foreach my $item (@pairs) {
                   7266: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7267:         $key = unescape($key) unless $escapedkeys;
                   7268:         #$key = &unescape($key);
1.1098    foxr     7269: 	    next if ($key =~ /^error: 2 /);
                   7270: 	    $returnhash{$key}=&thaw_unescape($value);
                   7271: 	}
1.755     albertel 7272:     }
                   7273:     return %returnhash;
1.407     www      7274: }
                   7275: 
1.1098    foxr     7276: 
1.717     albertel 7277: # --------------------------------------------------------- dumpstore interface
                   7278: 
                   7279: sub dumpstore {
                   7280:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7281:    # same as dump but keys must be escaped. They may contain colon separated
                   7282:    # lists of values that may themself contain colons (e.g. symbs).
                   7283:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7284: }
                   7285: 
1.407     www      7286: # -------------------------------------------------------------- keys interface
                   7287: 
                   7288: sub getkeys {
                   7289:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7290:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7291:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7292:    my $uhome=&homeserver($uname,$udomain);
                   7293:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7294:    my @keyarray=();
1.800     albertel 7295:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7296:       next if ($key =~ /^error: 2 /);
1.800     albertel 7297:       push(@keyarray,&unescape($key));
1.407     www      7298:    }
                   7299:    return @keyarray;
1.318     matthew  7300: }
                   7301: 
1.319     matthew  7302: # --------------------------------------------------------------- currentdump
                   7303: sub currentdump {
1.328     matthew  7304:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7305:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7306:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7307:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7308:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7309:    my $rep;
                   7310: 
                   7311:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7312:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7313:                    $courseid)));
                   7314:    } else {
                   7315:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7316:    }
                   7317: 
1.318     matthew  7318:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7319:    #
1.318     matthew  7320:    my %returnhash=();
1.319     matthew  7321:    #
1.1343    raeburn  7322:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7323:        # an old lond will not know currentdump
                   7324:        # Do a dump and make it look like a currentdump
1.822     albertel 7325:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7326:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7327:        my %hash = @tmp;
                   7328:        @tmp=();
1.424     matthew  7329:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7330:    } else {
                   7331:        my @pairs=split(/\&/,$rep);
1.800     albertel 7332:        foreach my $pair (@pairs) {
                   7333:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7334:            my ($symb,$param) = split(/:/,$key);
                   7335:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7336:                                                         &thaw_unescape($value);
1.319     matthew  7337:        }
1.191     harris41 7338:    }
1.12      www      7339:    return %returnhash;
1.424     matthew  7340: }
                   7341: 
                   7342: sub convert_dump_to_currentdump{
                   7343:     my %hash = %{shift()};
                   7344:     my %returnhash;
                   7345:     # Code ripped from lond, essentially.  The only difference
                   7346:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7347:     # we might run in to problems with parameter names =~ /^v\./
                   7348:     while (my ($key,$value) = each(%hash)) {
                   7349:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7350: 	$symb  = &unescape($symb);
                   7351: 	$param = &unescape($param);
1.424     matthew  7352:         next if ($v eq 'version' || $symb eq 'keys');
                   7353:         next if (exists($returnhash{$symb}) &&
                   7354:                  exists($returnhash{$symb}->{$param}) &&
                   7355:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7356:         $returnhash{$symb}->{$param}=$value;
                   7357:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7358:     }
                   7359:     #
                   7360:     # Remove all of the keys in the hashes which keep track of
                   7361:     # the version of the parameter.
                   7362:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7363:         # use a foreach because we are going to delete from the hash.
                   7364:         foreach my $key (keys(%$param_hash)) {
                   7365:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7366:         }
                   7367:     }
                   7368:     return \%returnhash;
1.12      www      7369: }
                   7370: 
1.627     albertel 7371: # ------------------------------------------------------ critical inc interface
                   7372: 
                   7373: sub cinc {
                   7374:     return &inc(@_,'critical');
                   7375: }
                   7376: 
1.449     matthew  7377: # --------------------------------------------------------------- inc interface
                   7378: 
                   7379: sub inc {
1.627     albertel 7380:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7381:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7382:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7383:     my $uhome=&homeserver($uname,$udomain);
                   7384:     my $items='';
                   7385:     if (! ref($store)) {
                   7386:         # got a single value, so use that instead
                   7387:         $items = &escape($store).'=&';
                   7388:     } elsif (ref($store) eq 'SCALAR') {
                   7389:         $items = &escape($$store).'=&';        
                   7390:     } elsif (ref($store) eq 'ARRAY') {
                   7391:         $items = join('=&',map {&escape($_);} @{$store});
                   7392:     } elsif (ref($store) eq 'HASH') {
                   7393:         while (my($key,$value) = each(%{$store})) {
                   7394:             $items.= &escape($key).'='.&escape($value).'&';
                   7395:         }
                   7396:     }
                   7397:     $items=~s/\&$//;
1.627     albertel 7398:     if ($critical) {
                   7399: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7400:     } else {
                   7401: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7402:     }
1.449     matthew  7403: }
                   7404: 
1.12      www      7405: # --------------------------------------------------------------- put interface
                   7406: 
                   7407: sub put {
1.1462    raeburn  7408:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7409:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7410:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7411:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7412:    my $items='';
1.800     albertel 7413:    foreach my $item (keys(%$storehash)) {
                   7414:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7415:    }
1.12      www      7416:    $items=~s/\&$//;
1.1462    raeburn  7417:    if ($encrypt) {
                   7418:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7419:    } else {
                   7420:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7421:    }
1.47      www      7422: }
                   7423: 
1.631     albertel 7424: # ------------------------------------------------------------ newput interface
                   7425: 
                   7426: sub newput {
                   7427:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7428:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7429:    if (!$uname) { $uname=$env{'user.name'}; }
                   7430:    my $uhome=&homeserver($uname,$udomain);
                   7431:    my $items='';
                   7432:    foreach my $key (keys(%$storehash)) {
                   7433:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7434:    }
                   7435:    $items=~s/\&$//;
                   7436:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7437: }
                   7438: 
                   7439: # ---------------------------------------------------------  putstore interface
                   7440: 
1.524     raeburn  7441: sub putstore {
1.1269    raeburn  7442:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7443:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7444:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7445:    my $uhome=&homeserver($uname,$udomain);
                   7446:    my $items='';
1.715     albertel 7447:    foreach my $key (keys(%$storehash)) {
                   7448:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7449:    }
1.715     albertel 7450:    $items=~s/\&$//;
1.716     albertel 7451:    my $esc_symb=&escape($symb);
                   7452:    my $esc_v=&escape($version);
1.715     albertel 7453:    my $reply =
1.716     albertel 7454:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7455: 	      $uhome);
1.1269    raeburn  7456:    if (($tolog) && ($reply eq 'ok')) {
                   7457:        my $namevalue='';
                   7458:        foreach my $key (keys(%{$storehash})) {
                   7459:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7460:        }
1.1434    raeburn  7461:        my $ip = &get_requestor_ip();
                   7462:        $namevalue .= 'ip='.&escape($ip).
1.1269    raeburn  7463:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7464:                      '&version='.$esc_v.
                   7465:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7466:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7467:    }
1.715     albertel 7468:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7469:        # gfall back to way things use to be done
1.715     albertel 7470:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7471: 			    $uname);
1.524     raeburn  7472:    }
1.715     albertel 7473:    return $reply;
                   7474: }
                   7475: 
                   7476: sub old_putstore {
1.716     albertel 7477:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7478:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7479:     if (!$uname) { $uname=$env{'user.name'}; }
                   7480:     my $uhome=&homeserver($uname,$udomain);
                   7481:     my %newstorehash;
1.800     albertel 7482:     foreach my $item (keys(%$storehash)) {
                   7483: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7484: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7485:     }
                   7486:     my $items='';
                   7487:     my %allitems = ();
1.800     albertel 7488:     foreach my $item (keys(%newstorehash)) {
                   7489: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7490: 	    my $key = $1.':keys:'.$2;
                   7491: 	    $allitems{$key} .= $3.':';
                   7492: 	}
1.800     albertel 7493: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7494:     }
1.800     albertel 7495:     foreach my $item (keys(%allitems)) {
                   7496: 	$allitems{$item} =~ s/\:$//;
                   7497: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7498:     }
                   7499:     $items=~s/\&$//;
                   7500:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7501: }
                   7502: 
1.47      www      7503: # ------------------------------------------------------ critical put interface
                   7504: 
                   7505: sub cput {
1.134     albertel 7506:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7507:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7508:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7509:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7510:    my $items='';
1.800     albertel 7511:    foreach my $item (keys(%$storehash)) {
                   7512:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7513:    }
1.47      www      7514:    $items=~s/\&$//;
1.134     albertel 7515:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7516: }
                   7517: 
                   7518: # -------------------------------------------------------------- eget interface
                   7519: 
                   7520: sub eget {
1.133     albertel 7521:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7522:    my $items='';
1.800     albertel 7523:    foreach my $item (@$storearr) {
                   7524:        $items.=&escape($item).'&';
1.191     harris41 7525:    }
1.12      www      7526:    $items=~s/\&$//;
1.620     albertel 7527:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7528:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7529:    my $uhome=&homeserver($uname,$udomain);
                   7530:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7531:    my @pairs=split(/\&/,$rep);
                   7532:    my %returnhash=();
1.42      www      7533:    my $i=0;
1.800     albertel 7534:    foreach my $item (@$storearr) {
                   7535:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7536:       $i++;
1.191     harris41 7537:    }
1.12      www      7538:    return %returnhash;
                   7539: }
                   7540: 
1.667     albertel 7541: # ------------------------------------------------------------ tmpput interface
                   7542: sub tmpput {
1.802     raeburn  7543:     my ($storehash,$server,$context)=@_;
1.667     albertel 7544:     my $items='';
1.800     albertel 7545:     foreach my $item (keys(%$storehash)) {
                   7546: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7547:     }
                   7548:     $items=~s/\&$//;
1.802     raeburn  7549:     if (defined($context)) {
                   7550:         $items .= ':'.&escape($context);
                   7551:     }
1.667     albertel 7552:     return &reply("tmpput:$items",$server);
                   7553: }
                   7554: 
                   7555: # ------------------------------------------------------------ tmpget interface
                   7556: sub tmpget {
1.688     albertel 7557:     my ($token,$server)=@_;
                   7558:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7559:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7560:     my %returnhash;
1.1328    raeburn  7561:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7562:         return %returnhash;
                   7563:     }
1.667     albertel 7564:     foreach my $item (split(/\&/,$rep)) {
                   7565: 	my ($key,$value)=split(/=/,$item);
                   7566: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7567:     }
                   7568:     return %returnhash;
                   7569: }
                   7570: 
1.1113    raeburn  7571: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7572: sub tmpdel {
                   7573:     my ($token,$server)=@_;
                   7574:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7575:     return &reply("tmpdel:$token",$server);
                   7576: }
                   7577: 
1.1198    raeburn  7578: # ------------------------------------------------------------ get_timebased_id 
                   7579: 
                   7580: sub get_timebased_id {
                   7581:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7582:         $maxtries) = @_;
                   7583:     my ($newid,$error,$dellock);
                   7584:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7585:         return ('','ok','invalid call to get suffix');
                   7586:     }
                   7587: 
                   7588: # set defaults for any optional args for which values were not supplied
                   7589:     if ($who eq '') {
                   7590:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7591:     }
                   7592:     if (!$locktries) {
                   7593:         $locktries = 3;
                   7594:     }
                   7595:     if (!$maxtries) {
                   7596:         $maxtries = 10;
                   7597:     }
                   7598:     
                   7599:     if (($cdom eq '') || ($cnum eq '')) {
                   7600:         if ($env{'request.course.id'}) {
                   7601:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7602:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7603:         }
                   7604:         if (($cdom eq '') || ($cnum eq '')) {
                   7605:             return ('','ok','call to get suffix not in course context');
                   7606:         }
                   7607:     }
                   7608: 
                   7609: # construct locking item
                   7610:     my $lockhash = {
                   7611:                       $prefix."\0".'locked_'.$keyid => $who,
                   7612:                    };
                   7613:     my $tries = 0;
                   7614: 
                   7615: # attempt to get lock on nohist_$namespace file
                   7616:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7617:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7618:         $tries ++;
                   7619:         sleep 1;
                   7620:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7621:     }
                   7622: 
                   7623: # attempt to get unique identifier, based on current timestamp
                   7624:     if ($gotlock eq 'ok') {
                   7625:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7626:         my $id = time;
                   7627:         $newid = $id;
1.1268    raeburn  7628:         if ($idtype eq 'addcode') {
                   7629:             $newid .= &sixnum_code();
                   7630:         }
1.1198    raeburn  7631:         my $idtries = 0;
                   7632:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7633:             if ($idtype eq 'concat') {
                   7634:                 $newid = $id.$idtries;
1.1268    raeburn  7635:             } elsif ($idtype eq 'addcode') {
                   7636:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7637:             } else {
                   7638:                 $newid ++;
                   7639:             }
                   7640:             $idtries ++;
                   7641:         }
                   7642:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7643:             my %new_item =  (
                   7644:                               $prefix."\0".$newid => $who,
                   7645:                             );
                   7646:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7647:                                                  $cdom,$cnum);
                   7648:             if ($putresult ne 'ok') {
                   7649:                 undef($newid);
                   7650:                 $error = 'error saving new item: '.$putresult;
                   7651:             }
                   7652:         } else {
1.1268    raeburn  7653:              undef($newid);
1.1198    raeburn  7654:              $error = ('error: no unique suffix available for the new item ');
                   7655:         }
                   7656: #  remove lock
                   7657:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7658:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7659:     } else {
                   7660:         $error = "error: could not obtain lockfile\n";
                   7661:         $dellock = 'ok';
1.1276    raeburn  7662:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7663:             $dellock = 'nolock';
                   7664:         }
1.1198    raeburn  7665:     }
                   7666:     return ($newid,$dellock,$error);
                   7667: }
                   7668: 
1.1268    raeburn  7669: sub sixnum_code {
                   7670:     my $code;
                   7671:     for (0..6) {
                   7672:         $code .= int( rand(9) );
                   7673:     }
                   7674:     return $code;
                   7675: }
                   7676: 
1.765     albertel 7677: # -------------------------------------------------- portfolio access checking
                   7678: 
                   7679: sub portfolio_access {
1.1270    raeburn  7680:     my ($requrl,$clientip) = @_;
1.765     albertel 7681:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7682:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7683:     if ($result) {
                   7684:         my %setters;
                   7685:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473    raeburn  7686:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7687:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7688:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7689:                 return 'B';
                   7690:             }
                   7691:         } else {
1.1473    raeburn  7692:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7693:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7694:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7695:                 return 'B';
                   7696:             }
                   7697:         }
                   7698:     }
1.765     albertel 7699:     if ($result eq 'ok') {
1.766     albertel 7700:        return 'F';
1.765     albertel 7701:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7702:        return 'A';
1.765     albertel 7703:     }
1.766     albertel 7704:     return '';
1.765     albertel 7705: }
                   7706: 
                   7707: sub get_portfolio_access {
1.1270    raeburn  7708:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7709: 
                   7710:     if (!ref($access_hash)) {
                   7711: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7712: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7713: 						   $file_name);
                   7714: 	$access_hash = $access_controls{$file_name};
                   7715:     }
                   7716: 
1.1270    raeburn  7717:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7718:     my $now = time;
                   7719:     if (ref($access_hash) eq 'HASH') {
                   7720:         foreach my $key (keys(%{$access_hash})) {
                   7721:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7722:             if ($start > $now) {
                   7723:                 next;
                   7724:             }
                   7725:             if ($end && $end<$now) {
                   7726:                 next;
                   7727:             }
                   7728:             if ($scope eq 'public') {
                   7729:                 $public = $key;
                   7730:                 last;
                   7731:             } elsif ($scope eq 'guest') {
                   7732:                 $guest = $key;
                   7733:             } elsif ($scope eq 'domains') {
                   7734:                 push(@domains,$key);
                   7735:             } elsif ($scope eq 'users') {
                   7736:                 push(@users,$key);
                   7737:             } elsif ($scope eq 'course') {
                   7738:                 push(@courses,$key);
                   7739:             } elsif ($scope eq 'group') {
                   7740:                 push(@groups,$key);
1.1270    raeburn  7741:             } elsif ($scope eq 'ip') {
                   7742:                 push(@ips,$key);
1.765     albertel 7743:             }
                   7744:         }
                   7745:         if ($public) {
                   7746:             return 'ok';
1.1270    raeburn  7747:         } elsif (@ips > 0) {
                   7748:             my $allowed;
                   7749:             foreach my $ipkey (@ips) {
                   7750:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7751:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7752:                         $allowed = 1;
                   7753:                         last; 
                   7754:                     }
                   7755:                 }
                   7756:             }
                   7757:             if ($allowed) {
                   7758:                 return 'ok';
                   7759:             }
1.765     albertel 7760:         }
                   7761:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7762:             if ($guest) {
                   7763:                 return $guest;
                   7764:             }
                   7765:         } else {
                   7766:             if (@domains > 0) {
                   7767:                 foreach my $domkey (@domains) {
                   7768:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7769:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7770:                             return 'ok';
                   7771:                         }
                   7772:                     }
                   7773:                 }
                   7774:             }
                   7775:             if (@users > 0) {
                   7776:                 foreach my $userkey (@users) {
1.865     raeburn  7777:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7778:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7779:                             if (ref($item) eq 'HASH') {
                   7780:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7781:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7782:                                     return 'ok';
                   7783:                                 }
                   7784:                             }
                   7785:                         }
                   7786:                     } 
1.765     albertel 7787:                 }
                   7788:             }
                   7789:             my %roleshash;
                   7790:             my @courses_and_groups = @courses;
                   7791:             push(@courses_and_groups,@groups); 
                   7792:             if (@courses_and_groups > 0) {
                   7793:                 my (%allgroups,%allroles); 
                   7794:                 my ($start,$end,$role,$sec,$group);
                   7795:                 foreach my $envkey (%env) {
1.1060    raeburn  7796:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7797:                         my $cid = $2.'_'.$3; 
                   7798:                         if ($1 eq 'gr') {
                   7799:                             $group = $4;
                   7800:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7801:                         } else {
                   7802:                             if ($4 eq '') {
                   7803:                                 $sec = 'none';
                   7804:                             } else {
                   7805:                                 $sec = $4;
                   7806:                             }
                   7807:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7808:                         }
1.811     albertel 7809:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7810:                         my $cid = $2.'_'.$3;
                   7811:                         if ($4 eq '') {
                   7812:                             $sec = 'none';
                   7813:                         } else {
                   7814:                             $sec = $4;
                   7815:                         }
                   7816:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7817:                     }
                   7818:                 }
                   7819:                 if (keys(%allroles) == 0) {
                   7820:                     return;
                   7821:                 }
                   7822:                 foreach my $key (@courses_and_groups) {
                   7823:                     my %content = %{$$access_hash{$key}};
                   7824:                     my $cnum = $content{'number'};
                   7825:                     my $cdom = $content{'domain'};
                   7826:                     my $cid = $cdom.'_'.$cnum;
                   7827:                     if (!exists($allroles{$cid})) {
                   7828:                         next;
                   7829:                     }    
                   7830:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7831:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7832:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7833:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7834:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7835:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7836:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7837:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7838:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7839:                                         if (grep/^all$/,@sections) {
                   7840:                                             return 'ok';
                   7841:                                         } else {
                   7842:                                             if (grep/^$sec$/,@sections) {
                   7843:                                                 return 'ok';
                   7844:                                             }
                   7845:                                         }
                   7846:                                     }
                   7847:                                 }
                   7848:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7849:                                     if (grep/^none$/,@groups) {
                   7850:                                         return 'ok';
                   7851:                                     }
                   7852:                                 } else {
                   7853:                                     if (grep/^all$/,@groups) {
                   7854:                                         return 'ok';
                   7855:                                     } 
                   7856:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7857:                                         if (grep/^$group$/,@groups) {
                   7858:                                             return 'ok';
                   7859:                                         }
                   7860:                                     }
                   7861:                                 } 
                   7862:                             }
                   7863:                         }
                   7864:                     }
                   7865:                 }
                   7866:             }
                   7867:             if ($guest) {
                   7868:                 return $guest;
                   7869:             }
                   7870:         }
                   7871:     }
                   7872:     return;
                   7873: }
                   7874: 
                   7875: sub course_group_datechecker {
                   7876:     my ($dates,$now,$status) = @_;
                   7877:     my ($start,$end) = split(/\./,$dates);
                   7878:     if (!$start && !$end) {
                   7879:         return 'ok';
                   7880:     }
                   7881:     if (grep/^active$/,@{$status}) {
                   7882:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7883:             return 'ok';
                   7884:         }
                   7885:     }
                   7886:     if (grep/^previous$/,@{$status}) {
                   7887:         if ($end > $now ) {
                   7888:             return 'ok';
                   7889:         }
                   7890:     }
                   7891:     if (grep/^future$/,@{$status}) {
                   7892:         if ($start > $now) {
                   7893:             return 'ok';
                   7894:         }
                   7895:     }
                   7896:     return; 
                   7897: }
                   7898: 
                   7899: sub parse_portfolio_url {
                   7900:     my ($url) = @_;
                   7901: 
                   7902:     my ($type,$udom,$unum,$group,$file_name);
                   7903:     
1.823     albertel 7904:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7905: 	$type = 1;
                   7906:         $udom = $1;
                   7907:         $unum = $2;
                   7908:         $file_name = $3;
1.823     albertel 7909:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7910: 	$type = 2;
                   7911:         $udom = $1;
                   7912:         $unum = $2;
                   7913:         $group = $3;
                   7914:         $file_name = $3.'/'.$4;
                   7915:     }
                   7916:     if (wantarray) {
                   7917: 	return ($type,$udom,$unum,$file_name,$group);
                   7918:     }
                   7919:     return $type;
                   7920: }
                   7921: 
                   7922: sub is_portfolio_url {
                   7923:     my ($url) = @_;
                   7924:     return scalar(&parse_portfolio_url($url));
                   7925: }
                   7926: 
1.798     raeburn  7927: sub is_portfolio_file {
                   7928:     my ($file) = @_;
1.820     raeburn  7929:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7930:         return 1;
                   7931:     }
                   7932:     return;
                   7933: }
                   7934: 
1.976     raeburn  7935: sub usertools_access {
1.1084    raeburn  7936:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7937:     my ($access,%tools);
                   7938:     if ($context eq '') {
                   7939:         $context = 'tools';
                   7940:     }
                   7941:     if ($context eq 'requestcourses') {
                   7942:         %tools = (
                   7943:                       official   => 1,
                   7944:                       unofficial => 1,
1.1006    raeburn  7945:                       community  => 1,
1.1246    raeburn  7946:                       textbook   => 1,
1.1305    raeburn  7947:                       placement  => 1,
1.1368    raeburn  7948:                       lti        => 1,
1.985     raeburn  7949:                  );
1.1183    raeburn  7950:     } elsif ($context eq 'requestauthor') {
                   7951:         %tools = (
                   7952:                       requestauthor => 1,
                   7953:                  );
1.985     raeburn  7954:     } else {
                   7955:         %tools = (
                   7956:                       aboutme   => 1,
                   7957:                       blog      => 1,
1.1177    raeburn  7958:                       webdav    => 1,
1.985     raeburn  7959:                       portfolio => 1,
1.1489    raeburn  7960:                       timezone  => 1,
1.985     raeburn  7961:                  );
                   7962:     }
1.976     raeburn  7963:     return if (!defined($tools{$tool}));
                   7964: 
1.1242    raeburn  7965:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7966:         $udom = $env{'user.domain'};
                   7967:         $uname = $env{'user.name'};
                   7968:     }
                   7969: 
1.978     raeburn  7970:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7971:         if ($action ne 'reload') {
1.985     raeburn  7972:             if ($context eq 'requestcourses') {
                   7973:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7974:             } elsif ($context eq 'requestauthor') {
                   7975:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7976:             } else {
                   7977:                 return $env{'environment.availabletools.'.$tool};
                   7978:             }
                   7979:         }
1.976     raeburn  7980:     }
                   7981: 
1.1183    raeburn  7982:     my ($toolstatus,$inststatus,$envkey);
                   7983:     if ($context eq 'requestauthor') {
                   7984:         $envkey = $context; 
                   7985:     } else {
                   7986:         $envkey = $context.'.'.$tool;
                   7987:     }
1.976     raeburn  7988: 
1.985     raeburn  7989:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7990:          ($action ne 'reload')) {
1.1183    raeburn  7991:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7992:         $inststatus = $env{'environment.inststatus'};
                   7993:     } else {
1.1084    raeburn  7994:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7995:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7996:             $inststatus = $userenvref->{'inststatus'};
                   7997:         } else {
1.1183    raeburn  7998:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7999:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  8000:             $inststatus = $userenv{'inststatus'};
                   8001:         }
1.976     raeburn  8002:     }
                   8003: 
                   8004:     if ($toolstatus ne '') {
                   8005:         if ($toolstatus) {
                   8006:             $access = 1;
                   8007:         } else {
                   8008:             $access = 0;
                   8009:         }
                   8010:         return $access;
                   8011:     }
                   8012: 
1.1084    raeburn  8013:     my ($is_adv,%domdef);
                   8014:     if (ref($is_advref) eq 'HASH') {
                   8015:         $is_adv = $is_advref->{'is_adv'};
                   8016:     } else {
                   8017:         $is_adv = &is_advanced_user($udom,$uname);
                   8018:     }
                   8019:     if (ref($domdefref) eq 'HASH') {
                   8020:         %domdef = %{$domdefref};
                   8021:     } else {
                   8022:         %domdef = &get_domain_defaults($udom);
                   8023:     }
1.976     raeburn  8024:     if (ref($domdef{$tool}) eq 'HASH') {
                   8025:         if ($is_adv) {
                   8026:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8027:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8028:                     $access = 1;
                   8029:                 } else {
                   8030:                     $access = 0;
                   8031:                 }
                   8032:                 return $access;
                   8033:             }
                   8034:         }
                   8035:         if ($inststatus ne '') {
                   8036:             my ($hasaccess,$hasnoaccess);
                   8037:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8038:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8039:                     if ($domdef{$tool}{$affiliation}) {
                   8040:                         $hasaccess = 1;
                   8041:                     } else {
                   8042:                         $hasnoaccess = 1;
                   8043:                     }
                   8044:                 }
                   8045:             }
                   8046:             if ($hasaccess || $hasnoaccess) {
                   8047:                 if ($hasaccess) {
                   8048:                     $access = 1;
                   8049:                 } elsif ($hasnoaccess) {
                   8050:                     $access = 0; 
                   8051:                 }
                   8052:                 return $access;
                   8053:             }
                   8054:         } else {
                   8055:             if ($domdef{$tool}{'default'} ne '') {
                   8056:                 if ($domdef{$tool}{'default'}) {
                   8057:                     $access = 1;
                   8058:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8059:                     $access = 0;
                   8060:                 }
                   8061:                 return $access;
                   8062:             }
                   8063:         }
                   8064:     } else {
1.1177    raeburn  8065:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8066:             $access = 1;
                   8067:         } else {
                   8068:             $access = 0;
                   8069:         }
1.976     raeburn  8070:         return $access;
                   8071:     }
                   8072: }
                   8073: 
1.1050    raeburn  8074: sub is_course_owner {
                   8075:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8076:     if (($udom eq '') || ($uname eq '')) {
                   8077:         $udom = $env{'user.domain'};
                   8078:         $uname = $env{'user.name'};
                   8079:     }
                   8080:     unless (($udom eq '') || ($uname eq '')) {
                   8081:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8082:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8083:                 return 1;
                   8084:             } else {
                   8085:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   8086:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8087:                     return 1;
                   8088:                 }
                   8089:             }
                   8090:         }
                   8091:     }
                   8092:     return;
                   8093: }
                   8094: 
1.976     raeburn  8095: sub is_advanced_user {
                   8096:     my ($udom,$uname) = @_;
1.1085    raeburn  8097:     if ($udom ne '' && $uname ne '') {
                   8098:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8099:             if (wantarray) {
                   8100:                 return ($env{'user.adv'},$env{'user.author'});
                   8101:             } else {
                   8102:                 return $env{'user.adv'};
                   8103:             }
1.1085    raeburn  8104:         }
                   8105:     }
1.976     raeburn  8106:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8107:     my %allroles;
1.1128    raeburn  8108:     my ($is_adv,$is_author);
1.976     raeburn  8109:     foreach my $role (keys(%roleshash)) {
                   8110:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8111:         my $area = '/'.$tdomain.'/'.$trest;
                   8112:         if ($sec ne '') {
                   8113:             $area .= '/'.$sec;
                   8114:         }
                   8115:         if (($area ne '') && ($trole ne '')) {
                   8116:             my $spec=$trole.'.'.$area;
                   8117:             if ($trole =~ /^cr\//) {
                   8118:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8119:             } elsif ($trole ne 'gr') {
                   8120:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8121:             }
1.1128    raeburn  8122:             if ($trole eq 'au') {
                   8123:                 $is_author = 1;
                   8124:             }
1.976     raeburn  8125:         }
                   8126:     }
                   8127:     foreach my $role (keys(%allroles)) {
                   8128:         last if ($is_adv);
                   8129:         foreach my $item (split(/:/,$allroles{$role})) {
                   8130:             if ($item ne '') {
                   8131:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8132:                 if ($privilege eq 'adv') {
                   8133:                     $is_adv = 1;
                   8134:                     last;
                   8135:                 }
                   8136:             }
                   8137:         }
                   8138:     }
1.1128    raeburn  8139:     if (wantarray) {
                   8140:         return ($is_adv,$is_author);
                   8141:     }
1.976     raeburn  8142:     return $is_adv;
                   8143: }
1.798     raeburn  8144: 
1.1035    raeburn  8145: sub check_can_request {
1.1368    raeburn  8146:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8147:     my $canreq = 0;
1.1368    raeburn  8148:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8149:         $uname = $env{'user.name'};
                   8150:         $udom = $env{'user.domain'};
                   8151:     }
1.1035    raeburn  8152:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8153:     my @options = ('approval','validate','autolimit');
                   8154:     my $optregex = join('|',@options);
                   8155:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486    raeburn  8156:         my %willtrust;
1.1035    raeburn  8157:         foreach my $type (@{$types}) {
1.1368    raeburn  8158:             if (&usertools_access($uname,$udom,$type,undef,
                   8159:                                   'requestcourses')) {
1.1035    raeburn  8160:                 $canreq ++;
1.1036    raeburn  8161:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  8162:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8163:                 }
1.1368    raeburn  8164:                 if ($dom eq $udom) {
1.1035    raeburn  8165:                     $can_request->{$type} = 1;
                   8166:                 }
                   8167:             }
1.1368    raeburn  8168:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8169:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8170:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8171:                 if (@curr > 0) {
1.1036    raeburn  8172:                     foreach my $item (@curr) {
                   8173:                         if (ref($request_domains) eq 'HASH') {
                   8174:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8175:                             if ($otherdom ne '') {
1.1486    raeburn  8176:                                 unless (exists($willtrust{$otherdom})) {
                   8177:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
                   8178:                                 }
                   8179:                                 if ($willtrust{$otherdom}) {
                   8180:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8181:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8182:                                             push(@{$request_domains->{$type}},$otherdom);
                   8183:                                         }
                   8184:                                     } else {
1.1036    raeburn  8185:                                         push(@{$request_domains->{$type}},$otherdom);
                   8186:                                     }
                   8187:                                 }
                   8188:                             }
                   8189:                         }
                   8190:                     }
1.1368    raeburn  8191:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8192:                         $canreq ++;
1.1035    raeburn  8193:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8194:                             $can_request->{$type} = 1;
                   8195:                         }
                   8196:                     }
                   8197:                 }
                   8198:             }
                   8199:         }
                   8200:     }
                   8201:     return $canreq;
                   8202: }
                   8203: 
1.341     www      8204: # ---------------------------------------------- Custom access rule evaluation
                   8205: 
                   8206: sub customaccess {
                   8207:     my ($priv,$uri)=@_;
1.807     albertel 8208:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8209:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8210:     $udom = &LONCAPA::clean_domain($udom);
                   8211:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8212:     my $access=0;
1.800     albertel 8213:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8214: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8215: 	if ($type eq 'user') {
                   8216: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8217: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8218: 		if ($tdom) {
                   8219: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8220: 		}
1.896     albertel 8221: 		if ($tuname) {
                   8222: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8223: 		}
                   8224: 		$access=($effect eq 'allow');
                   8225: 		last;
                   8226: 	    }
                   8227: 	} else {
                   8228: 	    if ($role) {
                   8229: 		if ($role ne $urole) { next; }
                   8230: 	    }
                   8231: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8232: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8233: 		if ($tdom) {
                   8234: 		    if ($tdom ne $udom) { next; }
                   8235: 		}
                   8236: 		if ($tcrs) {
                   8237: 		    if ($tcrs ne $ucrs) { next; }
                   8238: 		}
                   8239: 		if ($tsec) {
                   8240: 		    if ($tsec ne $usec) { next; }
                   8241: 		}
                   8242: 		$access=($effect eq 'allow');
                   8243: 		last;
                   8244: 	    }
                   8245: 	    if ($realm eq '' && $role eq '') {
                   8246: 		$access=($effect eq 'allow');
                   8247: 	    }
1.402     bowersj2 8248: 	}
1.341     www      8249:     }
                   8250:     return $access;
                   8251: }
                   8252: 
1.103     harris41 8253: # ------------------------------------------------- Check for a user privilege
1.12      www      8254: 
                   8255: sub allowed {
1.1461    raeburn  8256:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8257:     my $ver_orguri=$uri;
1.439     www      8258:     $uri=&deversion($uri);
1.152     www      8259:     my $orguri=$uri;
1.52      www      8260:     $uri=&declutter($uri);
1.809     raeburn  8261: 
1.810     raeburn  8262:     if ($priv eq 'evb') {
1.1478    raeburn  8263: # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8264:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8265:             return $1;
                   8266:         } else {
                   8267:             return;
                   8268:         }
                   8269:     }
                   8270: 
1.620     albertel 8271:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8272: # Free bre access to adm and meta resources
1.1436    raeburn  8273:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8274: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8275: 	&& ($priv eq 'bre')) {
1.14      www      8276: 	return 'F';
1.159     www      8277:     }
                   8278: 
1.545     banghart 8279: # Free bre access to user's own portfolio contents
1.714     raeburn  8280:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8281:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8282: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8283:         my %setters;
1.1473    raeburn  8284:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8285:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8286:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8287:             return 'B';
                   8288:         } else {
                   8289:             return 'F';
                   8290:         }
1.545     banghart 8291:     }
                   8292: 
1.762     raeburn  8293: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8294:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8295:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8296:         if (exists($env{'request.course.id'})) {
                   8297:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8298:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8299:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8300:                 my $courseprivid=$env{'request.course.id'};
                   8301:                 $courseprivid=~s/\_/\//;
                   8302:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8303:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8304:                     return $1; 
1.762     raeburn  8305:                 } else {
                   8306:                     if ($env{'request.course.sec'}) {
                   8307:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8308:                     }
                   8309:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8310:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8311:                         return $2;
                   8312:                     }
1.714     raeburn  8313:                 }
                   8314:             }
                   8315:         }
                   8316:     }
                   8317: 
1.159     www      8318: # Free bre to public access
                   8319: 
                   8320:     if ($priv eq 'bre') {
1.1362    raeburn  8321:         my $copyright;
                   8322:         unless ($uri =~ /ext\.tool/) {
                   8323:             $copyright=&metadata($uri,'copyright');
                   8324:         }
1.620     albertel 8325: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8326:            return 'F'; 
                   8327:         }
1.238     www      8328:         if ($copyright eq 'priv') {
                   8329:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8330: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8331: 		return '';
                   8332:             }
                   8333:         }
                   8334:         if ($copyright eq 'domain') {
                   8335:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8336: 	    unless (($env{'user.domain'} eq $1) ||
                   8337:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8338: 		return '';
                   8339:             }
1.262     matthew  8340:         }
1.620     albertel 8341:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8342:             # Library role, so allow browsing of resources in this domain.
                   8343:             return 'F';
1.238     www      8344:         }
1.341     www      8345:         if ($copyright eq 'custom') {
                   8346: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8347:         }
1.14      www      8348:     }
1.264     matthew  8349:     # Domain coordinator is trying to create a course
1.620     albertel 8350:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8351:         # uri is the requested domain in this case.
                   8352:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8353:         # a role of dc for the domain in question.
1.620     albertel 8354:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8355:     }
1.29      www      8356: 
1.52      www      8357:     my $thisallowed='';
                   8358:     my $statecond=0;
                   8359:     my $courseprivid='';
                   8360: 
1.1039    raeburn  8361:     my $ownaccess;
1.1043    raeburn  8362:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8363:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8364:         if ($uri eq '') {
                   8365:             $ownaccess = 1;
                   8366:         } else {
                   8367:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8368:                 my $udom = $env{'user.domain'};
                   8369:                 my $uname = $env{'user.name'};
                   8370:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8371:                     $ownaccess = 1;
1.1040    raeburn  8372:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8373:                     unless ($uri =~ m{\.\./}) {
                   8374:                         $ownaccess = 1;
                   8375:                     }
                   8376:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8377:                     my $now = time;
                   8378:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8379:                         my $adom = $1;
                   8380:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8381:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452    raeburn  8382:                                 my ($start,$end) = split(/\./,$env{$key});
                   8383:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8384:                                     $ownaccess = 1;
                   8385:                                     last;
                   8386:                                 }
                   8387:                             }
                   8388:                         }
                   8389:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8390:                         my $adom = $1;
                   8391:                         my $aname = $2;
1.1042    raeburn  8392:                         foreach my $role ('ca','aa') { 
                   8393:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8394:                                 my ($start,$end) =
1.1452    raeburn  8395:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8396:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8397:                                     $ownaccess = 1;
                   8398:                                     last;
                   8399:                                 }
1.1039    raeburn  8400:                             }
                   8401:                         }
                   8402:                     }
                   8403:                 }
                   8404:             }
                   8405:         }
                   8406:     }
                   8407: 
1.52      www      8408: # Course
                   8409: 
1.620     albertel 8410:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8411:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8412:             $thisallowed.=$1;
                   8413:         }
1.52      www      8414:     }
1.29      www      8415: 
1.52      www      8416: # Domain
                   8417: 
1.620     albertel 8418:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8419:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8420:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8421:             $thisallowed.=$1;
                   8422:         }
1.12      www      8423:     }
1.52      www      8424: 
1.1141    raeburn  8425: # User who is not author or co-author might still be able to edit
                   8426: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8427:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8428:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8429:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8430:             $thisallowed.=$1;
                   8431:         }
                   8432:     }
                   8433: 
1.52      www      8434: # Course: uri itself is a course
1.66      www      8435:     my $courseuri=$uri;
                   8436:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8437:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8438: 
1.620     albertel 8439:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8440:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8441:         if ($priv eq 'mip') {
                   8442:             my $rem = $1;
                   8443:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8444:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8445:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8446:                 if ($cdom ne '') {
1.1410    raeburn  8447:                     my %passwdconf = &get_passwdconf($cdom);
                   8448:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8449:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8450:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8451:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8452:                                 unless (@inststatuses) {
                   8453:                                     @inststatuses = ('default');
                   8454:                                 }
                   8455:                                 foreach my $status (@inststatuses) {
                   8456:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8457:                                         $thisallowed.=$rem;
                   8458:                                     }
                   8459:                                 }
                   8460:                             }
                   8461:                         }
1.1409    raeburn  8462:                     }
                   8463:                 }
                   8464:             }
                   8465:         } else {
                   8466:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8467:                 $thisallowed.=$1;
                   8468:             }
1.1039    raeburn  8469:         }
1.12      www      8470:     }
1.29      www      8471: 
1.665     albertel 8472: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8473: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8474:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8475: 	$thisallowed='';
1.671     raeburn  8476:         my ($match)=&is_on_map($uri);
                   8477:         if ($match) {
                   8478:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8479:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8480:                 my $value = $1;
1.1461    raeburn  8481:                 my $deeplinkblock;
                   8482:                 unless ($nodeeplinkcheck) {
                   8483:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8484:                 }
1.1402    raeburn  8485:                 if ($deeplinkblock) {
                   8486:                     $thisallowed='D';
                   8487:                 } elsif ($noblockcheck) {
1.1281    raeburn  8488:                     $thisallowed.=$value;
1.1162    raeburn  8489:                 } else {
1.1424    raeburn  8490:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8491:                     if (@blockers > 0) {
                   8492:                         $thisallowed = 'B';
                   8493:                     } else {
                   8494:                         $thisallowed.=$value;
                   8495:                     }
1.1162    raeburn  8496:                 }
1.671     raeburn  8497:             }
                   8498:         } else {
1.705     albertel 8499:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8500:             if ($refuri) {
                   8501:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8502:                     $thisallowed='F';
1.671     raeburn  8503:                 } else {
                   8504:                     $refuri=&declutter($refuri);
                   8505:                     my ($match) = &is_on_map($refuri);
                   8506:                     if ($match) {
1.1461    raeburn  8507:                         my $deeplinkblock;
                   8508:                         unless ($nodeeplinkcheck) {
                   8509:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8510:                         }
1.1402    raeburn  8511:                         if ($deeplinkblock) {
                   8512:                             $thisallowed='D';
                   8513:                         } elsif ($noblockcheck) {
1.1281    raeburn  8514:                             $thisallowed='F';
1.1162    raeburn  8515:                         } else {
1.1426    raeburn  8516:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8517:                             if (@blockers > 0) {
                   8518:                                 $thisallowed = 'B';
                   8519:                             } else {
                   8520:                                 $thisallowed='F';
                   8521:                             }
1.1162    raeburn  8522:                         }
1.671     raeburn  8523:                     }
1.669     raeburn  8524:                 }
1.671     raeburn  8525:             }
                   8526:         }
1.314     www      8527:     }
1.492     albertel 8528: 
1.766     albertel 8529:     if ($priv eq 'bre'
                   8530: 	&& $thisallowed ne 'F' 
                   8531: 	&& $thisallowed ne '2'
                   8532: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8533: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8534:     }
1.1250    raeburn  8535: 
1.52      www      8536: # Full access at system, domain or course-wide level? Exit.
1.29      www      8537:     if ($thisallowed=~/F/) {
                   8538: 	return 'F';
                   8539:     }
                   8540: 
1.52      www      8541: # If this is generating or modifying users, exit with special codes
1.29      www      8542: 
1.643     www      8543:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8544: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8545: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8546: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8547: 	    unless ($auname) { return $thisallowed; }
                   8548: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8549: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8550: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8551: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8552: 	}
1.52      www      8553: 	return $thisallowed;
                   8554:     }
                   8555: #
1.103     harris41 8556: # Gathered so far: system, domain and course wide privileges
1.52      www      8557: #
                   8558: # Course: See if uri or referer is an individual resource that is part of 
                   8559: # the course
                   8560: 
1.620     albertel 8561:     if ($env{'request.course.id'}) {
1.232     www      8562: 
1.1409    raeburn  8563: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8564: 
                   8565:         if ($priv eq 'mip') {
                   8566:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8567:                 return $thisallowed;
                   8568:             } else {
                   8569:                 return '';
                   8570:             }
                   8571:         }
                   8572: 
1.620     albertel 8573:        $courseprivid=$env{'request.course.id'};
                   8574:        if ($env{'request.course.sec'}) {
                   8575:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8576:        }
                   8577:        $courseprivid=~s/\_/\//;
                   8578:        my $checkreferer=1;
1.232     www      8579:        my ($match,$cond)=&is_on_map($uri);
                   8580:        if ($match) {
                   8581:            $statecond=$cond;
1.620     albertel 8582:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8583:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8584:                my $value = $1;
                   8585:                if ($priv eq 'bre') {
1.1461    raeburn  8586:                    my $deeplinkblock;
                   8587:                    unless ($nodeeplinkcheck) {
                   8588:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8589:                    }
1.1458    raeburn  8590:                    if ($deeplinkblock) {
                   8591:                        $thisallowed = 'D';
                   8592:                    } elsif ($noblockcheck) {
1.1281    raeburn  8593:                        $thisallowed.=$value;
1.1162    raeburn  8594:                    } else {
1.1424    raeburn  8595:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8596:                        if (@blockers > 0) {
                   8597:                            $thisallowed = 'B';
                   8598:                        } else {
                   8599:                            $thisallowed.=$value;
                   8600:                        }
1.1162    raeburn  8601:                    }
                   8602:                } else {
                   8603:                    $thisallowed.=$value;
                   8604:                }
1.52      www      8605:                $checkreferer=0;
                   8606:            }
1.29      www      8607:        }
1.1424    raeburn  8608: 
1.148     www      8609:        if ($checkreferer) {
1.620     albertel 8610: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8611:             unless ($refuri) {
1.800     albertel 8612:                 foreach my $key (keys(%env)) {
                   8613: 		    if ($key=~/^httpref\..*\*/) {
                   8614: 			my $pattern=$key;
1.156     www      8615:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8616:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8617:                         $pattern=~s/\//\\\//g;
1.152     www      8618:                         if ($orguri=~/$pattern/) {
1.800     albertel 8619: 			    $refuri=$env{$key};
1.148     www      8620:                         }
                   8621:                     }
1.191     harris41 8622:                 }
1.148     www      8623:             }
1.232     www      8624: 
1.148     www      8625:          if ($refuri) { 
1.152     www      8626: 	  $refuri=&declutter($refuri);
1.232     www      8627:           my ($match,$cond)=&is_on_map($refuri);
                   8628:             if ($match) {
                   8629:               my $refstatecond=$cond;
1.620     albertel 8630:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8631:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8632:                   my $value = $1;
                   8633:                   if ($priv eq 'bre') {
1.1461    raeburn  8634:                       my $deeplinkblock;
                   8635:                       unless ($nodeeplinkcheck) {
                   8636:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8637:                       }
1.1402    raeburn  8638:                       if ($deeplinkblock) {
                   8639:                           $thisallowed = 'D';
                   8640:                       } elsif ($noblockcheck) {
1.1281    raeburn  8641:                           $thisallowed.=$value;
1.1162    raeburn  8642:                       } else {
1.1426    raeburn  8643:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8644:                           if (@blockers > 0) {
                   8645:                               $thisallowed = 'B';
                   8646:                           } else {
                   8647:                               $thisallowed.=$value;
                   8648:                           }
1.1162    raeburn  8649:                       }
                   8650:                   } else {
                   8651:                       $thisallowed.=$value;
                   8652:                   }
1.53      www      8653:                   $uri=$refuri;
                   8654:                   $statecond=$refstatecond;
1.52      www      8655:               }
                   8656:           }
1.148     www      8657:         }
1.29      www      8658:        }
1.52      www      8659:    }
1.29      www      8660: 
1.52      www      8661: #
1.103     harris41 8662: # Gathered now: all privileges that could apply, and condition number
1.52      www      8663: # 
                   8664: #
                   8665: # Full or no access?
                   8666: #
1.29      www      8667: 
1.52      www      8668:     if ($thisallowed=~/F/) {
                   8669: 	return 'F';
                   8670:     }
1.29      www      8671: 
1.52      www      8672:     unless ($thisallowed) {
                   8673:         return '';
                   8674:     }
1.29      www      8675: 
1.52      www      8676: # Restrictions exist, deal with them
                   8677: #
                   8678: #   C:according to course preferences
                   8679: #   R:according to resource settings
                   8680: #   L:unless locked
                   8681: #   X:according to user session state
                   8682: #
                   8683: 
                   8684: # Possibly locked functionality, check all courses
1.1454    raeburn  8685: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8686: # Locks might take effect only after 10 minutes cache expiration for other
1.1454    raeburn  8687: # courses, and 2 minutes for current course, in which user has st or ta role
                   8688: # which is neither expired nor a future role (unless current course).
1.52      www      8689: 
1.1454    raeburn  8690:     my ($needlockcheck,$now,$crsonly);
1.52      www      8691:     if ($thisallowed=~/L/) {
1.1454    raeburn  8692:         $now = time;
                   8693:         if ($priv eq 'bre') {
                   8694:             if ($uri ne '') {
                   8695:                 if ($orguri =~ m{^/+res/}) {
                   8696:                     if ($uri =~ m{^lib/templates/}) {
                   8697:                         if ($env{'request.course.id'}) {
                   8698:                             $crsonly = 1;
                   8699:                             $needlockcheck = 1;
                   8700:                         }
                   8701:                     } else {
                   8702:                         $needlockcheck = 1;
                   8703:                     }
                   8704:                 } elsif ($env{'request.course.id'}) {
                   8705:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8706:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8707:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8708:                         $crsonly = 1;
                   8709:                     }
                   8710:                     $needlockcheck = 1;
                   8711:                 }
                   8712:             }
                   8713:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8714:             $needlockcheck = 1;
                   8715:         }
                   8716:     }
                   8717:     if ($needlockcheck) {
1.1453    raeburn  8718:         foreach my $envkey (keys(%env)) {
1.54      www      8719:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8720:                my $courseid=$2;
                   8721:                my $roleid=$1.'.'.$2;
1.92      www      8722:                $courseid=~s/^\///;
1.1453    raeburn  8723:                unless ($env{'request.role'} eq $roleid) {
                   8724:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8725:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8726:                }
1.54      www      8727:                my $expiretime=600;
1.620     albertel 8728:                if ($env{'request.role'} eq $roleid) {
1.54      www      8729: 		  $expiretime=120;
                   8730:                }
                   8731: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8732:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8733:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8734: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8735:                }
1.620     albertel 8736:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8737:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8738: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8739:                        &log($env{'user.domain'},$env{'user.name'},
                   8740:                             $env{'user.home'},
1.57      www      8741:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8742:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8743:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8744: 		       return '';
                   8745:                    }
                   8746:                }
1.620     albertel 8747:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8748:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455    raeburn  8749: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8750:                        &log($env{'user.domain'},$env{'user.name'},
                   8751:                             $env{'user.home'},
1.57      www      8752:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8753:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8754:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8755: 		       return '';
                   8756:                    }
                   8757:                }
                   8758: 	   }
1.29      www      8759:        }
1.52      www      8760:     }
1.1424    raeburn  8761: 
1.52      www      8762: #
                   8763: # Rest of the restrictions depend on selected course
                   8764: #
                   8765: 
1.620     albertel 8766:     unless ($env{'request.course.id'}) {
1.766     albertel 8767: 	if ($thisallowed eq 'A') {
                   8768: 	    return 'A';
1.814     raeburn  8769:         } elsif ($thisallowed eq 'B') {
                   8770:             return 'B';
1.766     albertel 8771: 	} else {
                   8772: 	    return '1';
                   8773: 	}
1.52      www      8774:     }
1.29      www      8775: 
1.52      www      8776: #
                   8777: # Now user is definitely in a course
                   8778: #
1.53      www      8779: 
                   8780: 
                   8781: # Course preferences
                   8782: 
                   8783:    if ($thisallowed=~/C/) {
1.620     albertel 8784:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8785:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8786:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8787: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8788: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8789: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8790: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8791: 			$env{'request.course.id'});
                   8792: 	   }
1.237     www      8793:            return '';
                   8794:        }
                   8795: 
1.620     albertel 8796:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8797: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8798: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8799: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8800: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8801: 			$env{'request.course.id'});
                   8802: 	   }
1.54      www      8803:            return '';
                   8804:        }
1.53      www      8805:    }
                   8806: 
                   8807: # Resource preferences
                   8808: 
                   8809:    if ($thisallowed=~/R/) {
1.620     albertel 8810:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8811:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8812: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8813: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8814: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8815: 	   }
                   8816: 	   return '';
1.54      www      8817:        }
1.53      www      8818:    }
1.30      www      8819: 
1.1461    raeburn  8820: # Restricted for deeplinked session?
                   8821: 
                   8822:     if ($env{'request.deeplink.login'}) {
                   8823:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8824:             if (!$symb) { $symb=&symbread($uri,1); }
                   8825:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8826:                 return '';
                   8827:             }
                   8828:         }
                   8829:     }
                   8830: 
1.246     www      8831: # Restricted by state or randomout?
1.30      www      8832: 
1.52      www      8833:    if ($thisallowed=~/X/) {
1.620     albertel 8834:       if ($env{'acc.randomout'}) {
1.579     albertel 8835: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8836:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8837:             return ''; 
                   8838:          }
1.247     www      8839:       }
                   8840:       if (&condval($statecond)) {
1.52      www      8841: 	 return '2';
                   8842:       } else {
                   8843:          return '';
                   8844:       }
                   8845:    }
1.30      www      8846: 
1.766     albertel 8847:     if ($thisallowed eq 'A') {
                   8848: 	return 'A';
1.814     raeburn  8849:     } elsif ($thisallowed eq 'B') {
                   8850:         return 'B';
1.1402    raeburn  8851:     } elsif ($thisallowed eq 'D') {
                   8852:         return 'D';
1.766     albertel 8853:     }
1.52      www      8854:    return 'F';
1.232     www      8855: }
1.1162    raeburn  8856: 
1.1192    raeburn  8857: # ------------------------------------------- Check construction space access
                   8858: 
                   8859: sub constructaccess {
                   8860:     my ($url,$setpriv)=@_;
                   8861: 
                   8862: # We do not allow editing of previous versions of files
                   8863:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8864: 
                   8865: # Get username and domain from URL
                   8866:     my ($ownername,$ownerdomain,$ownerhome);
                   8867: 
                   8868:     ($ownerdomain,$ownername) =
1.1325    raeburn  8869:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8870: 
                   8871: # The URL does not really point to any authorspace, forget it
                   8872:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8873: 
                   8874: # Now we need to see if the user has access to the authorspace of
                   8875: # $ownername at $ownerdomain
                   8876: 
                   8877:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8878: # Real author for this?
                   8879:        $ownerhome = $env{'user.home'};
                   8880:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8881:           return ($ownername,$ownerdomain,$ownerhome);
                   8882:        }
                   8883:     } else {
                   8884: # Co-author for this?
                   8885:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8886:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8887:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8888:             return ($ownername,$ownerdomain,$ownerhome);
                   8889:         }
1.1312    raeburn  8890:         if ($env{'request.course.id'}) {
                   8891:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8892:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8893:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8894:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8895:                     return ($ownername,$ownerdomain,$ownerhome);
                   8896:                 }
                   8897:             }
                   8898:         }
1.1192    raeburn  8899:     }
                   8900: 
                   8901: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8902: # we might as well leave
                   8903:    unless ($setpriv) { return ''; }
                   8904: 
                   8905: # Backdoor access?
                   8906:     my $allowed=&allowed('eco',$ownerdomain);
                   8907: # Nope
                   8908:     unless ($allowed) { return ''; }
                   8909: # Looks like we may have access, but could be locked by the owner of the construction space
                   8910:     if ($allowed eq 'U') {
                   8911:         my %blocked=&get('environment',['domcoord.author'],
                   8912:                          $ownerdomain,$ownername);
                   8913: # Is blocked by owner
                   8914:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8915:     }
                   8916:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8917: # Grant temporary access
                   8918:         my $then=$env{'user.login.time'};
1.1209    raeburn  8919:         my $update=$env{'user.update.time'};
1.1192    raeburn  8920:         if (!$update) { $update = $then; }
                   8921:         my $refresh=$env{'user.refresh.time'};
                   8922:         if (!$refresh) { $refresh = $update; }
                   8923:         my $now = time;
                   8924:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8925:                            $now,'ca','constructaccess');
                   8926:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8927:         return($ownername,$ownerdomain,$ownerhome);
                   8928:     }
                   8929: # No business here
                   8930:     return '';
                   8931: }
                   8932: 
1.1282    raeburn  8933: # ----------------------------------------------------------- Content Blocking
                   8934: 
                   8935: {
                   8936: # Caches for faster Course Contents display where content blocking
                   8937: # is in operation (i.e., interval param set) for timed quiz.
                   8938: #
                   8939: # User for whom data are being temporarily cached.
                   8940: my $cacheduser='';
1.1424    raeburn  8941: # Course for which data are being temporarily cached.
                   8942: my $cachedcid='';
1.1282    raeburn  8943: # Cached blockers for this user (a hash of blocking items). 
                   8944: my %cachedblockers=();
                   8945: # When the data were last cached.
                   8946: my $cachedlast='';
                   8947: 
                   8948: sub load_all_blockers {
1.1427    raeburn  8949:     my ($uname,$udom)=@_;
1.1282    raeburn  8950:     if (($uname ne '') && ($udom ne '')) { 
                   8951:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  8952:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  8953:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  8954:             return;
                   8955:         }
                   8956:     }
                   8957:     $cachedlast=time;
                   8958:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  8959:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  8960:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  8961:     return;
1.1282    raeburn  8962: }
                   8963: 
1.1162    raeburn  8964: sub get_comm_blocks {
                   8965:     my ($cdom,$cnum) = @_;
                   8966:     if ($cdom eq '' || $cnum eq '') {
                   8967:         return unless ($env{'request.course.id'});
                   8968:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8969:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8970:     }
                   8971:     my %commblocks;
                   8972:     my $hashid=$cdom.'_'.$cnum;
                   8973:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8974:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8975:         %commblocks = %{$blocksref};
                   8976:     } else {
                   8977:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8978:         my $cachetime = 600;
                   8979:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8980:     }
                   8981:     return %commblocks;
                   8982: }
                   8983: 
1.1282    raeburn  8984: sub get_commblock_resources {
                   8985:     my ($blocks) = @_;
                   8986:     my %blockers = ();
                   8987:     return %blockers unless ($env{'request.course.id'});
1.1470    raeburn  8988:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8989:     if ($env{'request.course.sec'}) {
                   8990:         $courseurl .= '/'.$env{'request.course.sec'};
                   8991:     }
                   8992:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8993:     my %commblocks;
                   8994:     if (ref($blocks) eq 'HASH') {
                   8995:         %commblocks = %{$blocks};
                   8996:     } else {
                   8997:         %commblocks = &get_comm_blocks();
                   8998:     }
1.1282    raeburn  8999:     return %blockers unless (keys(%commblocks) > 0); 
                   9000:     my $navmap = Apache::lonnavmaps::navmap->new();
                   9001:     return %blockers unless (ref($navmap));
1.1162    raeburn  9002:     my $now = time;
                   9003:     foreach my $block (keys(%commblocks)) {
                   9004:         if ($block =~ /^(\d+)____(\d+)$/) {
                   9005:             my ($start,$end) = ($1,$2);
                   9006:             if ($start <= $now && $end >= $now) {
                   9007:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9008:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   9009:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  9010:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9011:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  9012:                             }
                   9013:                         }
                   9014:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  9015:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9016:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  9017:                             }
                   9018:                         }
                   9019:                     }
                   9020:                 }
                   9021:             }
                   9022:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   9023:             my $item = $1;
                   9024:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9025:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471    raeburn  9026:                     my (@interval,$mapname);
1.1282    raeburn  9027:                     my $type = 'map';
                   9028:                     if ($item eq 'course') {
                   9029:                         $type = 'course';
                   9030:                         @interval=&EXT("resource.0.interval");
                   9031:                     } else {
                   9032:                         if ($item =~ /___\d+___/) {
                   9033:                             $type = 'resource';
                   9034:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  9035:                         } else {
1.1471    raeburn  9036:                             $mapname = &deversion($item);
                   9037:                             if (ref($navmap)) {
                   9038:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9039:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9040:                             }
                   9041:                         }
1.1282    raeburn  9042:                     }
1.1310    raeburn  9043:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  9044:                         my $timelimit = $1; 
1.1282    raeburn  9045:                         my $first_access;
                   9046:                         if ($type eq 'resource') {
                   9047:                             $first_access=&get_first_access($interval[1],$item);
                   9048:                         } elsif ($type eq 'map') {
                   9049:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9050:                         } else {
                   9051:                             $first_access=&get_first_access($interval[1]);
                   9052:                         }
                   9053:                         if ($first_access) {
1.1292    raeburn  9054:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  9055:                             if ($timesup > $now) {
                   9056:                                 my $activeblock;
1.1471    raeburn  9057:                                 if ($type eq 'resource') {
                   9058:                                     if (ref($navmap)) {
                   9059:                                         my $res = $navmap->getBySymb($item);
                   9060:                                         if ($res->answerable()) {
                   9061:                                             $activeblock = 1;
                   9062:                                         }
                   9063:                                     }
                   9064:                                 } elsif ($type eq 'map') {
                   9065:                                     my $mapsymb = &symbread($mapname,1);
                   9066:                                     if (($mapsymb) && (ref($navmap))) {
                   9067:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9068:                                         if (ref($mapres)) {
                   9069:                                             my $first = $mapres->map_start();
                   9070:                                             my $finish = $mapres->map_finish();
                   9071:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9072:                                             if (ref($it)) {
                   9073:                                                 my $res;
                   9074:                                                 while ($res = $it->next(undef,1)) {
                   9075:                                                     next unless (ref($res));
                   9076:                                                     my $symb = $res->symb();
                   9077:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9078:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9079:                                                     if ($interval[1] eq 'map') {
                   9080:                                                         if ($res->answerable()) {
                   9081:                                                             $activeblock = 1;
                   9082:                                                             last;
                   9083:                                                         }
                   9084:                                                     }
                   9085:                                                 }
                   9086:                                             }
                   9087:                                         }
1.1282    raeburn  9088:                                     }
                   9089:                                 }
                   9090:                                 if ($activeblock) {
                   9091:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9092:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9093:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9094:                                          }
                   9095:                                     }
                   9096:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9097:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9098:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9099:                                         }
1.1162    raeburn  9100:                                     }
                   9101:                                 }
                   9102:                             }
                   9103:                         }
                   9104:                     }
                   9105:                 }
                   9106:             }
                   9107:         }
                   9108:     }
1.1282    raeburn  9109:     return %blockers;
1.1162    raeburn  9110: }
                   9111: 
1.1282    raeburn  9112: sub has_comm_blocking {
1.1427    raeburn  9113:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  9114:     my @blockers;
                   9115:     return unless ($env{'request.course.id'});
                   9116:     return unless ($priv eq 'bre');
                   9117:     return if ($env{'request.state'} eq 'construct');
1.1470    raeburn  9118:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9119:     if ($env{'request.course.sec'}) {
                   9120:         $courseurl .= '/'.$env{'request.course.sec'};
                   9121:     }
                   9122:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427    raeburn  9123:     my %blockinfo;
                   9124:     if (ref($blocks) eq 'HASH') {
                   9125:         %blockinfo = &get_commblock_resources($blocks);
                   9126:     } else {
                   9127:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9128:         %blockinfo = %cachedblockers;
                   9129:     }
                   9130:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  9131:     my (%possibles,@symbs);
                   9132:     if (!$symb) {
1.1427    raeburn  9133:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9134:     }
1.1282    raeburn  9135:     if ($symb) {
                   9136:         @symbs = ($symb);
                   9137:     } elsif (keys(%possibles)) { 
                   9138:         @symbs = keys(%possibles);
                   9139:     }
                   9140:     my $noblock;
                   9141:     foreach my $symb (@symbs) {
                   9142:         last if ($noblock);
                   9143:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  9144:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  9145:             if ($block =~ /^firstaccess____(.+)$/) {
                   9146:                 my $item = $1;
1.1424    raeburn  9147:                 unless ($blocked) {
                   9148:                     if (($item eq $map) || ($item eq $symb)) {
                   9149:                         $noblock = 1;
                   9150:                         last;
                   9151:                     }
1.1282    raeburn  9152:                 }
                   9153:             }
1.1427    raeburn  9154:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9155:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9156:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  9157:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9158:                             push(@blockers,$block);
                   9159:                         }
                   9160:                     }
                   9161:                 }
1.1427    raeburn  9162:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9163:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  9164:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9165:                             push(@blockers,$block);
                   9166:                         }
1.1282    raeburn  9167:                     }
                   9168:                 }
1.1162    raeburn  9169:             }
                   9170:         }
                   9171:     }
1.1424    raeburn  9172:     unless ($noblock) { 
                   9173:         return @blockers;
                   9174:     }
                   9175:     return;
1.1282    raeburn  9176: }
1.1162    raeburn  9177: }
                   9178: 
1.1402    raeburn  9179: sub deeplink_check {
                   9180:     my ($priv,$symb,$uri) = @_;
                   9181:     return unless ($env{'request.course.id'});
                   9182:     return unless ($priv eq 'bre');
                   9183:     return if ($env{'request.state'} eq 'construct');
                   9184:     return if ($env{'request.role.adv'});
                   9185:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9186:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9187:     my (%possibles,@symbs);
                   9188:     if (!$symb) {
                   9189:         $symb = &symbread($uri,1,1,1,\%possibles);
                   9190:     }
                   9191:     if ($symb) {
                   9192:         @symbs = ($symb);
                   9193:     } elsif (keys(%possibles)) {
                   9194:         @symbs = keys(%possibles);
                   9195:     }
                   9196: 
1.1461    raeburn  9197:     my ($deeplink_symb,$allow);
                   9198:     if ($env{'request.deeplink.login'}) {
                   9199:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402    raeburn  9200:     }
                   9201:     foreach my $symb (@symbs) {
                   9202:         last if ($allow);
                   9203:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9204:         if ($deeplink eq '') {
                   9205:             $allow = 1;
                   9206:         } else {
1.1463    raeburn  9207:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9208:             if ($state ne 'only') {
1.1402    raeburn  9209:                 $allow = 1;
1.1463    raeburn  9210:             } else {
                   9211:                 my $check_deeplink_entry;
                   9212:                 if ($protect ne 'none') {
                   9213:                     my ($acctype,$item) = split(/:/,$protect);
                   9214:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9215:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9216:                             $check_deeplink_entry = 1
                   9217:                         }
                   9218:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9219:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9220:                             $check_deeplink_entry = 1;
                   9221:                         }
                   9222:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9223:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9224:                             $check_deeplink_entry = 1;
                   9225:                         }
                   9226:                     }
                   9227:                 }
                   9228:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402    raeburn  9229:                     if ($scope eq 'res') {
1.1461    raeburn  9230:                         if ($symb eq $deeplink_symb) {
1.1402    raeburn  9231:                             $allow = 1;
                   9232:                         }
1.1459    raeburn  9233:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463    raeburn  9234:                         my ($map_from_symb,$map_from_login);
1.1461    raeburn  9235:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9236:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9237:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9238:                         } else {
                   9239:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9240:                         }
1.1459    raeburn  9241:                         if (($map_from_symb) && ($map_from_login)) {
                   9242:                             if ($map_from_symb eq $map_from_login) {
                   9243:                                 $allow = 1;
                   9244:                             } elsif ($scope eq 'rec') {
                   9245:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9246:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9247:                                     $allow = 1;
                   9248:                                 }
                   9249:                             }
                   9250:                         }
1.1402    raeburn  9251:                     }
                   9252:                 }
                   9253:             }
                   9254:         }
                   9255:     }
                   9256:     return if ($allow);
                   9257:     return 1;
                   9258: }
                   9259: 
1.1282    raeburn  9260: # -------------------------------- Deversion and split uri into path an filename   
                   9261: 
1.1133    foxr     9262: #
1.1282    raeburn  9263: #   Removes the version from a URI and
1.1133    foxr     9264: #   splits it in to its filename and path to the filename.
                   9265: #   Seems like File::Basename could have done this more clearly.
                   9266: #   Parameters:
                   9267: #      $uri   - input URI
                   9268: #   Returns:
                   9269: #     Two element list consisting of 
                   9270: #     $pathname  - the URI up to and excluding the trailing /
                   9271: #     $filename  - The part of the URI following the last /
                   9272: #  NOTE:
                   9273: #    Another realization of this is simply:
                   9274: #    use File::Basename;
                   9275: #    ...
                   9276: #    $uri = shift;
                   9277: #    $filename = basename($uri);
                   9278: #    $path     = dirname($uri);
                   9279: #    return ($filename, $path);
                   9280: #
                   9281: #     The implementation below is probably faster however.
                   9282: #
1.710     albertel 9283: sub split_uri_for_cond {
                   9284:     my $uri=&deversion(&declutter(shift));
                   9285:     my @uriparts=split(/\//,$uri);
                   9286:     my $filename=pop(@uriparts);
                   9287:     my $pathname=join('/',@uriparts);
                   9288:     return ($pathname,$filename);
                   9289: }
1.232     www      9290: # --------------------------------------------------- Is a resource on the map?
                   9291: 
                   9292: sub is_on_map {
1.710     albertel 9293:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9294:     #Trying to find the conditional for the file
1.620     albertel 9295:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9296: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9297:     if ($match) {
1.289     bowersj2 9298: 	return (1,$1);
                   9299:     } else {
1.434     www      9300: 	return (0,0);
1.289     bowersj2 9301:     }
1.12      www      9302: }
                   9303: 
1.427     www      9304: # --------------------------------------------------------- Get symb from alias
                   9305: 
                   9306: sub get_symb_from_alias {
                   9307:     my $symb=shift;
                   9308:     my ($map,$resid,$url)=&decode_symb($symb);
                   9309: # Already is a symb
                   9310:     if ($url) { return $symb; }
                   9311: # Must be an alias
                   9312:     my $aliassymb='';
                   9313:     my %bighash;
1.620     albertel 9314:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9315:                             &GDBM_READER(),0640)) {
                   9316:         my $rid=$bighash{'mapalias_'.$symb};
                   9317: 	if ($rid) {
                   9318: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9319: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9320: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9321: 	}
                   9322:         untie %bighash;
                   9323:     }
                   9324:     return $aliassymb;
                   9325: }
                   9326: 
1.12      www      9327: # ----------------------------------------------------------------- Define Role
                   9328: 
                   9329: sub definerole {
                   9330:   if (allowed('mcr','/')) {
1.1326    raeburn  9331:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9332:     foreach my $role (split(':',$sysrole)) {
                   9333: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9334:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9335:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9336: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9337:                return "refused:s:$crole&$cqual"; 
                   9338:             }
                   9339:         }
1.191     harris41 9340:     }
1.800     albertel 9341:     foreach my $role (split(':',$domrole)) {
                   9342: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9343:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9344:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9345: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9346:                return "refused:d:$crole&$cqual"; 
                   9347:             }
                   9348:         }
1.191     harris41 9349:     }
1.800     albertel 9350:     foreach my $role (split(':',$courole)) {
                   9351: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9352:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9353:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9354: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9355:                return "refused:c:$crole&$cqual"; 
                   9356:             }
                   9357:         }
1.191     harris41 9358:     }
1.1326    raeburn  9359:     my $uhome;
                   9360:     if (($uname ne '') && ($udom ne '')) {
                   9361:         $uhome = &homeserver($uname,$udom);
                   9362:         return $uhome if ($uhome eq 'no_host');
                   9363:     } else {
                   9364:         $uname = $env{'user.name'};
                   9365:         $udom = $env{'user.domain'};
                   9366:         $uhome = $env{'user.home'};
                   9367:     }
1.620     albertel 9368:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9369:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9370:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9371:     return reply($command,$uhome);
1.12      www      9372:   } else {
                   9373:     return 'refused';
                   9374:   }
1.105     harris41 9375: }
                   9376: 
                   9377: # ---------------- Make a metadata query against the network of library servers
                   9378: 
                   9379: sub metadata_query {
1.1237    raeburn  9380:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9381:     my %rhash;
1.845     albertel 9382:     my %libserv = &all_library();
1.244     matthew  9383:     my @server_list = (defined($server_array) ? @$server_array
                   9384:                                               : keys(%libserv) );
                   9385:     for my $server (@server_list) {
1.1237    raeburn  9386:         my $domains = ''; 
                   9387:         if (ref($domains_hash) eq 'HASH') {
                   9388:             $domains = $domains_hash->{$server}; 
                   9389:         }
1.118     harris41 9390: 	unless ($custom or $customshow) {
1.1237    raeburn  9391: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9392: 	    $rhash{$server}=$reply;
                   9393: 	}
                   9394: 	else {
                   9395: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9396: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9397: 			     $server);
                   9398: 	    $rhash{$server}=$reply;
                   9399: 	}
1.112     harris41 9400:     }
1.118     harris41 9401:     return \%rhash;
1.240     www      9402: }
                   9403: 
                   9404: # ----------------------------------------- Send log queries and wait for reply
                   9405: 
                   9406: sub log_query {
                   9407:     my ($uname,$udom,$query,%filters)=@_;
                   9408:     my $uhome=&homeserver($uname,$udom);
                   9409:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9410:     my $uhost=&hostname($uhome);
1.800     albertel 9411:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9412:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9413:                        $uhome);
1.479     albertel 9414:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9415:     return get_query_reply($queryid);
                   9416: }
                   9417: 
1.818     raeburn  9418: # -------------------------- Update MySQL table for portfolio file
                   9419: 
                   9420: sub update_portfolio_table {
1.821     raeburn  9421:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9422:     if ($group ne '') {
                   9423:         $file_name =~s /^\Q$group\E//;
                   9424:     }
1.818     raeburn  9425:     my $homeserver = &homeserver($uname,$udom);
                   9426:     my $queryid=
1.821     raeburn  9427:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9428:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9429:     my $reply = &get_query_reply($queryid);
                   9430:     return $reply;
                   9431: }
                   9432: 
1.899     raeburn  9433: # -------------------------- Update MySQL allusers table
                   9434: 
                   9435: sub update_allusers_table {
                   9436:     my ($uname,$udom,$names) = @_;
                   9437:     my $homeserver = &homeserver($uname,$udom);
                   9438:     my $queryid=
                   9439:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9440:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9441:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9442:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9443:                'generation='.&escape($names->{'generation'}).'%%'.
                   9444:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9445:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9446:     return;
1.899     raeburn  9447: }
                   9448: 
1.508     raeburn  9449: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9450: 
                   9451: sub fetch_enrollment_query {
1.511     raeburn  9452:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9453:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9454:     my $maxtries = 1;
1.508     raeburn  9455:     if ($context eq 'automated') {
                   9456:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9457:         $sleep = 2;
                   9458:         $loopmax = 100;
1.547     raeburn  9459:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9460:     } else {
                   9461:         $homeserver = &homeserver($cnum,$dom);
                   9462:     }
1.838     albertel 9463:     my $host=&hostname($homeserver);
1.506     raeburn  9464:     my $cmd = '';
1.1000    raeburn  9465:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9466:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9467:     }
                   9468:     $cmd =~ s/%%$//;
                   9469:     $cmd = &escape($cmd);
                   9470:     my $query = 'fetchenrollment';
1.620     albertel 9471:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9472:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9473:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9474:         return 'error: '.$queryid;
                   9475:     }
1.1317    raeburn  9476:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9477:     my $tries = 1;
                   9478:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9479:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9480:         $tries ++;
                   9481:     }
1.526     raeburn  9482:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9483:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9484:     } else {
1.901     albertel 9485:         my @responses = split(/:/,$reply);
1.1322    raeburn  9486:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9487:             foreach my $line (@responses) {
                   9488:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9489:                 $$replyref{$key} = $value;
                   9490:             }
                   9491:         } else {
1.1117    foxr     9492:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9493:             foreach my $line (@responses) {
                   9494:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9495:                 $$replyref{$key} = $value;
                   9496:                 if ($value > 0) {
1.800     albertel 9497:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9498:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9499:                         my $destname = $pathname.'/'.$filename;
                   9500:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9501:                         if ($xml_classlist =~ /^error/) {
                   9502:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9503:                         } else {
1.1359    raeburn  9504:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9505:                                 print FILE &unescape($xml_classlist);
                   9506:                                 close(FILE);
1.526     raeburn  9507:                             } else {
                   9508:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9509:                             }
                   9510:                         }
                   9511:                     }
                   9512:                 }
                   9513:             }
                   9514:         }
                   9515:         return 'ok';
                   9516:     }
                   9517:     return 'error';
                   9518: }
                   9519: 
1.242     www      9520: sub get_query_reply {
1.1471    raeburn  9521:     my ($queryid,$sleep,$loopmax) = @_;
1.1317    raeburn  9522:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9523:         $sleep = 0.2;
                   9524:     }
                   9525:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9526:         $loopmax = 100;
                   9527:     }
1.1117    foxr     9528:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9529:     my $reply='';
1.1317    raeburn  9530:     for (1..$loopmax) {
                   9531: 	sleep($sleep);
1.240     www      9532:         if (-e $replyfile.'.end') {
1.1359    raeburn  9533: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9534: 		$reply = join('',<$fh>);
                   9535: 		close($fh);
1.240     www      9536: 	   } else { return 'error: reply_file_error'; }
1.242     www      9537:            return &unescape($reply);
                   9538: 	}
1.240     www      9539:     }
1.242     www      9540:     return 'timeout:'.$queryid;
1.240     www      9541: }
                   9542: 
                   9543: sub courselog_query {
1.241     www      9544: #
                   9545: # possible filters:
                   9546: # url: url or symb
                   9547: # username
                   9548: # domain
                   9549: # action: view, submit, grade
                   9550: # start: timestamp
                   9551: # end: timestamp
                   9552: #
1.240     www      9553:     my (%filters)=@_;
1.620     albertel 9554:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9555:     if ($filters{'url'}) {
                   9556: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9557:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9558:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9559:     }
1.620     albertel 9560:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9561:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9562:     return &log_query($cname,$cdom,'courselog',%filters);
                   9563: }
                   9564: 
                   9565: sub userlog_query {
1.858     raeburn  9566: #
                   9567: # possible filters:
                   9568: # action: log check role
                   9569: # start: timestamp
                   9570: # end: timestamp
                   9571: #
1.240     www      9572:     my ($uname,$udom,%filters)=@_;
                   9573:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9574: }
                   9575: 
1.506     raeburn  9576: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9577: 
                   9578: sub auto_run {
1.508     raeburn  9579:     my ($cnum,$cdom) = @_;
1.876     raeburn  9580:     my $response = 0;
                   9581:     my $settings;
                   9582:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9583:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9584:         $settings = $domconfig{'autoenroll'};
                   9585:         if ($settings->{'run'} eq '1') {
                   9586:             $response = 1;
                   9587:         }
                   9588:     } else {
1.934     raeburn  9589:         my $homeserver;
                   9590:         if (&is_course($cdom,$cnum)) {
                   9591:             $homeserver = &homeserver($cnum,$cdom);
                   9592:         } else {
                   9593:             $homeserver = &domain($cdom,'primary');
                   9594:         }
                   9595:         if ($homeserver ne 'no_host') {
                   9596:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9597:         }
1.876     raeburn  9598:     }
1.506     raeburn  9599:     return $response;
                   9600: }
1.776     albertel 9601: 
1.506     raeburn  9602: sub auto_get_sections {
1.508     raeburn  9603:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9604:     my $homeserver;
                   9605:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9606:         $homeserver = &homeserver($cnum,$cdom);
                   9607:     }
                   9608:     if (!defined($homeserver)) { 
                   9609:         if ($cdom =~ /^$match_domain$/) {
                   9610:             $homeserver = &domain($cdom,'primary');
                   9611:         }
                   9612:     }
                   9613:     my @secs;
                   9614:     if (defined($homeserver)) {
                   9615:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9616:         unless ($response eq 'refused') {
                   9617:             @secs = split(/:/,$response);
                   9618:         }
1.506     raeburn  9619:     }
                   9620:     return @secs;
                   9621: }
1.776     albertel 9622: 
1.506     raeburn  9623: sub auto_new_course {
1.1099    raeburn  9624:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9625:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9626:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9627:     return $response;
                   9628: }
1.776     albertel 9629: 
1.506     raeburn  9630: sub auto_validate_courseID {
1.508     raeburn  9631:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9632:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9633:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9634:     return $response;
                   9635: }
1.776     albertel 9636: 
1.1007    raeburn  9637: sub auto_validate_instcode {
1.1020    raeburn  9638:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9639:     my ($homeserver,$response);
                   9640:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9641:         $homeserver = &homeserver($cnum,$cdom);
                   9642:     }
                   9643:     if (!defined($homeserver)) {
                   9644:         if ($cdom =~ /^$match_domain$/) {
                   9645:             $homeserver = &domain($cdom,'primary');
                   9646:         }
                   9647:     }
1.1065    raeburn  9648:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9649:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9650:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9651:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9652: }
                   9653: 
1.1444    raeburn  9654: sub auto_validate_inst_crosslist {
                   9655:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9656:     my ($homeserver,$response);
                   9657:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9658:         $homeserver = &homeserver($cnum,$cdom);
                   9659:     }
                   9660:     if (!defined($homeserver)) {
                   9661:         if ($cdom =~ /^$match_domain$/) {
                   9662:             $homeserver = &domain($cdom,'primary');
                   9663:         }
                   9664:     }
                   9665:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9666:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9667:                          &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445    raeburn  9668:                          &escape($coowner),$homeserver);
1.1444    raeburn  9669:     }
                   9670:     return $response;
                   9671: }
                   9672: 
1.506     raeburn  9673: sub auto_create_password {
1.873     raeburn  9674:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9675:     my ($homeserver,$response);
1.506     raeburn  9676:     my $create_passwd = 0;
                   9677:     my $authchk = '';
1.873     raeburn  9678:     if ($udom =~ /^$match_domain$/) {
                   9679:         $homeserver = &domain($udom,'primary');
                   9680:     }
                   9681:     if ($homeserver eq '') {
                   9682:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9683:             $homeserver = &homeserver($cnum,$cdom);
                   9684:         }
                   9685:     }
                   9686:     if ($homeserver eq '') {
                   9687:         $authchk = 'nodomain';
1.506     raeburn  9688:     } else {
1.873     raeburn  9689:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9690:         if ($response eq 'refused') {
                   9691:             $authchk = 'refused';
                   9692:         } else {
1.901     albertel 9693:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9694:         }
1.506     raeburn  9695:     }
                   9696:     return ($authparam,$create_passwd,$authchk);
                   9697: }
                   9698: 
1.706     raeburn  9699: sub auto_photo_permission {
                   9700:     my ($cnum,$cdom,$students) = @_;
                   9701:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9702:     my ($outcome,$perm_reqd,$conditions) = 
                   9703: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9704:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9705: 	return (undef,undef);
                   9706:     }
1.706     raeburn  9707:     return ($outcome,$perm_reqd,$conditions);
                   9708: }
                   9709: 
                   9710: sub auto_checkphotos {
                   9711:     my ($uname,$udom,$pid) = @_;
                   9712:     my $homeserver = &homeserver($uname,$udom);
                   9713:     my ($result,$resulttype);
                   9714:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9715: 				   &escape($uname).':'.&escape($pid),
                   9716: 				   $homeserver));
1.709     albertel 9717:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9718: 	return (undef,undef);
                   9719:     }
1.706     raeburn  9720:     if ($outcome) {
                   9721:         ($result,$resulttype) = split(/:/,$outcome);
                   9722:     } 
                   9723:     return ($result,$resulttype);
                   9724: }
                   9725: 
                   9726: sub auto_photochoice {
                   9727:     my ($cnum,$cdom) = @_;
                   9728:     my $homeserver = &homeserver($cnum,$cdom);
                   9729:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9730: 						       &escape($cdom),
                   9731: 						       $homeserver)));
1.709     albertel 9732:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9733: 	return (undef,undef);
                   9734:     }
1.706     raeburn  9735:     return ($update,$comment);
                   9736: }
                   9737: 
                   9738: sub auto_photoupdate {
                   9739:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9740:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9741:     my $host=&hostname($homeserver);
1.706     raeburn  9742:     my $cmd = '';
                   9743:     my $maxtries = 1;
1.800     albertel 9744:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9745:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9746:     }
                   9747:     $cmd =~ s/%%$//;
                   9748:     $cmd = &escape($cmd);
                   9749:     my $query = 'institutionalphotos';
                   9750:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9751:     unless ($queryid=~/^\Q$host\E\_/) {
                   9752:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9753:         return 'error: '.$queryid;
                   9754:     }
                   9755:     my $reply = &get_query_reply($queryid);
                   9756:     my $tries = 1;
                   9757:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9758:         $reply = &get_query_reply($queryid);
                   9759:         $tries ++;
                   9760:     }
                   9761:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9762:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9763:     } else {
                   9764:         my @responses = split(/:/,$reply);
                   9765:         my $outcome = shift(@responses); 
                   9766:         foreach my $item (@responses) {
                   9767:             my ($key,$value) = split(/=/,$item);
                   9768:             $$photo{$key} = $value;
                   9769:         }
                   9770:         return $outcome;
                   9771:     }
                   9772:     return 'error';
                   9773: }
                   9774: 
1.521     raeburn  9775: sub auto_instcode_format {
1.793     albertel 9776:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9777: 	$cat_order) = @_;
1.521     raeburn  9778:     my $courses = '';
1.772     raeburn  9779:     my @homeservers;
1.521     raeburn  9780:     if ($caller eq 'global') {
1.841     albertel 9781: 	my %servers = &get_servers($codedom,'library');
                   9782: 	foreach my $tryserver (keys(%servers)) {
                   9783: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9784: 		push(@homeservers,$tryserver);
                   9785: 	    }
1.584     raeburn  9786:         }
1.1022    raeburn  9787:     } elsif ($caller eq 'requests') {
                   9788:         if ($codedom =~ /^$match_domain$/) {
                   9789:             my $chome = &domain($codedom,'primary');
                   9790:             unless ($chome eq 'no_host') {
                   9791:                 push(@homeservers,$chome);
                   9792:             }
                   9793:         }
1.521     raeburn  9794:     } else {
1.772     raeburn  9795:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9796:     }
1.793     albertel 9797:     foreach my $code (keys(%{$instcodes})) {
                   9798:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9799:     }
                   9800:     chop($courses);
1.772     raeburn  9801:     my $ok_response = 0;
                   9802:     my $response;
                   9803:     while (@homeservers > 0 && $ok_response == 0) {
                   9804:         my $server = shift(@homeservers); 
                   9805:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9806:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9807:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9808: 		split(/:/,$response);
1.772     raeburn  9809:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9810:             push(@{$codetitles},&str2array($codetitles_str));
                   9811:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9812:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9813:             $ok_response = 1;
                   9814:         }
                   9815:     }
                   9816:     if ($ok_response) {
1.521     raeburn  9817:         return 'ok';
1.772     raeburn  9818:     } else {
                   9819:         return $response;
1.521     raeburn  9820:     }
                   9821: }
                   9822: 
1.792     raeburn  9823: sub auto_instcode_defaults {
                   9824:     my ($domain,$returnhash,$code_order) = @_;
                   9825:     my @homeservers;
1.841     albertel 9826: 
                   9827:     my %servers = &get_servers($domain,'library');
                   9828:     foreach my $tryserver (keys(%servers)) {
                   9829: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9830: 	    push(@homeservers,$tryserver);
                   9831: 	}
1.792     raeburn  9832:     }
1.841     albertel 9833: 
1.792     raeburn  9834:     my $response;
1.841     albertel 9835:     foreach my $server (@homeservers) {
1.792     raeburn  9836:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9837:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9838: 	
                   9839: 	foreach my $pair (split(/\&/,$response)) {
                   9840: 	    my ($name,$value)=split(/\=/,$pair);
                   9841: 	    if ($name eq 'code_order') {
                   9842: 		@{$code_order} = split(/\&/,&unescape($value));
                   9843: 	    } else {
                   9844: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9845: 	    }
                   9846: 	}
                   9847: 	return 'ok';
1.792     raeburn  9848:     }
1.841     albertel 9849: 
                   9850:     return $response;
1.1003    raeburn  9851: }
                   9852: 
                   9853: sub auto_possible_instcodes {
1.1007    raeburn  9854:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9855:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9856:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9857:         return;
                   9858:     }
1.1003    raeburn  9859:     my (@homeservers,$uhome);
                   9860:     if (defined(&domain($domain,'primary'))) {
                   9861:         $uhome=&domain($domain,'primary');
                   9862:         push(@homeservers,&domain($domain,'primary'));
                   9863:     } else {
                   9864:         my %servers = &get_servers($domain,'library');
                   9865:         foreach my $tryserver (keys(%servers)) {
                   9866:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9867:                 push(@homeservers,$tryserver);
                   9868:             }
                   9869:         }
                   9870:     }
                   9871:     my $response;
                   9872:     foreach my $server (@homeservers) {
                   9873:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9874:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9875:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9876:             split(':',$response);
                   9877:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9878:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9879:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9880:             my ($name,$value)=split('=',$item);
                   9881:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9882:         }
                   9883:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9884:             my ($name,$value)=split('=',$item);
                   9885:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9886:         }
                   9887:         return 'ok';
                   9888:     }
                   9889:     return $response;
                   9890: }
1.792     raeburn  9891: 
1.1010    raeburn  9892: sub auto_courserequest_checks {
                   9893:     my ($dom) = @_;
1.1020    raeburn  9894:     my ($homeserver,%validations);
                   9895:     if ($dom =~ /^$match_domain$/) {
                   9896:         $homeserver = &domain($dom,'primary');
                   9897:     }
                   9898:     unless ($homeserver eq 'no_host') {
                   9899:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9900:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9901:             my @items = split(/&/,$response);
                   9902:             foreach my $item (@items) {
                   9903:                 my ($key,$value) = split('=',$item);
                   9904:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9905:             }
                   9906:         }
                   9907:     }
1.1010    raeburn  9908:     return %validations; 
                   9909: }
                   9910: 
1.1020    raeburn  9911: sub auto_courserequest_validation {
1.1255    raeburn  9912:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9913:     my ($homeserver,$response);
                   9914:     if ($dom =~ /^$match_domain$/) {
                   9915:         $homeserver = &domain($dom,'primary');
                   9916:     }
1.1255    raeburn  9917:     unless ($homeserver eq 'no_host') {
                   9918:         my $customdata;
                   9919:         if (ref($custominfo) eq 'HASH') {
                   9920:             $customdata = &freeze_escape($custominfo);
                   9921:         }
1.1020    raeburn  9922:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9923:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9924:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9925:                                     $customdata,$homeserver));
1.1020    raeburn  9926:     }
                   9927:     return $response;
                   9928: }
                   9929: 
1.777     albertel 9930: sub auto_validate_class_sec {
1.918     raeburn  9931:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9932:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9933:     my $ownerlist;
                   9934:     if (ref($owners) eq 'ARRAY') {
                   9935:         $ownerlist = join(',',@{$owners});
                   9936:     } else {
                   9937:         $ownerlist = $owners;
                   9938:     }
1.773     raeburn  9939:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9940:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9941:     return $response;
                   9942: }
                   9943: 
1.1460    raeburn  9944: sub auto_instsec_reformat {
                   9945:     my ($cdom,$action,$instsecref) = @_;
                   9946:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9947:     my @homeservers;
                   9948:     if (defined(&domain($cdom,'primary'))) {
                   9949:         push(@homeservers,&domain($cdom,'primary'));
                   9950:     } else {
                   9951:         my %servers = &get_servers($cdom,'library');
                   9952:         foreach my $tryserver (keys(%servers)) {
                   9953:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9954:                 push(@homeservers,$tryserver);
                   9955:             }
                   9956:         }
                   9957:     }
                   9958:     my $response;
                   9959:     my %reformatted = %{$instsecref};
                   9960:     foreach my $server (@homeservers) {
                   9961:         if (ref($instsecref) eq 'HASH') {
                   9962:             my $info = &freeze_escape($instsecref);
                   9963:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9964:                                 $action.':'.$info,$server);
                   9965:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9966:             my @items = split(/&/,$response);
                   9967:             foreach my $item (@items) {
                   9968:                 my ($key,$value) = split(/=/,$item);
                   9969:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9970:             }
                   9971:         }
                   9972:     }
                   9973:     return %reformatted;
                   9974: }
                   9975: 
1.1367    raeburn  9976: sub auto_validate_instclasses {
                   9977:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9978:     my ($homeserver,%validations);
                   9979:     $homeserver = &homeserver($cnum,$cdom);
                   9980:     unless ($homeserver eq 'no_host') {
                   9981:         my $ownerlist;
                   9982:         if (ref($owners) eq 'ARRAY') {
                   9983:             $ownerlist = join(',',@{$owners});
                   9984:         } else {
                   9985:             $ownerlist = $owners;
                   9986:         }
                   9987:         if (ref($classesref) eq 'HASH') {
                   9988:             my $classes = &freeze_escape($classesref);
                   9989:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9990:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9991:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9992:                 my @items = split(/&/,$response);
                   9993:                 foreach my $item (@items) {
                   9994:                     my ($key,$value) = split('=',$item);
                   9995:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9996:                 }
                   9997:             }
                   9998:         }
                   9999:     }
                   10000:     return %validations;
                   10001: }
                   10002: 
1.1248    raeburn  10003: sub auto_crsreq_update {
                   10004:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  10005:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  10006:     my ($homeserver,%crsreqresponse);
                   10007:     if ($cdom =~ /^$match_domain$/) {
                   10008:         $homeserver = &domain($cdom,'primary');
                   10009:     }
                   10010:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10011:         my $info;
                   10012:         if (ref($inbound) eq 'HASH') {
                   10013:             $info = &freeze_escape($inbound);
                   10014:         }
                   10015:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   10016:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   10017:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  10018:                             &escape($title).':'.&escape($code).':'.
                   10019:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   10020:                             $homeserver);
1.1248    raeburn  10021:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10022:             my @items = split(/&/,$response);
                   10023:             foreach my $item (@items) {
                   10024:                 my ($key,$value) = split('=',$item);
                   10025:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   10026:             }
                   10027:         }
                   10028:     }
                   10029:     return \%crsreqresponse;
                   10030: }
                   10031: 
1.1305    raeburn  10032: sub auto_export_grades {
1.1309    raeburn  10033:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   10034:     my ($homeserver,%exportresponse);
                   10035:     if ($cdom =~ /^$match_domain$/) {
                   10036:         $homeserver = &domain($cdom,'primary');
                   10037:     }
                   10038:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10039:         my $info;
                   10040:         if (ref($inforef) eq 'HASH') {
                   10041:             $info = &freeze_escape($inforef);
                   10042:         }
                   10043:         if (ref($gradesref) eq 'HASH') {
                   10044:             my $grades = &freeze_escape($gradesref);
                   10045:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10046:                                 $info.':'.$grades,$homeserver);
                   10047:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10048:                 my @items = split(/&/,$response);
                   10049:                 foreach my $item (@items) {
                   10050:                     my ($key,$value) = split('=',$item);
                   10051:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10052:                 }
                   10053:             }
                   10054:         }
                   10055:     }
                   10056:     return \%exportresponse;
1.1305    raeburn  10057: }
                   10058: 
1.1287    raeburn  10059: sub check_instcode_cloning {
                   10060:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10061:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10062:         return;
                   10063:     }
                   10064:     my $canclone;
                   10065:     if (@{$code_order} > 0) {
                   10066:         my $instcoderegexp ='^';
                   10067:         my @clonecodes = split(/\&/,$cloner);
                   10068:         foreach my $item (@{$code_order}) {
                   10069:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10070:                 foreach my $pair (@clonecodes) {
                   10071:                     my ($key,$val) = split(/\=/,$pair,2);
                   10072:                     $val = &unescape($val);
                   10073:                     if ($key eq $item) {
                   10074:                         $instcoderegexp .= '('.$val.')';
                   10075:                         last;
                   10076:                     }
                   10077:                 }
                   10078:             } else {
                   10079:                 $instcoderegexp .= $codedefaults->{$item};
                   10080:             }
                   10081:         }
                   10082:         $instcoderegexp .= '$';
                   10083:         my (@from,@to);
                   10084:         eval {
                   10085:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10086:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10087:         };
                   10088:         if ((@from > 0) && (@to > 0)) {
                   10089:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10090:             if (!@diffs) {
                   10091:                 $canclone = 1;
                   10092:             }
                   10093:         }
                   10094:     }
                   10095:     return $canclone;
                   10096: }
                   10097: 
                   10098: sub default_instcode_cloning {
                   10099:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10100:     my (%codedefaults,@code_order,$canclone);
                   10101:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10102:         %codedefaults = %{$codedefaultsref};
                   10103:         @code_order = @{$codeorderref};
                   10104:     } elsif ($clonedom) {
                   10105:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10106:     }
                   10107:     if (($domdefclone) && (@code_order)) {
                   10108:         my @clonecodes = split(/\+/,$domdefclone);
                   10109:         my $instcoderegexp ='^';
                   10110:         foreach my $item (@code_order) {
                   10111:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10112:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10113:             } else {
                   10114:                 $instcoderegexp .= $codedefaults{$item};
                   10115:             }
                   10116:         }
                   10117:         $instcoderegexp .= '$';
                   10118:         my (@from,@to);
                   10119:         eval {
                   10120:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10121:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10122:         };
                   10123:         if ((@from > 0) && (@to > 0)) {
                   10124:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10125:             if (!@diffs) {
                   10126:                 $canclone = 1;
                   10127:             }
                   10128:         }
                   10129:     }
                   10130:     return $canclone;
                   10131: }
                   10132: 
1.679     raeburn  10133: # ------------------------------------------------------- Course Group routines
                   10134: 
                   10135: sub get_coursegroups {
1.809     raeburn  10136:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10137:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10138: }
                   10139: 
1.679     raeburn  10140: sub modify_coursegroup {
                   10141:     my ($cdom,$cnum,$groupsettings) = @_;
                   10142:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10143: }
                   10144: 
1.809     raeburn  10145: sub toggle_coursegroup_status {
                   10146:     my ($cdom,$cnum,$group,$action) = @_;
                   10147:     my ($from_namespace,$to_namespace);
                   10148:     if ($action eq 'delete') {
                   10149:         $from_namespace = 'coursegroups';
                   10150:         $to_namespace = 'deleted_groups';
                   10151:     } else {
                   10152:         $from_namespace = 'deleted_groups';
                   10153:         $to_namespace = 'coursegroups';
                   10154:     }
                   10155:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10156:     if (my $tmp = &error(%curr_group)) {
                   10157:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10158:         return ('read error',$tmp);
                   10159:     } else {
                   10160:         my %savedsettings = %curr_group; 
1.809     raeburn  10161:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10162:         my $deloutcome;
                   10163:         if ($result eq 'ok') {
1.809     raeburn  10164:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10165:         } else {
                   10166:             return ('write error',$result);
                   10167:         }
                   10168:         if ($deloutcome eq 'ok') {
                   10169:             return 'ok';
                   10170:         } else {
                   10171:             return ('delete error',$deloutcome);
                   10172:         }
                   10173:     }
                   10174: }
                   10175: 
1.679     raeburn  10176: sub modify_group_roles {
1.957     raeburn  10177:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10178:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10179:     my $role = 'gr/'.&escape($userprivs);
                   10180:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10181:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10182:     if ($result eq 'ok') {
                   10183:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10184:     }
1.679     raeburn  10185:     return $result;
                   10186: }
                   10187: 
                   10188: sub modify_coursegroup_membership {
                   10189:     my ($cdom,$cnum,$membership) = @_;
                   10190:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10191:     return $result;
                   10192: }
                   10193: 
1.682     raeburn  10194: sub get_active_groups {
                   10195:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10196:     my $now = time;
                   10197:     my %groups = ();
                   10198:     foreach my $key (keys(%env)) {
1.811     albertel 10199:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10200:             my ($start,$end) = split(/\./,$env{$key});
                   10201:             if (($end!=0) && ($end<$now)) { next; }
                   10202:             if (($start!=0) && ($start>$now)) { next; }
                   10203:             if ($1 eq $cdom && $2 eq $cnum) {
                   10204:                 $groups{$3} = $env{$key} ;
                   10205:             }
                   10206:         }
                   10207:     }
                   10208:     return %groups;
                   10209: }
                   10210: 
1.683     raeburn  10211: sub get_group_membership {
                   10212:     my ($cdom,$cnum,$group) = @_;
                   10213:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10214: }
                   10215: 
                   10216: sub get_users_groups {
                   10217:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10218:     my @usersgroups;
1.683     raeburn  10219:     my $cachetime=1800;
                   10220: 
                   10221:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10222:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10223:     if (defined($cached)) {
1.734     albertel 10224:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10225:     } else {  
                   10226:         $grouplist = '';
1.816     raeburn  10227:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10228:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10229:         my $access_end = $env{'course.'.$courseid.
                   10230:                               '.default_enrollment_end_date'};
                   10231:         my $now = time;
                   10232:         foreach my $key (keys(%roleshash)) {
                   10233:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10234:                 my $group = $1;
                   10235:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10236:                     my $start = $2;
                   10237:                     my $end = $1;
                   10238:                     if ($start == -1) { next; } # deleted from group
                   10239:                     if (($start!=0) && ($start>$now)) { next; }
                   10240:                     if (($end!=0) && ($end<$now)) {
                   10241:                         if ($access_end && $access_end < $now) {
                   10242:                             if ($access_end - $end < 86400) {
                   10243:                                 push(@usersgroups,$group);
1.733     raeburn  10244:                             }
                   10245:                         }
1.817     raeburn  10246:                         next;
1.733     raeburn  10247:                     }
1.817     raeburn  10248:                     push(@usersgroups,$group);
1.683     raeburn  10249:                 }
                   10250:             }
                   10251:         }
1.817     raeburn  10252:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10253:         $grouplist = join(':',@usersgroups);
                   10254:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10255:     }
1.733     raeburn  10256:     return @usersgroups;
1.683     raeburn  10257: }
                   10258: 
                   10259: sub devalidate_getgroups_cache {
                   10260:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10261:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10262: 
1.683     raeburn  10263:     my $hashid="$udom:$uname:$courseid";
                   10264:     &devalidate_cache_new('getgroups',$hashid);
                   10265: }
                   10266: 
1.12      www      10267: # ------------------------------------------------------------------ Plain Text
                   10268: 
                   10269: sub plaintext {
1.988     raeburn  10270:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10271:     if ($short =~ m{^cr/}) {
1.758     albertel 10272: 	return (split('/',$short))[-1];
                   10273:     }
1.742     raeburn  10274:     if (!defined($cid)) {
                   10275:         $cid = $env{'request.course.id'};
                   10276:     }
                   10277:     my %rolenames = (
1.1008    raeburn  10278:                       Course    => 'std',
                   10279:                       Community => 'alt1',
1.1305    raeburn  10280:                       Placement => 'std',
1.742     raeburn  10281:                     );
1.1037    raeburn  10282:     if ($cid ne '') {
                   10283:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10284:             unless ($forcedefault) {
                   10285:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10286:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10287:                 return &Apache::lonlocal::mt($roletext);
                   10288:             }
                   10289:         }
                   10290:     }
                   10291:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10292:         (defined($rolenames{$type})) && 
                   10293:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10294:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10295:     } elsif ($cid ne '') {
                   10296:         my $crstype = $env{'course.'.$cid.'.type'};
                   10297:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10298:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10299:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10300:         }
1.742     raeburn  10301:     }
1.1037    raeburn  10302:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10303: }
                   10304: 
                   10305: # ----------------------------------------------------------------- Assign Role
                   10306: 
                   10307: sub assignrole {
1.957     raeburn  10308:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10309:         $context)=@_;
1.21      www      10310:     my $mrole;
                   10311:     if ($role =~ /^cr\//) {
1.393     www      10312:         my $cwosec=$url;
1.811     albertel 10313:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10314: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10315:            my $refused = 1;
                   10316:            if ($context eq 'requestcourses') {
                   10317:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10318:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10319:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10320:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10321:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10322:                            if ($crsenv{'internal.courseowner'} eq
                   10323:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10324:                                $refused = '';
                   10325:                            }
                   10326:                        }
                   10327:                    }
                   10328:                }
                   10329:            }
                   10330:            if ($refused) {
                   10331:                &logthis('Refused custom assignrole: '.
                   10332:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10333:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10334:                return 'refused';
                   10335:            }
1.104     www      10336:         }
1.21      www      10337:         $mrole='cr';
1.678     raeburn  10338:     } elsif ($role =~ /^gr\//) {
                   10339:         my $cwogrp=$url;
1.811     albertel 10340:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10341:         unless (&allowed('mdg',$cwogrp)) {
                   10342:             &logthis('Refused group assignrole: '.
                   10343:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10344:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10345:             return 'refused';
                   10346:         }
                   10347:         $mrole='gr';
1.21      www      10348:     } else {
1.82      www      10349:         my $cwosec=$url;
1.811     albertel 10350:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10351:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10352:             my $refused;
                   10353:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10354:                 if (!(&allowed('c'.$role,$url))) {
                   10355:                     $refused = 1;
                   10356:                 }
                   10357:             } else {
                   10358:                 $refused = 1;
                   10359:             }
1.947     raeburn  10360:             if ($refused) {
1.1045    raeburn  10361:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  10362:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10363:                     my %crsenv;
                   10364:                     if ($role eq 'cc' || $role eq 'co') {
                   10365:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10366:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10367:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10368:                                 if ($crsenv{'internal.courseowner'} eq 
                   10369:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10370:                                     $refused = '';
                   10371:                                 }
                   10372:                             }
                   10373:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10374:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10375:                                 if ($crsenv{'internal.courseowner'} eq 
                   10376:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10377:                                     $refused = '';
                   10378:                                 }
                   10379:                             }
                   10380:                         }
                   10381:                     }
1.1368    raeburn  10382:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10383:                     if ($role eq 'st') {
                   10384:                         $refused = '';
1.1377    raeburn  10385:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10386:                         $refused = '';
                   10387:                     }
1.1017    raeburn  10388:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10389:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10390:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10391:                         my $wrongcc;
                   10392:                         if ($cnum =~ /^$match_community$/) {
                   10393:                             $wrongcc = 1 if ($role eq 'cc');
                   10394:                         } else {
                   10395:                             $wrongcc = 1 if ($role eq 'co');
                   10396:                         }
                   10397:                         unless ($wrongcc) {
                   10398:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10399:                             if ($crsenv{'internal.courseowner'} eq 
                   10400:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10401:                                 $refused = '';
                   10402:                             }
1.1017    raeburn  10403:                         }
                   10404:                     }
1.1183    raeburn  10405:                 } elsif ($context eq 'requestauthor') {
                   10406:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10407:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10408:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10409:                             $refused = '';
                   10410:                         } else {
                   10411:                             my %domdefaults = &get_domain_defaults($udom);
                   10412:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10413:                                 my $checkbystatus;
                   10414:                                 if ($env{'user.adv'}) { 
                   10415:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10416:                                     if ($disposition eq 'automatic') {
                   10417:                                         $refused = '';
                   10418:                                     } elsif ($disposition eq '') {
                   10419:                                         $checkbystatus = 1;
                   10420:                                     } 
                   10421:                                 } else {
                   10422:                                     $checkbystatus = 1;
                   10423:                                 }
                   10424:                                 if ($checkbystatus) {
                   10425:                                     if ($env{'environment.inststatus'}) {
                   10426:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10427:                                         foreach my $type (@inststatuses) {
                   10428:                                             if (($type ne '') &&
                   10429:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10430:                                                 $refused = '';
                   10431:                                             }
                   10432:                                         }
                   10433:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10434:                                         $refused = '';
                   10435:                                     }
                   10436:                                 }
                   10437:                             }
                   10438:                         }
                   10439:                     }
1.1017    raeburn  10440:                 }
                   10441:                 if ($refused) {
1.947     raeburn  10442:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10443:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10444: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10445:                     return 'refused';
                   10446:                 }
1.932     raeburn  10447:             }
1.1131    raeburn  10448:         } elsif ($role eq 'au') {
                   10449:             if ($url ne '/'.$udom.'/') {
                   10450:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10451:                          ' to assign author role for '.$uname.':'.$udom.
                   10452:                          ' in domain: '.$url.' refused (wrong domain).');
                   10453:                 return 'refused';
                   10454:             }
1.104     www      10455:         }
1.21      www      10456:         $mrole=$role;
                   10457:     }
1.620     albertel 10458:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10459:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10460:     if ($end) { $command.='_'.$end; }
1.21      www      10461:     if ($start) {
                   10462: 	if ($end) { 
1.81      www      10463:            $command.='_'.$start; 
1.21      www      10464:         } else {
1.81      www      10465:            $command.='_0_'.$start;
1.21      www      10466:         }
                   10467:     }
1.739     raeburn  10468:     my $origstart = $start;
                   10469:     my $origend = $end;
1.957     raeburn  10470:     my $delflag;
1.357     www      10471: # actually delete
                   10472:     if ($deleteflag) {
1.373     www      10473: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10474: # modify command to delete the role
1.620     albertel 10475:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10476:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10477: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10478: # set start and finish to negative values for userrolelog
                   10479:            $start=-1;
                   10480:            $end=-1;
1.957     raeburn  10481:            $delflag = 1;
1.357     www      10482:         }
                   10483:     }
                   10484: # send command
1.349     www      10485:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10486: # log new user role if status is ok
1.349     www      10487:     if ($answer eq 'ok') {
1.663     raeburn  10488: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10489:         if (($role eq 'cc') || ($role eq 'in') ||
                   10490:             ($role eq 'ep') || ($role eq 'ad') ||
                   10491:             ($role eq 'ta') || ($role eq 'st') ||
                   10492:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10493:             ($role eq 'co')) {
1.1200    raeburn  10494: # for course roles, perform group memberships changes triggered by role change.
                   10495:             unless ($role =~ /^gr/) {
                   10496:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10497:                                                  $origstart,$selfenroll,$context);
                   10498:             }
1.1184    raeburn  10499:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10500:                            $selfenroll,$context);
                   10501:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10502:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10503:                  ($role eq 'da')) {
1.1184    raeburn  10504:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10505:                            $context);
                   10506:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10507:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10508:                              $context); 
                   10509:         }
1.1053    raeburn  10510:         if ($role eq 'cc') {
                   10511:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10512:         }
1.349     www      10513:     }
                   10514:     return $answer;
1.169     harris41 10515: }
                   10516: 
1.1053    raeburn  10517: sub autoupdate_coowners {
                   10518:     my ($url,$end,$start,$uname,$udom) = @_;
                   10519:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10520:     if (($cdom ne '') && ($cnum ne '')) {
                   10521:         my $now = time;
                   10522:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10523:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10524:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10525:             my $instcode = $coursehash{'internal.coursecode'};
1.1444    raeburn  10526:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10527:             if ($instcode ne '') {
1.1056    raeburn  10528:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10529:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10530:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10531:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444    raeburn  10532:                         unless ($result eq 'valid') {
                   10533:                             if ($xlists ne '') {
                   10534:                                 foreach my $xlist (split(',',$xlists)) {
                   10535:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10536:                                     $result =
1.1446    raeburn  10537:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10538:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10539:                                     last if ($result eq 'valid');
1.1444    raeburn  10540:                                 }
                   10541:                             }
                   10542:                         }
1.1056    raeburn  10543:                         if ($result eq 'valid') {
                   10544:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10545:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10546:                                     push(@newcoowners,$coowner);
                   10547:                                 }
                   10548:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10549:                                     push(@newcoowners,$uname.':'.$udom);
                   10550:                                 }
                   10551:                                 @newcoowners = sort(@newcoowners);
                   10552:                             } else {
                   10553:                                 push(@newcoowners,$uname.':'.$udom);
                   10554:                             }
1.1444    raeburn  10555:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10556:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10557:                                 unless ($coowner eq $uname.':'.$udom) {
                   10558:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10559:                                 }
1.1444    raeburn  10560:                             }
                   10561:                             unless (@newcoowners > 0) {
                   10562:                                 $delcoowners = 1;
                   10563:                                 $coowners = '';
1.1053    raeburn  10564:                             }
                   10565:                         }
                   10566:                         if (@newcoowners || $delcoowners) {
                   10567:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10568:                                             $delcoowners,@newcoowners);
                   10569:                         }
                   10570:                     }
                   10571:                 }
                   10572:             }
                   10573:         }
                   10574:     }
                   10575: }
                   10576: 
                   10577: sub store_coowners {
                   10578:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10579:     my $cid = $cdom.'_'.$cnum;
                   10580:     my ($coowners,$delresult,$putresult);
                   10581:     if (@newcoowners) {
                   10582:         $coowners = join(',',@newcoowners);
                   10583:         my %coownershash = (
                   10584:                             'internal.co-owners' => $coowners,
                   10585:                            );
                   10586:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10587:         if ($putresult eq 'ok') {
                   10588:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10589:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10590:             }
                   10591:         }
                   10592:     }
                   10593:     if ($delcoowners) {
                   10594:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10595:         if ($delresult eq 'ok') {
                   10596:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10597:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10598:             }
                   10599:         }
                   10600:     }
                   10601:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10602:         my %crsinfo =
                   10603:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10604:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10605:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10606:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10607:         }
                   10608:     }
                   10609: }
                   10610: 
1.169     harris41 10611: # -------------------------------------------------- Modify user authentication
1.197     www      10612: # Overrides without validation
                   10613: 
1.169     harris41 10614: sub modifyuserauth {
                   10615:     my ($udom,$uname,$umode,$upass)=@_;
                   10616:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  10617:     my $allowed;
                   10618:     if (&allowed('mau',$udom)) {
                   10619:         $allowed = 1;
                   10620:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10621:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10622:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10623:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10624:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10625:         if (($cdom ne '') && ($cnum ne '')) {
                   10626:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10627:             if ($is_owner) {
                   10628:                 $allowed = 1;
                   10629:             }
                   10630:         }
                   10631:     }
                   10632:     unless ($allowed) { return 'refused'; }
1.197     www      10633:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10634:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10635:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10636:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10637: 		     &escape($upass),$uhome);
1.1434    raeburn  10638:     my $ip = &get_requestor_ip();
1.620     albertel 10639:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10640:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434    raeburn  10641:          '(Remote '.$ip.'): '.$reply);
1.197     www      10642:     &log($udom,,$uname,$uhome,
1.620     albertel 10643:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10644:                                      $env{'user.name'}.', '.$umode.
1.1435    raeburn  10645:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10646:     unless ($reply eq 'ok') {
1.197     www      10647:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10648: 	return 'error: '.$reply;
                   10649:     }   
1.170     harris41 10650:     return 'ok';
1.80      www      10651: }
                   10652: 
1.81      www      10653: # --------------------------------------------------------------- Modify a user
1.80      www      10654: 
1.81      www      10655: sub modifyuser {
1.206     matthew  10656:     my ($udom,    $uname, $uid,
                   10657:         $umode,   $upass, $first,
                   10658:         $middle,  $last,  $gene,
1.1058    raeburn  10659:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10660:     $udom= &LONCAPA::clean_domain($udom);
                   10661:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10662:     my $showcandelete = 'none';
                   10663:     if (ref($candelete) eq 'ARRAY') {
                   10664:         if (@{$candelete} > 0) {
                   10665:             $showcandelete = join(', ',@{$candelete});
                   10666:         }
                   10667:     }
1.81      www      10668:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10669:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10670: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10671:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10672:                                      ' desiredhome not specified'). 
1.620     albertel 10673:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10674:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10675:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10676:     my $newuser;
                   10677:     if ($uhome eq 'no_host') {
                   10678:         $newuser = 1;
1.1368    raeburn  10679:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10680:                 ($umode eq 'lti')) {
                   10681:             return 'error: more information needed to create new user';
                   10682:         }
1.1075    raeburn  10683:     }
1.80      www      10684: # ----------------------------------------------------------------- Create User
1.406     albertel 10685:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10686: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10687:         my $unhome='';
1.844     albertel 10688:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10689:             $unhome = $desiredhome;
1.620     albertel 10690: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10691: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10692:         } else { # load balancing routine for determining $unhome
1.81      www      10693:             my $loadm=10000000;
1.841     albertel 10694: 	    my %servers = &get_servers($udom,'library');
                   10695: 	    foreach my $tryserver (keys(%servers)) {
                   10696: 		my $answer=reply('load',$tryserver);
                   10697: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10698: 		    $loadm=$answer;
                   10699: 		    $unhome=$tryserver;
                   10700: 		}
1.80      www      10701: 	    }
                   10702:         }
                   10703:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10704: 	    return 'error: unable to find a home server for '.$uname.
                   10705:                    ' in domain '.$udom;
1.80      www      10706:         }
                   10707:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10708:                          &escape($upass),$unhome);
                   10709: 	unless ($reply eq 'ok') {
                   10710:             return 'error: '.$reply;
                   10711:         }   
1.230     stredwic 10712:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10713:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10714: 	    return 'error: unable verify users home machine.';
1.80      www      10715:         }
1.209     matthew  10716:     }   # End of creation of new user
1.80      www      10717: # ---------------------------------------------------------------------- Add ID
                   10718:     if ($uid) {
                   10719:        $uid=~tr/A-Z/a-z/;
                   10720:        my %uidhash=&idrget($udom,$uname);
1.196     www      10721:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10722:          && (!$forceid)) {
1.80      www      10723: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10724: 	      return 'error: user id "'.$uid.'" does not match '.
                   10725:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10726:           }
                   10727:        } else {
1.1300    raeburn  10728: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10729:        }
                   10730:     }
                   10731: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10732:     my @tmp=&get('environment',
1.899     raeburn  10733: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10734:                     'permanentemail','inststatus'],
1.134     albertel 10735: 		   $udom,$uname);
1.1075    raeburn  10736:     my (%names,%oldnames);
1.313     matthew  10737:     if ($tmp[0] =~ m/^error:.*/) { 
                   10738:         %names=(); 
                   10739:     } else {
                   10740:         %names = @tmp;
1.1075    raeburn  10741:         %oldnames = %names;
1.313     matthew  10742:     }
1.388     www      10743: #
1.1058    raeburn  10744: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10745: # of users did not contain them), do not overwrite existing values
                   10746: # unless field is in $candelete array ref.  
                   10747: #
                   10748: 
                   10749:     my @fields = ('firstname','middlename','lastname','generation',
                   10750:                   'permanentemail','id');
                   10751:     my %newvalues;
                   10752:     if (ref($candelete) eq 'ARRAY') {
                   10753:         foreach my $field (@fields) {
                   10754:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10755:                 if ($field eq 'firstname') {
                   10756:                     $names{$field} = $first;
                   10757:                 } elsif ($field eq 'middlename') {
                   10758:                     $names{$field} = $middle;
                   10759:                 } elsif ($field eq 'lastname') {
                   10760:                     $names{$field} = $last;
                   10761:                 } elsif ($field eq 'generation') { 
                   10762:                     $names{$field} = $gene;
                   10763:                 } elsif ($field eq 'permanentemail') {
                   10764:                     $names{$field} = $email;
                   10765:                 } elsif ($field eq 'id') {
                   10766:                     $names{$field}  = $uid;
                   10767:                 }
                   10768:             }
                   10769:         }
                   10770:     }
1.388     www      10771:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10772:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10773:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10774:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10775:     if ($email) {
                   10776:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10777:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10778:     }
1.899     raeburn  10779:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10780:     if (defined($inststatus)) {
                   10781:         $names{'inststatus'} = '';
                   10782:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10783:         if (ref($usertypes) eq 'HASH') {
                   10784:             my @okstatuses; 
                   10785:             foreach my $item (split(/:/,$inststatus)) {
                   10786:                 if (defined($usertypes->{$item})) {
                   10787:                     push(@okstatuses,$item);  
                   10788:                 }
                   10789:             }
                   10790:             if (@okstatuses) {
                   10791:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10792:             }
                   10793:         }
                   10794:     }
1.1075    raeburn  10795:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10796:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10797:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10798:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10799:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10800:     } else {
                   10801:         $logmsg .= ' during self creation';
                   10802:     }
1.1075    raeburn  10803:     my $changed;
                   10804:     if ($newuser) {
                   10805:         $changed = 1;
                   10806:     } else {
                   10807:         foreach my $field (@fields) {
                   10808:             if ($names{$field} ne $oldnames{$field}) {
                   10809:                 $changed = 1;
                   10810:                 last;
                   10811:             }
                   10812:         }
                   10813:     }
                   10814:     unless ($changed) {
                   10815:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10816:         &logthis($logmsg);
                   10817:         return 'ok';
                   10818:     }
                   10819:     my $reply = &put('environment', \%names, $udom,$uname);
                   10820:     if ($reply ne 'ok') { 
                   10821:         return 'error: '.$reply;
                   10822:     }
1.1087    raeburn  10823:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10824:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10825:     }
1.1075    raeburn  10826:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10827:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10828:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10829:     &logthis($logmsg);
1.134     albertel 10830:     return 'ok';
1.80      www      10831: }
                   10832: 
1.81      www      10833: # -------------------------------------------------------------- Modify student
1.80      www      10834: 
1.81      www      10835: sub modifystudent {
                   10836:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10837:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10838:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10839:     if (!$cid) {
1.620     albertel 10840: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10841: 	    return 'not_in_class';
                   10842: 	}
1.80      www      10843:     }
                   10844: # --------------------------------------------------------------- Make the user
1.81      www      10845:     my $reply=&modifyuser
1.209     matthew  10846: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10847:          $desiredhome,$email,$inststatus);
1.80      www      10848:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10849:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10850:     # student's environment
1.297     matthew  10851:     $uid = undef if (!$forceid);
1.455     albertel 10852:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10853:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10854:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10855:     return $reply;
                   10856: }
                   10857: 
                   10858: sub modify_student_enrollment {
1.1216    raeburn  10859:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10860:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10861:     my ($cdom,$cnum,$chome);
                   10862:     if (!$cid) {
1.620     albertel 10863: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10864: 	    return 'not_in_class';
                   10865: 	}
1.620     albertel 10866: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10867: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10868:     } else {
                   10869: 	($cdom,$cnum)=split(/_/,$cid);
                   10870:     }
1.620     albertel 10871:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10872:     if (!$chome) {
1.457     raeburn  10873: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10874:     }
1.455     albertel 10875:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10876:     # Make sure the user exists
1.81      www      10877:     my $uhome=&homeserver($uname,$udom);
                   10878:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10879: 	return 'error: no such user';
                   10880:     }
1.297     matthew  10881:     # Get student data if we were not given enough information
                   10882:     if (!defined($first)  || $first  eq '' || 
                   10883:         !defined($last)   || $last   eq '' || 
                   10884:         !defined($uid)    || $uid    eq '' || 
                   10885:         !defined($middle) || $middle eq '' || 
                   10886:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10887:         # They did not supply us with enough data to enroll the student, so
                   10888:         # we need to pick up more information.
1.297     matthew  10889:         my %tmp = &get('environment',
1.294     matthew  10890:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10891:                        ,$udom,$uname);
                   10892: 
1.800     albertel 10893:         #foreach my $key (keys(%tmp)) {
                   10894:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10895:         #}
1.294     matthew  10896:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10897:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10898:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10899:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10900:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10901:     }
1.556     albertel 10902:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10903:     my $user = "$uname:$udom";
                   10904:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10905:     my $reply=cput('classlist',
1.1148    raeburn  10906: 		   {$user => 
1.1314    raeburn  10907: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10908: 		   $cdom,$cnum);
1.1148    raeburn  10909:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10910:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10911:     } else { 
1.81      www      10912: 	return 'error: '.$reply;
                   10913:     }
1.297     matthew  10914:     # Add student role to user
1.83      www      10915:     my $uurl='/'.$cid;
1.81      www      10916:     $uurl=~s/\_/\//g;
                   10917:     if ($usec) {
                   10918: 	$uurl.='/'.$usec;
                   10919:     }
1.1148    raeburn  10920:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10921:                              $selfenroll,$context);
                   10922:     if ($result ne 'ok') {
                   10923:         if ($old_entry{$user} ne '') {
                   10924:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10925:         } else {
                   10926:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10927:         }
                   10928:     }
                   10929:     return $result; 
1.21      www      10930: }
                   10931: 
1.556     albertel 10932: sub format_name {
                   10933:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10934:     my $name;
                   10935:     if ($first ne 'lastname') {
                   10936: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10937:     } else {
                   10938: 	if ($lastname=~/\S/) {
                   10939: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10940: 	    $name=~s/\s+,/,/;
                   10941: 	} else {
                   10942: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10943: 	}
                   10944:     }
                   10945:     $name=~s/^\s+//;
                   10946:     $name=~s/\s+$//;
                   10947:     $name=~s/\s+/ /g;
                   10948:     return $name;
                   10949: }
                   10950: 
1.84      www      10951: # ------------------------------------------------- Write to course preferences
                   10952: 
                   10953: sub writecoursepref {
                   10954:     my ($courseid,%prefs)=@_;
                   10955:     $courseid=~s/^\///;
                   10956:     $courseid=~s/\_/\//g;
                   10957:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10958:     my $chome=homeserver($cnum,$cdomain);
                   10959:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10960: 	return 'error: no such course';
                   10961:     }
                   10962:     my $cstring='';
1.800     albertel 10963:     foreach my $pref (keys(%prefs)) {
                   10964: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10965:     }
1.84      www      10966:     $cstring=~s/\&$//;
                   10967:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10968: }
                   10969: 
                   10970: # ---------------------------------------------------------- Make/modify course
                   10971: 
                   10972: sub createcourse {
1.741     raeburn  10973:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  10974:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10975:     $url=&declutter($url);
                   10976:     my $cid='';
1.1028    raeburn  10977:     if ($context eq 'requestcourses') {
                   10978:         my $can_create = 0;
                   10979:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10980:         if ($udom eq $ownerdom) {
1.1423    raeburn  10981:             my $reload;
                   10982:             if (($callercontext eq 'auto') &&
                   10983:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10984:                 $reload = 'reload';
                   10985:             }
                   10986:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10987:                                   $context)) {
                   10988:                 $can_create = 1;
                   10989:             }
                   10990:         } else {
                   10991:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10992:                                            $category);
                   10993:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10994:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10995:                 if (@curr > 0) {
                   10996:                     my @options = qw(approval validate autolimit);
                   10997:                     my $optregex = join('|',@options);
                   10998:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10999:                         $can_create = 1;
                   11000:                     }
                   11001:                 }
                   11002:             }
                   11003:         }
                   11004:         if ($can_create) {
                   11005:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   11006:                 unless (&allowed('ccc',$udom)) {
                   11007:                     return 'refused'; 
                   11008:                 }
1.1017    raeburn  11009:             }
                   11010:         } else {
                   11011:             return 'refused';
                   11012:         }
1.1028    raeburn  11013:     } elsif (!&allowed('ccc',$udom)) {
                   11014:         return 'refused';
1.84      www      11015:     }
1.1011    raeburn  11016: # --------------------------------------------------------------- Get Unique ID
                   11017:     my $uname;
                   11018:     if ($cnum =~ /^$match_courseid$/) {
                   11019:         my $chome=&homeserver($cnum,$udom,'true');
                   11020:         if (($chome eq '') || ($chome eq 'no_host')) {
                   11021:             $uname = $cnum;
                   11022:         } else {
1.1038    raeburn  11023:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11024:         }
                   11025:     } else {
1.1038    raeburn  11026:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11027:     }
                   11028:     return $uname if ($uname =~ /^error/);
                   11029: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  11030:     if (!defined($course_server)) {
                   11031:         if (defined(&domain($udom,'primary'))) {
                   11032:             $course_server = &domain($udom,'primary');
                   11033:         } else {
                   11034:             $course_server = $env{'user.home'}; 
                   11035:         }
                   11036:     }
                   11037:     my %host_servers =
                   11038:         &Apache::lonnet::get_servers($udom,'library');
                   11039:     unless ($host_servers{$course_server}) {
                   11040:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11041:     }
1.84      www      11042: # ------------------------------------------------------------- Make the course
                   11043:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11044:                       $course_server);
1.84      www      11045:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11046:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11047:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11048: 	return 'error: no such course';
                   11049:     }
1.271     www      11050: # ----------------------------------------------------------------- Course made
1.516     raeburn  11051: # log existence
1.1029    raeburn  11052:     my $now = time;
1.918     raeburn  11053:     my $newcourse = {
                   11054:                     $udom.'_'.$uname => {
1.921     raeburn  11055:                                      description => $description,
                   11056:                                      inst_code   => $inst_code,
                   11057:                                      owner       => $course_owner,
                   11058:                                      type        => $crstype,
1.1029    raeburn  11059:                                      creator     => $env{'user.name'}.':'.
                   11060:                                                     $env{'user.domain'},
                   11061:                                      created     => $now,
                   11062:                                      context     => $context,
1.918     raeburn  11063:                                                 },
                   11064:                     };
1.921     raeburn  11065:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11066: # set toplevel url
1.271     www      11067:     my $topurl=$url;
                   11068:     unless ($nonstandard) {
                   11069: # ------------------------------------------ For standard courses, make top url
                   11070:         my $mapurl=&clutter($url);
1.278     www      11071:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11072:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11073: <map>
                   11074: <resource id="1" type="start"></resource>
                   11075: <resource id="2" src="$mapurl"></resource>
                   11076: <resource id="3" type="finish"></resource>
                   11077: <link index="1" from="1" to="2"></link>
                   11078: <link index="2" from="2" to="3"></link>
                   11079: </map>
                   11080: ENDINITMAP
                   11081:         $topurl=&declutter(
1.638     albertel 11082:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11083:                           );
                   11084:     }
                   11085: # ----------------------------------------------------------- Write preferences
1.84      www      11086:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11087:                      ('description'              => $description,
                   11088:                       'url'                      => $topurl,
                   11089:                       'internal.creator'         => $env{'user.name'}.':'.
                   11090:                                                     $env{'user.domain'},
                   11091:                       'internal.created'         => $now,
                   11092:                       'internal.creationcontext' => $context)
                   11093:                     );
1.84      www      11094:     return '/'.$udom.'/'.$uname;
                   11095: }
                   11096: 
1.1011    raeburn  11097: # ------------------------------------------------------------------- Create ID
                   11098: sub generate_coursenum {
1.1038    raeburn  11099:     my ($udom,$crstype) = @_;
1.1011    raeburn  11100:     my $domdesc = &domain($udom);
                   11101:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11102:     my $first;
                   11103:     if ($crstype eq 'Community') {
                   11104:         $first = '0';
                   11105:     } else {
                   11106:         $first = int(1+rand(9)); 
                   11107:     } 
                   11108:     my $uname=$first.
1.1011    raeburn  11109:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11110:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11111:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11112: # ----------------------------------------------- Make sure that does not exist
                   11113:     my $uhome=&homeserver($uname,$udom,'true');
                   11114:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11115:         if ($crstype eq 'Community') {
                   11116:             $first = '0';
                   11117:         } else {
                   11118:             $first = int(1+rand(9));
                   11119:         }
                   11120:         $uname=$first.
1.1011    raeburn  11121:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11122:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11123:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11124:         $uhome=&homeserver($uname,$udom,'true');
                   11125:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11126:             return 'error: unable to generate unique course-ID';
                   11127:         }
                   11128:     }
                   11129:     return $uname;
                   11130: }
                   11131: 
1.813     albertel 11132: sub is_course {
1.1167    droeschl 11133:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11134:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   11135: 
1.1381    raeburn  11136:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11137:     my $uhome=&homeserver($cnum,$cdom);
                   11138:     my $iscourse;
                   11139:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  11140:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  11141:     } else {
                   11142:         my $hashid = $cdom.':'.$cnum;
                   11143:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11144:         unless (defined($cached)) {
                   11145:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11146:                                         $cnum,undef,undef,'.');
                   11147:             $iscourse = 0;
                   11148:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11149:                 $iscourse = 1;
                   11150:             }
                   11151:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11152:         }
                   11153:     }
                   11154:     return unless ($iscourse);
1.1167    droeschl 11155:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11156: }
                   11157: 
1.1015    raeburn  11158: sub store_userdata {
                   11159:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11160:     my $result;
1.1016    raeburn  11161:     if ($datakey ne '') {
1.1013    raeburn  11162:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11163:             if ($udom eq '' || $uname eq '') {
                   11164:                 $udom = $env{'user.domain'};
                   11165:                 $uname = $env{'user.name'};
                   11166:             }
                   11167:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11168:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11169:                 $result = 'error: no_host';
                   11170:             } else {
1.1434    raeburn  11171:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11172:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11173: 
                   11174:                 my $namevalue='';
                   11175:                 foreach my $key (keys(%{$storehash})) {
                   11176:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11177:                 }
                   11178:                 $namevalue=~s/\&$//;
1.1224    raeburn  11179:                 unless ($namespace eq 'courserequests') {
                   11180:                     $datakey = &escape($datakey);
                   11181:                 }
1.1105    raeburn  11182:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11183:                                   $namevalue,$uhome);
1.1013    raeburn  11184:             }
                   11185:         } else {
                   11186:             $result = 'error: data to store was not a hash reference'; 
                   11187:         }
                   11188:     } else {
                   11189:         $result= 'error: invalid requestkey'; 
                   11190:     }
                   11191:     return $result;
                   11192: }
                   11193: 
1.21      www      11194: # ---------------------------------------------------------- Assign Custom Role
                   11195: 
                   11196: sub assigncustomrole {
1.957     raeburn  11197:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11198:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11199:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11200: }
                   11201: 
                   11202: # ----------------------------------------------------------------- Revoke Role
                   11203: 
                   11204: sub revokerole {
1.957     raeburn  11205:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11206:     my $now=time;
1.965     raeburn  11207:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11208: }
                   11209: 
                   11210: # ---------------------------------------------------------- Revoke Custom Role
                   11211: 
                   11212: sub revokecustomrole {
1.957     raeburn  11213:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11214:     my $now=time;
1.357     www      11215:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11216:            $deleteflag,$selfenroll,$context);
1.17      www      11217: }
                   11218: 
1.533     banghart 11219: # ------------------------------------------------------------ Disk usage
1.535     albertel 11220: sub diskusage {
1.955     raeburn  11221:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11222:     $directorypath =~ s/\/$//;
                   11223:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11224:                        .&escape($getpropath).':'.&escape($uname).':'
                   11225:                        .&escape($udom),homeserver($uname,$udom));
                   11226:     if ($listing eq 'unknown_cmd') {
                   11227:         if ($getpropath) {
                   11228:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11229:         }
                   11230:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11231:     }
1.514     albertel 11232:     return $listing;
1.512     banghart 11233: }
                   11234: 
1.566     banghart 11235: sub is_locked {
1.1096    raeburn  11236:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11237:     my @check;
                   11238:     my $is_locked;
1.1093    raeburn  11239:     push (@check,$file_name);
1.613     albertel 11240:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11241: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11242:     my ($tmp)=keys(%locked);
                   11243:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11244:     
1.566     banghart 11245:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11246:         $is_locked = 'false';
                   11247:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11248:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11249:                $is_locked = 'true';
1.1096    raeburn  11250:                if (ref($which) eq 'ARRAY') {
                   11251:                    push(@{$which},$entry);
                   11252:                } else {
                   11253:                    last;
                   11254:                }
1.745     raeburn  11255:            }
                   11256:        }
1.566     banghart 11257:     } else {
                   11258:         $is_locked = 'false';
                   11259:     }
1.1093    raeburn  11260:     return $is_locked;
1.566     banghart 11261: }
                   11262: 
1.759     albertel 11263: sub declutter_portfile {
                   11264:     my ($file) = @_;
1.833     albertel 11265:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11266:     return $file;
                   11267: }
                   11268: 
1.559     banghart 11269: # ------------------------------------------------------------- Mark as Read Only
                   11270: 
                   11271: sub mark_as_readonly {
                   11272:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11273:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11274:     my ($tmp)=keys(%current_permissions);
                   11275:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11276:     foreach my $file (@{$files}) {
1.759     albertel 11277: 	$file = &declutter_portfile($file);
1.561     banghart 11278:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11279:     }
1.613     albertel 11280:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11281:     return;
                   11282: }
                   11283: 
1.572     banghart 11284: # ------------------------------------------------------------Save Selected Files
                   11285: 
                   11286: sub save_selected_files {
                   11287:     my ($user, $path, @files) = @_;
                   11288:     my $filename = $user."savedfiles";
1.573     banghart 11289:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  11290:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11291:     foreach my $file (@files) {
1.620     albertel 11292:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11293:     }
                   11294:     foreach my $file (@other_files) {
1.574     banghart 11295:         print (OUT $file."\n");
1.572     banghart 11296:     }
1.574     banghart 11297:     close (OUT);
1.572     banghart 11298:     return 'ok';
                   11299: }
                   11300: 
1.574     banghart 11301: sub clear_selected_files {
                   11302:     my ($user) = @_;
                   11303:     my $filename = $user."savedfiles";
1.1359    raeburn  11304:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11305:     print (OUT undef);
                   11306:     close (OUT);
                   11307:     return ("ok");    
                   11308: }
                   11309: 
1.572     banghart 11310: sub files_in_path {
                   11311:     my ($user, $path) = @_;
                   11312:     my $filename = $user."savedfiles";
                   11313:     my %return_files;
1.1359    raeburn  11314:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11315:     while (my $line_in = <IN>) {
1.574     banghart 11316:         chomp ($line_in);
                   11317:         my @paths_and_file = split (m!/!, $line_in);
                   11318:         my $file_part = pop (@paths_and_file);
                   11319:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11320:         $path_part.='/';
                   11321:         my $path_and_file = $path_part.$file_part;
                   11322:         if ($path_part eq $path) {
                   11323:             $return_files{$file_part}= 'selected';
                   11324:         }
                   11325:     }
1.574     banghart 11326:     close (IN);
                   11327:     return (\%return_files);
1.572     banghart 11328: }
                   11329: 
                   11330: # called in portfolio select mode, to show files selected NOT in current directory
                   11331: sub files_not_in_path {
                   11332:     my ($user, $path) = @_;
                   11333:     my $filename = $user."savedfiles";
                   11334:     my @return_files;
                   11335:     my $path_part;
1.1359    raeburn  11336:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11337:     while (my $line = <IN>) {
1.572     banghart 11338:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11339:         my @paths_and_file = split(m|/|, $line);
                   11340:         my $file_part = pop(@paths_and_file);
                   11341:         chomp($file_part);
                   11342:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11343:         $path_part .= '/';
                   11344:         my $path_and_file = $path_part.$file_part;
                   11345:         if ($path_part ne $path) {
1.800     albertel 11346:             push(@return_files, ($path_and_file));
1.572     banghart 11347:         }
                   11348:     }
1.800     albertel 11349:     close(OUT);
1.574     banghart 11350:     return (@return_files);
1.572     banghart 11351: }
                   11352: 
1.1273    raeburn  11353: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11354:  
                   11355: sub portfiles_versioning {
                   11356:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11357:     my $portfolio_root = '/userfiles/portfolio';
                   11358:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11359:     foreach my $file (@{$portfiles}) {
                   11360:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11361:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11362:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11363:         my $getpropath = 1;
                   11364:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11365:                                              $stu_name,$getpropath);
                   11366:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11367:         my $new_answer = 
                   11368:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11369:         if ($new_answer ne 'problem getting file') {
                   11370:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11371:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11372:                               [$symb,$env{'request.course.id'},'graded']);
                   11373:         }
                   11374:     }
                   11375: }
                   11376: 
                   11377: sub get_next_version {
                   11378:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11379:     my $version;
                   11380:     if (ref($dir_list) eq 'ARRAY') {
                   11381:         foreach my $row (@{$dir_list}) {
                   11382:             my ($file) = split(/\&/,$row,2);
                   11383:             my ($file_name,$file_version,$file_ext) =
                   11384:                 &file_name_version_ext($file);
                   11385:             if (($file_name eq $answer_name) &&
                   11386:                 ($file_ext eq $answer_ext)) {
                   11387:                      # gets here if filename and extension match,
                   11388:                      # regardless of version
                   11389:                 if ($file_version ne '') {
                   11390:                     # a versioned file is found  so save it for later
                   11391:                     if ($file_version > $version) {
                   11392:                         $version = $file_version;
                   11393:                     }
                   11394:                 }
                   11395:             }
                   11396:         }
                   11397:     }
                   11398:     $version ++;
                   11399:     return($version);
                   11400: }
                   11401: 
                   11402: sub version_selected_portfile {
                   11403:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11404:     my ($answer_name,$answer_ver,$answer_ext) =
                   11405:         &file_name_version_ext($file_name);
                   11406:     my $new_answer;
                   11407:     $env{'form.copy'} =
                   11408:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11409:     if($env{'form.copy'} eq '-1') {
                   11410:         $new_answer = 'problem getting file';
                   11411:     } else {
                   11412:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11413:         my $copy_result = 
                   11414:             &finishuserfileupload($stu_name,$domain,'copy',
                   11415:                                   '/portfolio'.$directory.$new_answer);
                   11416:     }
                   11417:     undef($env{'form.copy'});
                   11418:     return ($new_answer);
                   11419: }
                   11420: 
                   11421: sub file_name_version_ext {
                   11422:     my ($file)=@_;
                   11423:     my @file_parts = split(/\./, $file);
                   11424:     my ($name,$version,$ext);
                   11425:     if (@file_parts > 1) {
                   11426:         $ext=pop(@file_parts);
                   11427:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11428:             $version=pop(@file_parts);
                   11429:         }
                   11430:         $name=join('.',@file_parts);
                   11431:     } else {
                   11432:         $name=join('.',@file_parts);
                   11433:     }
                   11434:     return($name,$version,$ext);
                   11435: }
                   11436: 
1.745     raeburn  11437: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11438: 
1.745     raeburn  11439: sub get_portfile_permissions {
                   11440:     my ($domain,$user) = @_;
1.613     albertel 11441:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11442:     my ($tmp)=keys(%current_permissions);
                   11443:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11444:     return \%current_permissions;
                   11445: }
                   11446: 
                   11447: #---------------------------------------------Get portfolio file access controls
                   11448: 
1.749     raeburn  11449: sub get_access_controls {
1.745     raeburn  11450:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11451:     my %access;
                   11452:     my $real_file = $file;
                   11453:     $file =~ s/\.meta$//;
1.745     raeburn  11454:     if (defined($file)) {
1.749     raeburn  11455:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11456:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11457:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11458:             }
                   11459:         }
1.745     raeburn  11460:     } else {
1.749     raeburn  11461:         foreach my $key (keys(%{$current_permissions})) {
                   11462:             if ($key =~ /\0accesscontrol$/) {
                   11463:                 if (defined($group)) {
                   11464:                     if ($key !~ m-^\Q$group\E/-) {
                   11465:                         next;
                   11466:                     }
                   11467:                 }
                   11468:                 my ($fullpath) = split(/\0/,$key);
                   11469:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11470:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11471:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11472:                     }
                   11473:                 }
                   11474:             }
                   11475:         }
                   11476:     }
                   11477:     return %access;
                   11478: }
                   11479: 
                   11480: sub modify_access_controls {
                   11481:     my ($file_name,$changes,$domain,$user)=@_;
                   11482:     my ($outcome,$deloutcome);
                   11483:     my %store_permissions;
                   11484:     my %new_values;
                   11485:     my %new_control;
                   11486:     my %translation;
                   11487:     my @deletions = ();
                   11488:     my $now = time;
                   11489:     if (exists($$changes{'activate'})) {
                   11490:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11491:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11492:             my $numnew = scalar(@newitems);
                   11493:             for (my $i=0; $i<$numnew; $i++) {
                   11494:                 my $newkey = $newitems[$i];
                   11495:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11496:                 if ($newkey =~ /^\d+:/) { 
                   11497:                     $newkey =~ s/^(\d+)/$newid/;
                   11498:                     $translation{$1} = $newid;
                   11499:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11500:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11501:                     $translation{$1} = $newid;
                   11502:                 }
1.749     raeburn  11503:                 $new_values{$file_name."\0".$newkey} = 
                   11504:                                           $$changes{'activate'}{$newitems[$i]};
                   11505:                 $new_control{$newkey} = $now;
                   11506:             }
                   11507:         }
                   11508:     }
                   11509:     my %todelete;
                   11510:     my %changed_items;
                   11511:     foreach my $action ('delete','update') {
                   11512:         if (exists($$changes{$action})) {
                   11513:             if (ref($$changes{$action}) eq 'HASH') {
                   11514:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11515:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11516:                     if ($action eq 'delete') { 
                   11517:                         $todelete{$itemnum} = 1;
                   11518:                     } else {
                   11519:                         $changed_items{$itemnum} = $key;
                   11520:                     }
                   11521:                 }
1.745     raeburn  11522:             }
                   11523:         }
1.749     raeburn  11524:     }
                   11525:     # get lock on access controls for file.
                   11526:     my $lockhash = {
                   11527:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11528:                                                        ':'.$env{'user.domain'},
                   11529:                    }; 
                   11530:     my $tries = 0;
                   11531:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11532:    
1.1288    damieng  11533:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11534:         $tries ++;
1.1289    damieng  11535:         sleep(0.1);
1.749     raeburn  11536:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11537:     }
                   11538:     if ($gotlock eq 'ok') {
                   11539:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11540:         my ($tmp)=keys(%curr_permissions);
                   11541:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11542:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11543:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11544:             if (ref($curr_controls) eq 'HASH') {
                   11545:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11546:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11547:                     if (defined($todelete{$itemnum})) {
                   11548:                         push(@deletions,$file_name."\0".$control_item);
                   11549:                     } else {
                   11550:                         if (defined($changed_items{$itemnum})) {
                   11551:                             $new_control{$changed_items{$itemnum}} = $now;
                   11552:                             push(@deletions,$file_name."\0".$control_item);
                   11553:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11554:                         } else {
                   11555:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11556:                         }
                   11557:                     }
1.745     raeburn  11558:                 }
                   11559:             }
                   11560:         }
1.970     raeburn  11561:         my ($group);
                   11562:         if (&is_course($domain,$user)) {
                   11563:             ($group,my $file) = split(/\//,$file_name,2);
                   11564:         }
1.749     raeburn  11565:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11566:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11567:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11568:         #  remove lock
                   11569:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11570:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11571:         my $sqlresult =
1.970     raeburn  11572:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11573:                                     $group);
1.749     raeburn  11574:     } else {
                   11575:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11576:     }
1.749     raeburn  11577:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11578: }
                   11579: 
1.827     raeburn  11580: sub make_public_indefinitely {
1.1271    raeburn  11581:     my (@requrl) = @_;
                   11582:     return &automated_portfile_access('public',\@requrl);
                   11583: }
                   11584: 
                   11585: sub automated_portfile_access {
                   11586:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11587:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11588:         return 'invalid';
                   11589:     }
1.1271    raeburn  11590:     my %urls;
                   11591:     if (ref($addsref) eq 'ARRAY') {
                   11592:         foreach my $requrl (@{$addsref}) {
                   11593:             if (&is_portfolio_url($requrl)) {
                   11594:                 unless (exists($urls{$requrl})) {
                   11595:                     $urls{$requrl} = 'add';
                   11596:                 }
                   11597:             }
                   11598:         }
                   11599:     }
                   11600:     if (ref($delsref) eq 'ARRAY') {
                   11601:         foreach my $requrl (@{$delsref}) { 
                   11602:             if (&is_portfolio_url($requrl)) {
                   11603:                 unless (exists($urls{$requrl})) {
                   11604:                     $urls{$requrl} = 'delete'; 
                   11605:                 }
                   11606:             }
                   11607:         }
                   11608:     }
                   11609:     unless (keys(%urls)) {
                   11610:         return 'invalid';
                   11611:     }
                   11612:     my $ip;
                   11613:     if ($accesstype eq 'ip') {
                   11614:         if (ref($info) eq 'HASH') {
                   11615:             if ($info->{'ip'} ne '') {
                   11616:                 $ip = $info->{'ip'};
                   11617:             }
                   11618:         }
                   11619:         if ($ip eq '') {
                   11620:             return 'invalid';
                   11621:         }
                   11622:     }
                   11623:     my $errors;
1.827     raeburn  11624:     my $now = time;
1.1271    raeburn  11625:     my %current_perms;
                   11626:     foreach my $requrl (sort(keys(%urls))) {
                   11627:         my $action;
                   11628:         if ($urls{$requrl} eq 'add') {
                   11629:             $action = 'activate';
                   11630:         } else {
                   11631:             $action = 'none';
                   11632:         }
                   11633:         my $aclnum = 0;
1.827     raeburn  11634:         my (undef,$udom,$unum,$file_name,$group) =
                   11635:             &parse_portfolio_url($requrl);
1.1271    raeburn  11636:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11637:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11638:         }
                   11639:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11640:                                                    $group,$file_name);
                   11641:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11642:             my ($num,$scope,$end,$start) = 
                   11643:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11644:             if ($scope eq $accesstype) {
                   11645:                 if (($start <= $now) && ($end == 0)) {
                   11646:                     if ($accesstype eq 'ip') {
                   11647:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11648:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11649:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11650:                                     if ($urls{$requrl} eq 'add') {
                   11651:                                         $action = 'none';
                   11652:                                         last;
                   11653:                                     } else {
                   11654:                                         $action = 'delete';
                   11655:                                         $aclnum = $num;
                   11656:                                         last;
                   11657:                                     }
                   11658:                                 }
                   11659:                             }
                   11660:                         }
                   11661:                     } elsif ($accesstype eq 'public') {
                   11662:                         if ($urls{$requrl} eq 'add') {
                   11663:                             $action = 'none';
                   11664:                             last;
                   11665:                         } else {
                   11666:                             $action = 'delete';
                   11667:                             $aclnum = $num;
                   11668:                             last;
                   11669:                         }
                   11670:                     }
                   11671:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11672:                     $action = 'update';
                   11673:                     $aclnum = $num;
1.1271    raeburn  11674:                     last;
1.827     raeburn  11675:                 }
                   11676:             }
                   11677:         }
                   11678:         if ($action eq 'none') {
1.1271    raeburn  11679:             next;
1.827     raeburn  11680:         } else {
                   11681:             my %changes;
                   11682:             my $newend = 0;
                   11683:             my $newstart = $now;
1.1271    raeburn  11684:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11685:             $changes{$action}{$newkey} = {
1.1271    raeburn  11686:                 type => $accesstype,
1.827     raeburn  11687:                 time => {
                   11688:                     start => $newstart,
                   11689:                     end   => $newend,
                   11690:                 },
                   11691:             };
1.1271    raeburn  11692:             if ($accesstype eq 'ip') {
                   11693:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11694:             }
1.827     raeburn  11695:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11696:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11697:             unless ($outcome eq 'ok') {
                   11698:                 $errors .= $outcome.' ';
                   11699:             }
1.827     raeburn  11700:         }
1.1271    raeburn  11701:     }
                   11702:     if ($errors) {
                   11703:         $errors =~ s/\s$//;
                   11704:         return $errors;
1.827     raeburn  11705:     } else {
1.1271    raeburn  11706:         return 'ok';
1.827     raeburn  11707:     }
                   11708: }
                   11709: 
1.745     raeburn  11710: #------------------------------------------------------Get Marked as Read Only
                   11711: 
                   11712: sub get_marked_as_readonly {
                   11713:     my ($domain,$user,$what,$group) = @_;
                   11714:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11715:     my @readonly_files;
1.629     banghart 11716:     my $cmp1=$what;
                   11717:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11718:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11719:         if (defined($group)) {
                   11720:             if ($file_name !~ m-^\Q$group\E/-) {
                   11721:                 next;
                   11722:             }
                   11723:         }
1.561     banghart 11724:         if (ref($value) eq "ARRAY"){
                   11725:             foreach my $stored_what (@{$value}) {
1.629     banghart 11726:                 my $cmp2=$stored_what;
1.759     albertel 11727:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11728:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11729:                 }
1.629     banghart 11730:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11731:                     push(@readonly_files, $file_name);
1.745     raeburn  11732:                     last;
1.563     banghart 11733:                 } elsif (!defined($what)) {
                   11734:                     push(@readonly_files, $file_name);
1.745     raeburn  11735:                     last;
1.561     banghart 11736:                 }
                   11737:             }
1.745     raeburn  11738:         }
1.561     banghart 11739:     }
                   11740:     return @readonly_files;
                   11741: }
1.577     banghart 11742: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11743: 
1.577     banghart 11744: sub get_marked_as_readonly_hash {
1.745     raeburn  11745:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11746:     my %readonly_files;
1.745     raeburn  11747:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11748:         if (defined($group)) {
                   11749:             if ($file_name !~ m-^\Q$group\E/-) {
                   11750:                 next;
                   11751:             }
                   11752:         }
1.577     banghart 11753:         if (ref($value) eq "ARRAY"){
                   11754:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11755:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11756:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11757:                         if ($lock_descriptor eq 'graded') {
                   11758:                             $readonly_files{$file_name} = 'graded';
                   11759:                         } elsif ($lock_descriptor eq 'handback') {
                   11760:                             $readonly_files{$file_name} = 'handback';
                   11761:                         } else {
                   11762:                             if (!exists($readonly_files{$file_name})) {
                   11763:                                 $readonly_files{$file_name} = 'locked';
                   11764:                             }
                   11765:                         }
1.745     raeburn  11766:                     }
1.750     banghart 11767:                 } 
1.577     banghart 11768:             }
                   11769:         } 
                   11770:     }
                   11771:     return %readonly_files;
                   11772: }
1.559     banghart 11773: # ------------------------------------------------------------ Unmark as Read Only
                   11774: 
                   11775: sub unmark_as_readonly {
1.629     banghart 11776:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11777:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11778:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11779:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11780:     my $symb_crs = $what;
                   11781:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11782:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11783:     my ($tmp)=keys(%current_permissions);
                   11784:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11785:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11786:     foreach my $file (@readonly_files) {
1.759     albertel 11787: 	my $clean_file = &declutter_portfile($file);
                   11788: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11789: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11790:         my @new_locks;
                   11791:         my @del_keys;
                   11792:         if (ref($current_locks) eq "ARRAY"){
                   11793:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11794:                 my $compare=$locker;
1.749     raeburn  11795:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11796:                     $compare=join('',@{$locker});
1.746     raeburn  11797:                     if ($compare ne $symb_crs) {
                   11798:                         push(@new_locks, $locker);
                   11799:                     }
1.563     banghart 11800:                 }
                   11801:             }
1.650     albertel 11802:             if (scalar(@new_locks) > 0) {
1.563     banghart 11803:                 $current_permissions{$file} = \@new_locks;
                   11804:             } else {
                   11805:                 push(@del_keys, $file);
1.613     albertel 11806:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11807:                 delete($current_permissions{$file});
1.563     banghart 11808:             }
                   11809:         }
1.561     banghart 11810:     }
1.613     albertel 11811:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11812:     return;
                   11813: }
1.512     banghart 11814: 
1.17      www      11815: # ------------------------------------------------------------ Directory lister
                   11816: 
                   11817: sub dirlist {
1.955     raeburn  11818:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11819:     $uri=~s/^\///;
                   11820:     $uri=~s/\/$//;
1.253     stredwic 11821:     my ($udom, $uname);
1.955     raeburn  11822:     if ($getuserdir) {
1.253     stredwic 11823:         $udom = $userdomain;
                   11824:         $uname = $username;
1.955     raeburn  11825:     } else {
                   11826:         (undef,$udom,$uname)=split(/\//,$uri);
                   11827:         if(defined($userdomain)) {
                   11828:             $udom = $userdomain;
                   11829:         }
                   11830:         if(defined($username)) {
                   11831:             $uname = $username;
                   11832:         }
1.253     stredwic 11833:     }
1.955     raeburn  11834:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11835: 
1.955     raeburn  11836:     $dirRoot = $perlvar{'lonDocRoot'};
                   11837:     if (defined($getpropath)) {
                   11838:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11839:         $dirRoot =~ s/\/$//;
1.955     raeburn  11840:     } elsif (defined($getuserdir)) {
                   11841:         my $subdir=$uname.'__';
                   11842:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11843:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11844:                    ."/$udom/$subdir/$uname";
                   11845:     } elsif (defined($alternateRoot)) {
                   11846:         $dirRoot = $alternateRoot;
1.751     banghart 11847:     }
1.253     stredwic 11848: 
                   11849:     if($udom) {
                   11850:         if($uname) {
1.1135    raeburn  11851:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11852:             if ($uhome eq 'no_host') {
                   11853:                 return ([],'no_host');
                   11854:             }
1.955     raeburn  11855:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11856:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11857:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11858:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11859:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11860:             } else {
                   11861:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11862:             }
1.605     matthew  11863:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11864:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11865:                 @listing_results = split(/:/,$listing);
                   11866:             } else {
                   11867:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11868:             }
1.1135    raeburn  11869:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11870:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11871:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11872:                 return ([],$listing);
                   11873:             } else {
                   11874:                 return (\@listing_results);
1.1135    raeburn  11875:             }
1.955     raeburn  11876:         } elsif(!$alternateRoot) {
1.1136    raeburn  11877:             my (%allusers,%listerror);
1.841     albertel 11878: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11879:  	    foreach my $tryserver (keys(%servers)) {
                   11880:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11881:                                   &escape($udom),$tryserver);
                   11882:                 if ($listing eq 'unknown_cmd') {
                   11883: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11884: 				      $udom, $tryserver);
                   11885:                 } else {
                   11886:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11887:                 }
1.841     albertel 11888: 		if ($listing eq 'unknown_cmd') {
                   11889: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11890: 				      $udom, $tryserver);
                   11891: 		    @listing_results = split(/:/,$listing);
                   11892: 		} else {
                   11893: 		    @listing_results =
                   11894: 			map { &unescape($_); } split(/:/,$listing);
                   11895: 		}
1.1136    raeburn  11896:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11897:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11898:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11899:                     $listerror{$tryserver} = $listing;
                   11900:                 } else {
1.841     albertel 11901: 		    foreach my $line (@listing_results) {
                   11902: 			my ($entry) = split(/&/,$line,2);
                   11903: 			$allusers{$entry} = 1;
                   11904: 		    }
                   11905: 		}
1.253     stredwic 11906:             }
1.1136    raeburn  11907:             my @alluserslist=();
1.800     albertel 11908:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11909:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11910:             }
1.1318    droeschl 11911: 
                   11912:             if (!%listerror) {
                   11913:                 # no errors
                   11914:                 return (\@alluserslist);
                   11915:             } elsif (scalar(keys(%servers)) == 1) {
                   11916:                 # one library server, one error 
                   11917:                 my ($key) = keys(%listerror);
                   11918:                 return (\@alluserslist, $listerror{$key});
                   11919:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11920:                 # con_lost indicates that we might miss data from at least one
                   11921:                 # library server
                   11922:                 return (\@alluserslist, 'con_lost');
                   11923:             } else {
                   11924:                 # multiple library servers and no con_lost -> data should be
                   11925:                 # complete. 
                   11926:                 return (\@alluserslist);
                   11927:             }
                   11928: 
1.253     stredwic 11929:         } else {
1.1136    raeburn  11930:             return ([],'missing username');
1.253     stredwic 11931:         }
1.955     raeburn  11932:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11933:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11934:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11935:         return (\@all_domains);
1.955     raeburn  11936:     } else {
1.1136    raeburn  11937:         return ([],'missing domain');
1.275     stredwic 11938:     }
                   11939: }
                   11940: 
                   11941: # --------------------------------------------- GetFileTimestamp
                   11942: # This function utilizes dirlist and returns the date stamp for
                   11943: # when it was last modified.  It will also return an error of -1
                   11944: # if an error occurs
                   11945: 
                   11946: sub GetFileTimestamp {
1.955     raeburn  11947:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11948:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11949:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11950:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11951:                                     undef,$getuserdir);
                   11952:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11953:         return -1;
                   11954:     }
                   11955:     if (ref($fileref) eq 'ARRAY') {
                   11956:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11957:         # @stats contains first the filename, then the stat output
                   11958:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11959:     } else {
                   11960:         return -1;
1.253     stredwic 11961:     }
1.26      www      11962: }
                   11963: 
1.712     albertel 11964: sub stat_file {
                   11965:     my ($uri) = @_;
1.787     albertel 11966:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11967: 
1.955     raeburn  11968:     my ($udom,$uname,$file);
1.712     albertel 11969:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11970: 	($udom,$uname,$file) =
1.811     albertel 11971: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11972: 	$file = 'userfiles/'.$file;
                   11973:     }
                   11974:     if ($uri =~ m-^/res/-) {
                   11975: 	($udom,$uname) = 
1.807     albertel 11976: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11977: 	$file = $uri;
                   11978:     }
                   11979: 
                   11980:     if (!$udom || !$uname || !$file) {
                   11981: 	# unable to handle the uri
                   11982: 	return ();
                   11983:     }
1.956     raeburn  11984:     my $getpropath;
                   11985:     if ($file =~ /^userfiles\//) {
                   11986:         $getpropath = 1;
                   11987:     }
1.1136    raeburn  11988:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11989:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11990:         return ();
                   11991:     } else {
                   11992:         if (ref($listref) eq 'ARRAY') {
                   11993:             my @stats = split('&',$listref->[0]);
                   11994: 	    shift(@stats); #filename is first
                   11995: 	    return @stats;
                   11996:         }
1.712     albertel 11997:     }
                   11998:     return ();
                   11999: }
                   12000: 
1.1313    raeburn  12001: # --------------------------------------------------------- recursedirs
                   12002: # Recursive function to traverse either a specific user's Authoring Space
                   12003: # or corresponding Published Resource Space, and populate the hash ref:
                   12004: # $dirhashref with URLs of all directories, and if $filehashref hash
                   12005: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   12006: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   12007: # files in Authoring Space.
                   12008: #
                   12009: # Inputs:
                   12010: #
                   12011: # $is_home - true if current server is home server for user's space
                   12012: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   12013: # $docroot - Document root (i.e., /home/httpd/html
                   12014: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   12015: # $relpath - Current path (relative to top level).
                   12016: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   12017: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   12018: #
                   12019: # Returns: nothing
                   12020: #
                   12021: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   12022: #
                   12023: # Currently used by interface/londocs.pm to create linked select boxes for
                   12024: # directory and filename to import a Course "Author" resource into a course, and
                   12025: # also to create linked select boxes for Authoring Space and Directory to choose
                   12026: # save location for creation of a new "standard" problem from the Course Editor.
                   12027: #
                   12028: 
                   12029: sub recursedirs {
                   12030:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   12031:     return unless (ref($dirhashref) eq 'HASH');
                   12032:     my $currpath = $docroot.$toppath;
                   12033:     if ($relpath) {
                   12034:         $currpath .= "/$relpath";
                   12035:     }
                   12036:     my $savefile;
                   12037:     if (ref($filehashref)) {
                   12038:         $savefile = 1;
                   12039:     }
                   12040:     if ($is_home) {
                   12041:         if (opendir(my $dirh,$currpath)) {
                   12042:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   12043:                 next if ($item eq '');
                   12044:                 if (-d "$currpath/$item") {
                   12045:                     my $newpath;
                   12046:                     if ($relpath) {
                   12047:                         $newpath = "$relpath/$item";
                   12048:                     } else {
                   12049:                         $newpath = $item;
                   12050:                     }
                   12051:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   12052:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   12053:                 } elsif ($savefile) {
                   12054:                     if ($context eq 'priv') {
                   12055:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   12056:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   12057:                         }
                   12058:                     } else {
                   12059:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   12060:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   12061:                         }
                   12062:                     }
                   12063:                 }
                   12064:             }
                   12065:             closedir($dirh);
                   12066:         }
                   12067:     } else {
                   12068:         my ($dirlistref,$listerror) =
                   12069:             &dirlist($toppath.$relpath);
                   12070:         my @dir_lines;
                   12071:         my $dirptr=16384;
                   12072:         if (ref($dirlistref) eq 'ARRAY') {
                   12073:             foreach my $dir_line (sort
                   12074:                               {
                   12075:                                   my ($afile)=split('&',$a,2);
                   12076:                                   my ($bfile)=split('&',$b,2);
                   12077:                                   return (lc($afile) cmp lc($bfile));
                   12078:                               } (@{$dirlistref})) {
                   12079:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   12080:                     split(/\&/,$dir_line,16);
                   12081:                 $item =~ s/\s+$//;
                   12082:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   12083:                 if ($dirptr&$testdir) {
                   12084:                     my $newpath;
                   12085:                     if ($relpath) {
                   12086:                         $newpath = "$relpath/$item";
                   12087:                     } else {
                   12088:                         $relpath = '/';
                   12089:                         $newpath = $item;
                   12090:                     }
                   12091:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   12092:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   12093:                 } elsif ($savefile) {
                   12094:                     if ($context eq 'priv') {
                   12095:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   12096:                             $filehashref->{$relpath}{$item} = 1;
                   12097:                         }
                   12098:                     } else {
                   12099:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   12100:                             $filehashref->{$relpath}{$item} = 1;
                   12101:                         }
                   12102:                     }
                   12103:                 }
                   12104:             }
                   12105:         }
                   12106:     }
                   12107:     return;
                   12108: }
                   12109: 
1.26      www      12110: # -------------------------------------------------------- Value of a Condition
                   12111: 
1.713     albertel 12112: # gets the value of a specific preevaluated condition
                   12113: #    stored in the string  $env{user.state.<cid>}
                   12114: # or looks up a condition reference in the bighash and if if hasn't
                   12115: # already been evaluated recurses into docondval to get the value of
                   12116: # the condition, then memoizing it to 
                   12117: #   $env{user.state.<cid>.<condition>}
1.40      www      12118: sub directcondval {
                   12119:     my $number=shift;
1.620     albertel 12120:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 12121: 	&Apache::lonuserstate::evalstate();
                   12122:     }
1.713     albertel 12123:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   12124: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   12125:     } elsif ($number =~ /^_/) {
                   12126: 	my $sub_condition;
                   12127: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12128: 		&GDBM_READER(),0640)) {
                   12129: 	    $sub_condition=$bighash{'conditions'.$number};
                   12130: 	    untie(%bighash);
                   12131: 	}
                   12132: 	my $value = &docondval($sub_condition);
1.949     raeburn  12133: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 12134: 	return $value;
                   12135:     }
1.620     albertel 12136:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   12137:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      12138:     } else {
                   12139:        return 2;
                   12140:     }
                   12141: }
                   12142: 
1.713     albertel 12143: # get the collection of conditions for this resource
1.26      www      12144: sub condval {
                   12145:     my $condidx=shift;
1.54      www      12146:     my $allpathcond='';
1.713     albertel 12147:     foreach my $cond (split(/\|/,$condidx)) {
                   12148: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   12149: 	    $allpathcond.=
                   12150: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   12151: 	}
1.191     harris41 12152:     }
1.54      www      12153:     $allpathcond=~s/\|$//;
1.713     albertel 12154:     return &docondval($allpathcond);
                   12155: }
                   12156: 
                   12157: #evaluates an expression of conditions
                   12158: sub docondval {
                   12159:     my ($allpathcond) = @_;
                   12160:     my $result=0;
                   12161:     if ($env{'request.course.id'}
                   12162: 	&& defined($allpathcond)) {
                   12163: 	my $operand='|';
                   12164: 	my @stack;
                   12165: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   12166: 	    if ($chunk eq '(') {
                   12167: 		push @stack,($operand,$result);
                   12168: 	    } elsif ($chunk eq ')') {
                   12169: 		my $before=pop @stack;
                   12170: 		if (pop @stack eq '&') {
                   12171: 		    $result=$result>$before?$before:$result;
                   12172: 		} else {
                   12173: 		    $result=$result>$before?$result:$before;
                   12174: 		}
                   12175: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   12176: 		$operand=$chunk;
                   12177: 	    } else {
                   12178: 		my $new=directcondval($chunk);
                   12179: 		if ($operand eq '&') {
                   12180: 		    $result=$result>$new?$new:$result;
                   12181: 		} else {
                   12182: 		    $result=$result>$new?$result:$new;
                   12183: 		}
                   12184: 	    }
                   12185: 	}
1.26      www      12186:     }
                   12187:     return $result;
1.421     albertel 12188: }
                   12189: 
                   12190: # ---------------------------------------------------- Devalidate courseresdata
                   12191: 
                   12192: sub devalidatecourseresdata {
                   12193:     my ($coursenum,$coursedomain)=@_;
                   12194:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12195:     &devalidate_cache_new('courseres',$hashid);
1.28      www      12196: }
                   12197: 
1.763     www      12198: 
1.200     www      12199: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     12200: #
                   12201: #  Parameters:
                   12202: #      $coursenum    - Number of the course.
                   12203: #      $coursedomain - Domain at which the course was created.
                   12204: #  Returns:
                   12205: #     A hash of the course parameters along (I think) with timestamps
                   12206: #     and version info.
1.877     foxr     12207: 
1.624     albertel 12208: sub get_courseresdata {
                   12209:     my ($coursenum,$coursedomain)=@_;
1.200     www      12210:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   12211:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12212:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 12213:     my %dumpreply;
1.417     albertel 12214:     unless (defined($cached)) {
1.624     albertel 12215: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 12216: 	$result=\%dumpreply;
1.251     albertel 12217: 	my ($tmp) = keys(%dumpreply);
                   12218: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 12219: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 12220: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   12221: 	    return $tmp;
1.416     albertel 12222: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 12223: 	    $result=undef;
1.599     albertel 12224: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 12225: 	}
                   12226:     }
1.624     albertel 12227:     return $result;
                   12228: }
                   12229: 
1.633     albertel 12230: sub devalidateuserresdata {
                   12231:     my ($uname,$udom)=@_;
                   12232:     my $hashid="$udom:$uname";
                   12233:     &devalidate_cache_new('userres',$hashid);
                   12234: }
                   12235: 
1.624     albertel 12236: sub get_userresdata {
                   12237:     my ($uname,$udom)=@_;
                   12238:     #most student don\'t have any data set, check if there is some data
                   12239:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   12240: 
                   12241:     my $hashid="$udom:$uname";
                   12242:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   12243:     if (!defined($cached)) {
                   12244: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   12245: 	$result=\%resourcedata;
                   12246: 	&do_cache_new('userres',$hashid,$result,600);
                   12247:     }
                   12248:     my ($tmp)=keys(%$result);
                   12249:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   12250: 	return $result;
                   12251:     }
                   12252:     #error 2 occurs when the .db doesn't exist
                   12253:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  12254:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   12255: 	    &logthis("<font color=\"blue\">WARNING:".
                   12256: 		     " Trying to get resource data for ".
                   12257: 		     $uname." at ".$udom.": ".
                   12258: 		     $tmp."</font>");
                   12259:         }
1.624     albertel 12260:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 12261: 	#&EXT_cache_set($udom,$uname);
                   12262: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 12263: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 12264:     }
                   12265:     return $tmp;
                   12266: }
1.879     foxr     12267: #----------------------------------------------- resdata - return resource data
                   12268: #  Purpose:
                   12269: #    Return resource data for either users or for a course.
                   12270: #  Parameters:
                   12271: #     $name      - Course/user name.
                   12272: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  12273: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  12274: #     $mapp      - decluttered URL of enclosing map  
                   12275: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   12276: #     $recurseup - Ref to array of map URLs, starting with map containing
                   12277: #                  $mapp up through hierarchy of nested maps to top level map.  
                   12278: #     $courseid  - CourseID (first part of param identifier).
                   12279: #     $modifier  - Middle part of param identifier.
                   12280: #     $what      - Last part of param identifier.
1.879     foxr     12281: #     @which     - Array of names of resources desired.
                   12282: #  Returns:
                   12283: #     The value of the first reasource in @which that is found in the
                   12284: #     resource hash.
                   12285: #  Exceptional Conditions:
                   12286: #     If the $type passed in is not valid (not the string 'course' or 
                   12287: #     'user', an undefined  reference is returned.
                   12288: #     If none of the resources are found, an undef is returned
1.624     albertel 12289: sub resdata {
1.1301    raeburn  12290:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   12291:         $modifier,$what,@which)=@_;
1.624     albertel 12292:     my $result;
                   12293:     if ($type eq 'course') {
                   12294: 	$result=&get_courseresdata($name,$domain);
                   12295:     } elsif ($type eq 'user') {
                   12296: 	$result=&get_userresdata($name,$domain);
                   12297:     }
                   12298:     if (!ref($result)) { return $result; }    
1.251     albertel 12299:     foreach my $item (@which) {
1.1301    raeburn  12300:         if ($item->[1] eq 'course') {
                   12301:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   12302:                 unless ($$recursed) {
1.1302    raeburn  12303:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  12304:                     $$recursed = 1;
                   12305:                 }
                   12306:                 foreach my $item (@${recurseup}) {
                   12307:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   12308:                     last if (defined($result->{$norecursechk}));
                   12309:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   12310:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   12311:                 }
                   12312:             }
                   12313:         }
                   12314:         if (defined($result->{$item->[0]})) {
1.927     albertel 12315: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12316: 	}
1.250     albertel 12317:     }
1.291     albertel 12318:     return undef;
1.200     www      12319: }
                   12320: 
1.1360    raeburn  12321: sub get_domain_lti {
                   12322:     my ($cdom,$context) = @_;
1.1483    raeburn  12323:     my ($name,$cachename,%lti);
1.1360    raeburn  12324:     if ($context eq 'consumer') {
                   12325:         $name = 'ltitools';
                   12326:     } elsif ($context eq 'provider') {
                   12327:         $name = 'lti';
1.1483    raeburn  12328:     } elsif ($context eq 'linkprot') {
                   12329:         $name = 'ltisec';
1.1360    raeburn  12330:     } else {
                   12331:         return %lti;
                   12332:     }
1.1483    raeburn  12333: 
                   12334:     if ($context eq 'linkprot') {
                   12335:         $cachename = $context;
                   12336:     } else {
                   12337:         $cachename = $name;
                   12338:     }
                   12339:     
                   12340:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298    raeburn  12341:     if (defined($cached)) {
                   12342:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12343:             %lti = %{$result};
1.1298    raeburn  12344:         }
                   12345:     } else {
1.1360    raeburn  12346:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12347:         if (ref($domconfig{$name}) eq 'HASH') {
1.1483    raeburn  12348:             if ($context eq 'linkprot') {
                   12349:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12350:                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12351:                 }
                   12352:             } else {
                   12353:                 %lti = %{$domconfig{$name}};
                   12354:             }
                   12355:             if (($context eq 'consumer') && (keys(%lti))) {
                   12356:                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
                   12357:                 if (ref($encdomconfig{$name}) eq 'HASH') {
                   12358:                     foreach my $id (keys(%lti)) {
                   12359:                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
                   12360:                             foreach my $item ('key','secret') {
                   12361:                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
                   12362:                             }
1.1344    raeburn  12363:                         }
                   12364:                     }
                   12365:                 }
                   12366:             }
1.1298    raeburn  12367:         }
                   12368:         my $cachetime = 24*60*60;
1.1483    raeburn  12369:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298    raeburn  12370:     }
1.1360    raeburn  12371:     return %lti;
1.1298    raeburn  12372: }
                   12373: 
1.1463    raeburn  12374: sub get_course_lti {
                   12375:     my ($cnum,$cdom) = @_;
                   12376:     my $hashid=$cdom.'_'.$cnum;
                   12377:     my %courselti;
                   12378:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   12379:     if (defined($cached)) {
                   12380:         if (ref($result) eq 'HASH') {
                   12381:             %courselti = %{$result};
                   12382:         }
                   12383:     } else {
                   12384:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   12385:         my $cachetime = 24*60*60;
                   12386:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   12387:     }
                   12388:     return %courselti;
                   12389: }
                   12390: 
1.1479    raeburn  12391: sub courselti_itemid {
                   12392:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12393:     my ($chome,$itemid);
                   12394:     $chome = &homeserver($cnum,$cdom);
                   12395:     return if ($chome eq 'no_host');
                   12396:     if (ref($params) eq 'HASH') {
                   12397:         my $items = &freeze_escape($params);
                   12398:         my $rep;
                   12399:         if (grep { $_ eq $chome } current_machine_ids()) {
                   12400:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12401:         } else {
                   12402:             my $escurl = &escape($url);
                   12403:             my $escmethod = &escape($method);
                   12404:             my $items = &freeze_escape($params);
                   12405:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12406:         }
                   12407:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12408:                 ($rep eq 'unknown_cmd')) {
                   12409:             $itemid = $rep;
                   12410:         }
                   12411:     }
                   12412:     return $itemid;
                   12413: }
                   12414: 
                   12415: sub domainlti_itemid {
                   12416:     my ($cdom,$url,$method,$params,$context) = @_;
                   12417:     my ($primary_id,$itemid);
                   12418:     $primary_id = &domain($cdom,'primary');
                   12419:     return if ($primary_id eq '');
                   12420:     if (ref($params) eq 'HASH') {
                   12421:         my $items = &freeze_escape($params);
                   12422:         my $rep;
                   12423:         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12424:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12425:         } else {
                   12426:             my $cnum = '';
                   12427:             my $escurl = &escape($url);
                   12428:             my $escmethod = &escape($method);
                   12429:             my $items = &freeze_escape($params);
                   12430:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   12431:         }
                   12432:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12433:                 ($rep eq 'unknown_cmd')) {
                   12434:             $itemid = $rep;
                   12435:         }
                   12436:     }
                   12437:     return $itemid;
                   12438: }
                   12439: 
1.1236    raeburn  12440: sub get_numsuppfiles {
                   12441:     my ($cnum,$cdom,$ignorecache)=@_;
                   12442:     my $hashid=$cnum.':'.$cdom;
                   12443:     my ($suppcount,$cached);
                   12444:     unless ($ignorecache) {
                   12445:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   12446:     }
                   12447:     unless (defined($cached)) {
                   12448:         my $chome=&homeserver($cnum,$cdom);
                   12449:         unless ($chome eq 'no_host') {
1.1366    raeburn  12450:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  12451:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  12452:             ($suppcount,$supptools,$errors) =
                   12453:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   12454:                                                          $supptools,$errors);
1.1236    raeburn  12455:         }
                   12456:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   12457:     }
                   12458:     return $suppcount;
                   12459: }
                   12460: 
1.379     matthew  12461: #
                   12462: # EXT resource caching routines
                   12463: #
                   12464: 
1.1302    raeburn  12465: {
                   12466: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12467: #
                   12468: # The course for which we cache
                   12469: my $cachedmapkey='';
                   12470: # The cached recursive maps for this course
                   12471: my %cachedmaps=();
                   12472: # When this was last done
                   12473: my $cachedmaptime='';
                   12474: 
1.379     matthew  12475: sub clear_EXT_cache_status {
1.383     albertel 12476:     &delenv('cache.EXT.');
1.379     matthew  12477: }
                   12478: 
                   12479: sub EXT_cache_status {
                   12480:     my ($target_domain,$target_user) = @_;
1.383     albertel 12481:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12482:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12483:         # We know already the user has no data
                   12484:         return 1;
                   12485:     } else {
                   12486:         return 0;
                   12487:     }
                   12488: }
                   12489: 
                   12490: sub EXT_cache_set {
                   12491:     my ($target_domain,$target_user) = @_;
1.383     albertel 12492:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12493:     #&appenv({$cachename => time});
1.379     matthew  12494: }
                   12495: 
1.28      www      12496: # --------------------------------------------------------- Value of a Variable
1.58      www      12497: sub EXT {
1.715     albertel 12498: 
1.1461    raeburn  12499:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68      www      12500:     unless ($varname) { return ''; }
1.218     albertel 12501:     #get real user name/domain, courseid and symb
                   12502:     my $courseid;
1.359     albertel 12503:     my $publicuser;
1.427     www      12504:     if ($symbparm) {
                   12505: 	$symbparm=&get_symb_from_alias($symbparm);
                   12506:     }
1.218     albertel 12507:     if (!($uname && $udom)) {
1.790     albertel 12508:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12509:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12510:     } else {
1.620     albertel 12511: 	$courseid=$env{'request.course.id'};
1.218     albertel 12512:     }
1.48      www      12513:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12514:     my $rest;
1.320     albertel 12515:     if (defined($therest[0])) {
1.48      www      12516:        $rest=join('.',@therest);
                   12517:     } else {
                   12518:        $rest='';
                   12519:     }
1.320     albertel 12520: 
1.57      www      12521:     my $qualifierrest=$qualifier;
                   12522:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12523:     my $spacequalifierrest=$space;
                   12524:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12525:     if ($realm eq 'user') {
1.48      www      12526: # --------------------------------------------------------------- user.resource
                   12527: 	if ($space eq 'resource') {
1.651     albertel 12528: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12529: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12530: 		 &&
1.1469    raeburn  12531: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12532: 		# if we are in the middle of processing the resource the
                   12533: 		# get the value we are planning on committing
                   12534:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12535:                     return $Apache::lonhomework::results{$qualifierrest};
                   12536:                 } else {
                   12537:                     return $Apache::lonhomework::history{$qualifierrest};
                   12538:                 }
1.335     albertel 12539: 	    } else {
1.359     albertel 12540: 		my %restored;
1.620     albertel 12541: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12542: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12543: 		} else {
                   12544: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12545: 		}
1.335     albertel 12546: 		return $restored{$qualifierrest};
                   12547: 	    }
1.48      www      12548: # ----------------------------------------------------------------- user.access
                   12549:         } elsif ($space eq 'access') {
1.218     albertel 12550: 	    # FIXME - not supporting calls for a specific user
1.48      www      12551:             return &allowed($qualifier,$rest);
                   12552: # ------------------------------------------ user.preferences, user.environment
                   12553:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12554: 	    if (($uname eq $env{'user.name'}) &&
                   12555: 		($udom eq $env{'user.domain'})) {
                   12556: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12557: 	    } else {
1.359     albertel 12558: 		my %returnhash;
                   12559: 		if (!$publicuser) {
                   12560: 		    %returnhash=&userenvironment($udom,$uname,
                   12561: 						 $qualifierrest);
                   12562: 		}
1.218     albertel 12563: 		return $returnhash{$qualifierrest};
                   12564: 	    }
1.48      www      12565: # ----------------------------------------------------------------- user.course
                   12566:         } elsif ($space eq 'course') {
1.218     albertel 12567: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12568:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12569: # ------------------------------------------------------------------- user.role
                   12570:         } elsif ($space eq 'role') {
1.218     albertel 12571: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12572:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12573:             if ($qualifier eq 'value') {
                   12574: 		return $role;
                   12575:             } elsif ($qualifier eq 'extent') {
                   12576:                 return $where;
                   12577:             }
                   12578: # ----------------------------------------------------------------- user.domain
                   12579:         } elsif ($space eq 'domain') {
1.218     albertel 12580:             return $udom;
1.48      www      12581: # ------------------------------------------------------------------- user.name
                   12582:         } elsif ($space eq 'name') {
1.218     albertel 12583:             return $uname;
1.48      www      12584: # ---------------------------------------------------- Any other user namespace
1.29      www      12585:         } else {
1.359     albertel 12586: 	    my %reply;
                   12587: 	    if (!$publicuser) {
                   12588: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12589: 	    }
                   12590: 	    return $reply{$qualifierrest};
1.48      www      12591:         }
1.236     www      12592:     } elsif ($realm eq 'query') {
                   12593: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12594:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12595: 						[$spacequalifierrest]);
1.620     albertel 12596: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12597:    } elsif ($realm eq 'request') {
1.48      www      12598: # ------------------------------------------------------------- request.browser
                   12599:         if ($space eq 'browser') {
1.1145    bisitz   12600:             return $env{'browser.'.$qualifier};
1.57      www      12601: # ------------------------------------------------------------ request.filename
                   12602:         } else {
1.620     albertel 12603:             return $env{'request.'.$spacequalifierrest};
1.29      www      12604:         }
1.28      www      12605:     } elsif ($realm eq 'course') {
1.48      www      12606: # ---------------------------------------------------------- course.description
1.620     albertel 12607:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12608:     } elsif ($realm eq 'resource') {
1.165     www      12609: 
1.620     albertel 12610: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12611: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12612: 	}
1.693     albertel 12613: 
1.1232    raeburn  12614:         if ($qualifier eq '') {
                   12615: 	    if ($space eq 'title') {
                   12616: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12617: 	        return &gettitle($symbparm);
                   12618: 	    }
1.693     albertel 12619: 	
1.1232    raeburn  12620: 	    if ($space eq 'map') {
                   12621: 	        my ($map) = &decode_symb($symbparm);
                   12622: 	        return &symbread($map);
                   12623: 	    }
                   12624:             if ($space eq 'maptitle') {
                   12625:                 my ($map) = &decode_symb($symbparm);
                   12626:                 return &gettitle($map);
                   12627:             }
                   12628: 	    if ($space eq 'filename') {
                   12629: 	        if ($symbparm) {
                   12630: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12631: 	        }
                   12632: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12633: 	    }
1.1232    raeburn  12634: 
1.1233    raeburn  12635:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12636:                 if ($space eq 'visibleparts') {
                   12637:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12638:                     my $item;
                   12639:                     if (ref($navmap)) {
                   12640:                         my $res = $navmap->getBySymb($symbparm);
                   12641:                         my $parts = $res->parts();
                   12642:                         if (ref($parts) eq 'ARRAY') {
                   12643:                             $item = join(',',@{$parts});
                   12644:                         }
                   12645:                         undef($navmap);
1.1232    raeburn  12646:                     }
1.1233    raeburn  12647:                     return $item;
1.1232    raeburn  12648:                 }
                   12649:             }
                   12650:         }
1.693     albertel 12651: 
1.1301    raeburn  12652: 	my ($section, $group, @groups, @recurseup, $recursed);
1.1461    raeburn  12653:         if (ref($recurseupref) eq 'ARRAY') {
                   12654:             @recurseup = @{$recurseupref};
                   12655:             $recursed = 1;
                   12656:         }
1.1301    raeburn  12657: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  12658:         if (($courseid eq '') && ($cid)) {
                   12659:             $courseid = $cid;
                   12660:         }
                   12661: 	if (($symbparm && $courseid) && 
                   12662: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      12663: 
1.218     albertel 12664: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12665: 
1.60      www      12666: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12667: 	    my $symbp=$symbparm;
1.1301    raeburn  12668: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12669: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  12670:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12671: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12672: 	    if (($env{'user.name'} eq $uname) &&
                   12673: 		($env{'user.domain'} eq $udom)) {
                   12674: 		$section=$env{'request.course.sec'};
1.733     raeburn  12675:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12676:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12677: 	    } else {
1.539     albertel 12678: 		if (! defined($usection)) {
1.551     albertel 12679: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12680: 		} else {
                   12681: 		    $section = $usection;
                   12682: 		}
1.733     raeburn  12683:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12684: 	    }
                   12685: 
                   12686: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12687: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12688:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12689: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12690: 
1.593     albertel 12691: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12692: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12693:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12694: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12695: 
1.60      www      12696: # ----------------------------------------------------------- first, check user
1.624     albertel 12697: 
1.1301    raeburn  12698: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12699:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12700: 				       ([$courselevelr,'resource'],
                   12701: 					[$courselevelm,'map'     ],
1.1301    raeburn  12702:                                         [$courseleveli,'map'     ],
1.927     albertel 12703: 					[$courselevel, 'course'  ]));
1.931     albertel 12704: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12705: 
1.594     albertel 12706: # ------------------------------------------------ second, check some of course
1.684     raeburn  12707:             my $coursereply;
1.691     raeburn  12708:             if (@groups > 0) {
                   12709:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12710:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12711:                                        $mapp,\$recursed,\@recurseup);
                   12712:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12713:             }
1.96      www      12714: 
1.684     raeburn  12715: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12716: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12717: 				  'course',$mapp,\$recursed,\@recurseup,
                   12718:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12719: 				  ([$seclevelr,   'resource'],
                   12720: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12721:                                    [$secleveli,   'map'     ],
1.927     albertel 12722: 				   [$seclevel,    'course'  ],
                   12723: 				   [$courselevelr,'resource']));
                   12724: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12725: 
1.60      www      12726: # ------------------------------------------------------ third, check map parms
1.218     albertel 12727: 	    my %parmhash=();
                   12728: 	    my $thisparm='';
                   12729: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12730: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12731: 		    &GDBM_READER(),0640)) {
1.218     albertel 12732: 		$thisparm=$parmhash{$symbparm};
                   12733: 		untie(%parmhash);
                   12734: 	    }
1.927     albertel 12735: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12736: 	}
1.594     albertel 12737: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12738:  
                   12739:         my $what = $spacequalifierrest;
                   12740: 	$what=~s/\./\_/;
1.282     albertel 12741: 	my $filename;
                   12742: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12743: 	if ($symbparm) {
1.409     www      12744: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12745: 	} else {
1.620     albertel 12746: 	    $filename=$env{'request.filename'};
1.282     albertel 12747: 	}
1.1362    raeburn  12748:         my $toolsymb;
                   12749:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12750:             $toolsymb = $symbparm;
                   12751:         }
                   12752: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12753: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12754: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12755: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12756: 
1.1301    raeburn  12757: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12758: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12759: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12760: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12761: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12762: 				     'course',$mapp,\$recursed,\@recurseup,
                   12763:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12764: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12765:                                       [$courseleveli,'map'   ],
1.927     albertel 12766: 				      [$courselevel, 'course']));
                   12767: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12768: 	}
1.145     www      12769: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12770: 	unless ($space eq '0') {
1.336     albertel 12771: 	    my @parts=split(/_/,$space);
                   12772: 	    my $id=pop(@parts);
                   12773: 	    my $part=join('_',@parts);
                   12774: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12775: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12776: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12777: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12778: 	}
1.395     albertel 12779: 	if ($recurse) { return undef; }
1.1362    raeburn  12780: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12781: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12782: # ---------------------------------------------------- Any other user namespace
                   12783:     } elsif ($realm eq 'environment') {
                   12784: # ----------------------------------------------------------------- environment
1.620     albertel 12785: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12786: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12787: 	} else {
1.770     albertel 12788: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12789: 		return '';
                   12790: 	    }
1.219     albertel 12791: 	    my %returnhash=&userenvironment($udom,$uname,
                   12792: 					    $spacequalifierrest);
                   12793: 	    return $returnhash{$spacequalifierrest};
                   12794: 	}
1.28      www      12795:     } elsif ($realm eq 'system') {
1.48      www      12796: # ----------------------------------------------------------------- system.time
                   12797: 	if ($space eq 'time') {
                   12798: 	    return time;
                   12799:         }
1.696     albertel 12800:     } elsif ($realm eq 'server') {
                   12801: # ----------------------------------------------------------------- system.time
                   12802: 	if ($space eq 'name') {
                   12803: 	    return $ENV{'SERVER_NAME'};
                   12804:         }
1.1415    raeburn  12805:     } elsif ($realm eq 'client') {
                   12806:         if ($space eq 'remote_addr') {
1.1441    raeburn  12807:             return &get_requestor_ip();
1.1415    raeburn  12808:         }
1.28      www      12809:     }
1.48      www      12810:     return '';
1.61      www      12811: }
                   12812: 
1.927     albertel 12813: sub get_reply {
                   12814:     my ($reply_value) = @_;
1.940     raeburn  12815:     if (ref($reply_value) eq 'ARRAY') {
                   12816:         if (wantarray) {
                   12817: 	    return @$reply_value;
                   12818:         }
                   12819:         return $reply_value->[0];
                   12820:     } else {
                   12821:         return $reply_value;
1.927     albertel 12822:     }
                   12823: }
                   12824: 
1.691     raeburn  12825: sub check_group_parms {
1.1301    raeburn  12826:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12827:         $recursed,$recurseupref) = @_;
                   12828:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12829:                   [$what,'course']);
                   12830:     my $coursereply;
1.691     raeburn  12831:     foreach my $group (@{$groups}) {
1.1301    raeburn  12832:         my @groupitems = ();
1.691     raeburn  12833:         foreach my $level (@levels) {
1.927     albertel 12834:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12835:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12836:         }
1.1301    raeburn  12837:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12838:                                    $env{'course.'.$courseid.'.domain'},
                   12839:                                    'course',$mapp,$recursed,$recurseupref,
                   12840:                                    $courseid,'.['.$group.'].',$what,
                   12841:                                    @groupitems);
                   12842:         last if (defined($coursereply));
1.691     raeburn  12843:     }
                   12844:     return $coursereply;
                   12845: }
                   12846: 
1.1301    raeburn  12847: sub get_map_hierarchy {
1.1302    raeburn  12848:     my ($mapname,$courseid) = @_;
                   12849:     my @recurseup = ();
1.1301    raeburn  12850:     if ($mapname) {
1.1302    raeburn  12851:         if (($cachedmapkey eq $courseid) &&
                   12852:             (abs($cachedmaptime-time)<5)) {
                   12853:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12854:                 return @{$cachedmaps{$mapname}};
                   12855:             }
                   12856:         }
1.1301    raeburn  12857:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12858:         if (ref($navmap)) {
                   12859:             @recurseup = $navmap->recurseup_maps($mapname);
                   12860:             undef($navmap);
1.1302    raeburn  12861:             $cachedmaps{$mapname} = \@recurseup;
                   12862:             $cachedmaptime=time;
                   12863:             $cachedmapkey=$courseid;
1.1301    raeburn  12864:         }
                   12865:     }
                   12866:     return @recurseup;
                   12867: }
                   12868: 
1.1302    raeburn  12869: }
                   12870: 
1.691     raeburn  12871: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12872:     my ($courseid,@groups) = @_;
                   12873:     @groups = sort(@groups);
1.691     raeburn  12874:     return @groups;
                   12875: }
                   12876: 
1.395     albertel 12877: sub packages_tab_default {
1.1362    raeburn  12878:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12879:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12880: 
                   12881:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12882:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12883: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12884: 	if ($pack_type eq 'default') {
                   12885: 	    $do_default=1;
                   12886: 	} elsif ($pack_type eq 'extension') {
                   12887: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12888: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12889: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12890: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12891: 	}
                   12892:     }
                   12893:     # first look for a package that matches the requested part id
                   12894:     foreach my $package (@specifics) {
                   12895: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12896: 	next if ($pack_part ne $part);
                   12897: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12898: 	    return $packagetab{"$pack_type&$name&default"};
                   12899: 	}
                   12900:     }
                   12901:     # look for any possible matching non extension_ package
                   12902:     foreach my $package (@specifics) {
                   12903: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12904: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12905: 	    return $packagetab{"$pack_type&$name&default"};
                   12906: 	}
1.585     albertel 12907: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12908: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12909: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12910: 	}
                   12911:     }
1.738     albertel 12912:     # look for any posible extension_ match
                   12913:     foreach my $package (@extension) {
                   12914: 	my ($package,$pack_type)=@{$package};
                   12915: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12916: 	    return $packagetab{"$pack_type&$name&default"};
                   12917: 	}
                   12918: 	if (defined($packagetab{$package."&$name&default"})) {
                   12919: 	    return $packagetab{$package."&$name&default"};
                   12920: 	}
                   12921:     }
                   12922:     # look for a global default setting
                   12923:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12924: 	return $packagetab{"default&$name&default"};
                   12925:     }
1.395     albertel 12926:     return undef;
                   12927: }
                   12928: 
1.334     albertel 12929: sub add_prefix_and_part {
                   12930:     my ($prefix,$part)=@_;
                   12931:     my $keyroot;
                   12932:     if (defined($prefix) && $prefix !~ /^__/) {
                   12933: 	# prefix that has a part already
                   12934: 	$keyroot=$prefix;
                   12935:     } elsif (defined($prefix)) {
                   12936: 	# prefix that is missing a part
                   12937: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12938:     } else {
                   12939: 	# no prefix at all
                   12940: 	if (defined($part)) { $keyroot='_'.$part; }
                   12941:     }
                   12942:     return $keyroot;
                   12943: }
                   12944: 
1.71      www      12945: # ---------------------------------------------------------------- Get metadata
                   12946: 
1.599     albertel 12947: my %metaentry;
1.1070    www      12948: my %importedpartids;
1.1369    raeburn  12949: my %importedrespids;
1.71      www      12950: sub metadata {
1.1362    raeburn  12951:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12952:     $uri=&declutter($uri);
1.288     albertel 12953:     # if it is a non metadata possible uri return quickly
1.529     albertel 12954:     if (($uri eq '') || 
                   12955: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12956: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12957:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12958: 	return undef;
                   12959:     }
1.1261    raeburn  12960:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12961: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12962: 	return undef;
1.288     albertel 12963:     }
1.73      www      12964:     my $filename=$uri;
                   12965:     $uri=~s/\.meta$//;
1.172     www      12966: #
                   12967: # Is the metadata already cached?
1.177     www      12968: # Look at timestamp of caching
1.172     www      12969: # Everything is cached by the main uri, libraries are never directly cached
                   12970: #
1.428     albertel 12971:     if (!defined($liburi)) {
1.599     albertel 12972: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12973: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12974:     }
1.1362    raeburn  12975: 
                   12976: #
                   12977: # If the uri is for an external tool the file from
                   12978: # which metadata should be retrieved depends on whether
                   12979: # the tool had been configured to be gradable (set in the Course
                   12980: # Editor or Resource Editor).
                   12981: #
                   12982: # If a valid symb has been included as the third arg in the call
                   12983: # to &metadata() that can be used to retrieve the value of
                   12984: # parameter_0_gradable set for the resource, and included in the
                   12985: # uploaded map containing the tool. The value is retrieved via
                   12986: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12987: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12988: # is retrieved via &get().
                   12989: #
                   12990: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12991: # hiddenresource and encrypturl (during course initialization)
                   12992: # the map-level parameter for resource.0.gradable included in the 
                   12993: # uploaded map containing the tool will not yet have been stored
                   12994: # in the user_course_parms.db file for the user's session, so in 
                   12995: # this case fall back to retrieving gradable status from the
                   12996: # exttool_$marker.db file.
1.1362    raeburn  12997: #
                   12998: # In order to avoid an infinite loop, &metadata() will return
                   12999: # before a call to &EXT(), if the uri is for an external tool
                   13000: # and the $what for which metadata is being requested is
                   13001: # parameter_0_gradable or 0_gradable.
                   13002: #
                   13003: 
                   13004:     if ($uri =~ /ext\.tool$/) {
                   13005:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   13006:             return;
                   13007:         } else {
                   13008:             my ($checked,$use_passback);
                   13009:             if ($toolsymb ne '') {
                   13010:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  13011:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  13012:                     $checked = 1;
                   13013:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   13014:                         $use_passback = 1;
                   13015:                     }
                   13016:                 }
                   13017:             }
                   13018:             unless ($checked) {
                   13019:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   13020:                 $marker=~s/\D//g;
1.1363    raeburn  13021:                 if ($marker) {
1.1362    raeburn  13022:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   13023:                     $use_passback = $toolsettings{'gradable'};
                   13024:                 }
                   13025:             }
                   13026:             if ($use_passback) {
                   13027:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   13028:             } else {
                   13029:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   13030:             }
                   13031:         }
                   13032:     }
                   13033: 
1.428     albertel 13034:     {
1.1069    www      13035: # Imported parts would go here
1.1369    raeburn  13036:         my @origfiletagids=();
1.1069    www      13037:         my $importedparts=0;
1.1369    raeburn  13038: 
                   13039: # Imported responseids would go here
                   13040:         my $importedresponses=0;
1.172     www      13041: #
                   13042: # Is this a recursive call for a library?
                   13043: #
1.599     albertel 13044: #	if (! exists($metacache{$uri})) {
                   13045: #	    $metacache{$uri}={};
                   13046: #	}
1.924     albertel 13047: 	my $cachetime = 60*60;
1.171     www      13048:         if ($liburi) {
                   13049: 	    $liburi=&declutter($liburi);
                   13050:             $filename=$liburi;
1.401     bowersj2 13051:         } else {
1.599     albertel 13052: 	    &devalidate_cache_new('meta',$uri);
                   13053: 	    undef(%metaentry);
1.401     bowersj2 13054: 	}
1.140     www      13055:         my %metathesekeys=();
1.73      www      13056:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 13057: 	my $metastring;
1.1140    www      13058: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 13059: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 13060: 	    $metastring = 
1.929     albertel 13061: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 13062: 					  ('grade_target' => 'meta'));
                   13063: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  13064: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   13065:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 13066: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 13067: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 13068: 	    $metastring=&getfile($file);
1.489     albertel 13069: 	}
1.208     albertel 13070:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      13071:         my $token;
1.140     www      13072:         undef %metathesekeys;
1.71      www      13073:         while ($token=$parser->get_token) {
1.339     albertel 13074: 	    if ($token->[0] eq 'S') {
                   13075: 		if (defined($token->[2]->{'package'})) {
1.172     www      13076: #
                   13077: # This is a package - get package info
                   13078: #
1.339     albertel 13079: 		    my $package=$token->[2]->{'package'};
                   13080: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13081: 		    if (defined($token->[2]->{'id'})) { 
                   13082: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   13083: 		    }
1.599     albertel 13084: 		    if ($metaentry{':packages'}) {
                   13085: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 13086: 		    } else {
1.599     albertel 13087: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 13088: 		    }
1.736     albertel 13089: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 13090: 			my $part=$keyroot;
                   13091: 			$part=~s/^\_//;
1.736     albertel 13092: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   13093: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   13094: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 13095: 			    # ignore package.tab specified default values
                   13096:                             # here &package_tab_default() will fetch those
                   13097: 			    if ($subp eq 'default') { next; }
1.736     albertel 13098: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 13099: 			    my $unikey;
                   13100: 			    if ($pack =~ /_0$/) {
                   13101: 				$unikey='parameter_0_'.$name;
                   13102: 				$part=0;
                   13103: 			    } else {
                   13104: 				$unikey='parameter'.$keyroot.'_'.$name;
                   13105: 			    }
1.339     albertel 13106: 			    if ($subp eq 'display') {
                   13107: 				$value.=' [Part: '.$part.']';
                   13108: 			    }
1.599     albertel 13109: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 13110: 			    $metathesekeys{$unikey}=1;
1.599     albertel 13111: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13112: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 13113: 			    }
1.599     albertel 13114: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   13115: 				$metaentry{':'.$unikey}=
                   13116: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 13117: 			    }
1.339     albertel 13118: 			}
                   13119: 		    }
                   13120: 		} else {
1.172     www      13121: #
                   13122: # This is not a package - some other kind of start tag
1.339     albertel 13123: #
                   13124: 		    my $entry=$token->[1];
1.1068    www      13125: 		    my $unikey='';
1.175     www      13126: 
1.339     albertel 13127: 		    if ($entry eq 'import') {
1.175     www      13128: #
                   13129: # Importing a library here
1.339     albertel 13130: #
1.1067    www      13131:                         my $location=$parser->get_text('/import');
                   13132:                         my $dir=$filename;
                   13133:                         $dir=~s|[^/]*$||;
                   13134:                         $location=&filelocation($dir,$location);
1.1369    raeburn  13135: 
                   13136:                         my $importid=$token->[2]->{'id'};
1.1068    www      13137:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  13138: #
                   13139: # Check metadata for imported file to
                   13140: # see if it contained response items
                   13141: #
1.1372    raeburn  13142:                         my ($origfile,@libfilekeys);
1.1370    raeburn  13143:                         my %currmetaentry = %metaentry;
1.1372    raeburn  13144:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   13145:                                                            $depthcount+1));
                   13146:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   13147:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   13148:                                                              undef,$depthcount+1);
                   13149:                             if ($libresponseorder ne '') {
                   13150:                                 if ($#origfiletagids<0) {
                   13151:                                     undef(%importedrespids);
                   13152:                                     undef(%importedpartids);
                   13153:                                 }
1.1373    raeburn  13154:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   13155:                                 if (@respids) {
                   13156:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   13157:                                 }
                   13158:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  13159:                                     $importedresponses = 1;
1.1369    raeburn  13160: # We need to get the original file and the imported file to get the response order correct
                   13161: # Load and inspect original file
1.1372    raeburn  13162:                                     if ($#origfiletagids<0) {
                   13163:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13164:                                         $origfile=&getfile($origfilelocation);
                   13165:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13166:                                     }
1.1369    raeburn  13167:                                 }
                   13168:                             }
                   13169:                         }
1.1370    raeburn  13170: # Do not overwrite contents of %metaentry hash for resource itself with 
                   13171: # hash populated for imported library file
                   13172:                         %metaentry = %currmetaentry;
                   13173:                         undef(%currmetaentry);
1.1374    raeburn  13174:                         if ($importmode eq 'part') {
1.1068    www      13175: # Import as part(s)
1.1069    www      13176:                            $importedparts=1;
                   13177: # We need to get the original file and the imported file to get the part order correct
                   13178: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  13179: # Load and inspect original file if we didn't do that already
                   13180:                            if ($#origfiletagids<0) {
                   13181:                                undef(%importedrespids);
                   13182:                                undef(%importedpartids);
                   13183:                                if ($origfile eq '') {
                   13184:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13185:                                    $origfile=&getfile($origfilelocation);
                   13186:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13187:                                }
1.1070    www      13188:                            }
1.1372    raeburn  13189:                            my @impfilepartids;
                   13190: # If <partorder> tag is included in metadata for the imported file
                   13191: # get the parts in the imported file from that.
                   13192:                            if (grep(/^partorder$/,@libfilekeys)) {
                   13193:                                %currmetaentry = %metaentry;
                   13194:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13195:                                                             $depthcount+1);
                   13196:                                %metaentry = %currmetaentry;
                   13197:                                undef(%currmetaentry);
                   13198:                                if ($libpartorder ne '') {
                   13199:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   13200:                                }
                   13201:                            } else {
                   13202: # If no <partorder> tag available, load and inspect imported file
                   13203:                                my $impfile=&getfile($location);
                   13204:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13205:                            }
1.1069    www      13206:                            if ($#impfilepartids>=0) {
                   13207: # This problem had parts
1.1070    www      13208:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      13209:                            } else {
                   13210: # Importing by turning a single problem into a problem part
                   13211: # It gets the import-tags ID as part-ID
                   13212:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      13213:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      13214:                            }
1.1068    www      13215:                         } else {
1.1374    raeburn  13216: # Import as problem or as normal import
                   13217:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13218:                             unless ($importmode eq 'problem') {
1.1068    www      13219: # Normal import
1.1374    raeburn  13220:                                 if (defined($token->[2]->{'id'})) {
                   13221:                                     $unikey.='_'.$token->[2]->{'id'};
                   13222:                                 }
                   13223:                             }
                   13224: # Check metadata for imported file to
                   13225: # see if it contained parts
                   13226:                             if (grep(/^partorder$/,@libfilekeys)) {
                   13227:                                 %currmetaentry = %metaentry;
                   13228:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13229:                                                              $depthcount+1);
                   13230:                                 %metaentry = %currmetaentry;
                   13231:                                 undef(%currmetaentry);
                   13232:                                 if ($libpartorder ne '') {
                   13233:                                     $importedparts = 1;
                   13234:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   13235:                                 }
                   13236:                             }
1.1067    www      13237:                         }
1.339     albertel 13238: 			if ($depthcount<20) {
1.736     albertel 13239: 			    my $metadata = 
1.1362    raeburn  13240: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 13241: 					  $depthcount+1);
                   13242: 			    foreach my $meta (split(',',$metadata)) {
                   13243: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   13244: 				$metathesekeys{$meta}=1;
1.339     albertel 13245: 			    }
1.1068    www      13246:                         }
1.1067    www      13247: 		    } else {
                   13248: #
                   13249: # Not importing, some other kind of non-package, non-library start tag
                   13250: # 
                   13251:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13252:                         if (defined($token->[2]->{'id'})) {
                   13253:                             $unikey.='_'.$token->[2]->{'id'};
                   13254:                         }
1.339     albertel 13255: 			if (defined($token->[2]->{'name'})) { 
                   13256: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13257: 			}
                   13258: 			$metathesekeys{$unikey}=1;
1.736     albertel 13259: 			foreach my $param (@{$token->[3]}) {
                   13260: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13261: 				$token->[2]->{$param};
1.339     albertel 13262: 			}
                   13263: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13264: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13265: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13266: 		 # only ws inside the tag, and not in default, so use default
                   13267: 		 # as value
1.599     albertel 13268: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13269: 			} elsif ( $internaltext =~ /\S/ ) {
                   13270: 		  # something interesting inside the tag
                   13271: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13272: 			} else {
1.908     albertel 13273: 		  # no interesting values, don't set a default
1.339     albertel 13274: 			}
1.172     www      13275: # end of not-a-package not-a-library import
1.339     albertel 13276: 		    }
1.172     www      13277: # end of not-a-package start tag
1.339     albertel 13278: 		}
1.172     www      13279: # the next is the end of "start tag"
1.339     albertel 13280: 	    }
                   13281: 	}
1.483     albertel 13282: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13283: 	$extension = lc($extension);
                   13284: 	if ($extension eq 'htm') { $extension='html'; }
                   13285: 
1.737     albertel 13286: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13287: 	    #no specific packages #how's our extension
                   13288: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13289: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13290: 					 \%metathesekeys);
                   13291: 	}
1.883     albertel 13292: 
                   13293: 	if (!exists($metaentry{':packages'})
                   13294: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13295: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13296: 		#no specific packages well let's get default then
                   13297: 		if ($key!~/^default&/) { next; }
1.488     albertel 13298: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13299: 					     \%metathesekeys);
                   13300: 	    }
                   13301: 	}
1.338     www      13302: # are there custom rights to evaluate
1.599     albertel 13303: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13304: 
1.338     www      13305:     #
                   13306:     # Importing a rights file here
1.339     albertel 13307:     #
                   13308: 	    unless ($depthcount) {
1.599     albertel 13309: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13310: 		my $dir=$filename;
                   13311: 		$dir=~s|[^/]*$||;
                   13312: 		$location=&filelocation($dir,$location);
1.736     albertel 13313: 		my $rights_metadata =
1.1362    raeburn  13314: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13315: 			      $depthcount+1);
                   13316: 		foreach my $rights (split(',',$rights_metadata)) {
                   13317: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13318: 		    $metathesekeys{$rights}=1;
1.339     albertel 13319: 		}
                   13320: 	    }
                   13321: 	}
1.737     albertel 13322: 	# uniqifiy package listing
                   13323: 	my %seen;
                   13324: 	my @uniq_packages =
                   13325: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   13326: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   13327: 
1.1369    raeburn  13328:         if (($importedresponses) || ($importedparts)) {
                   13329:             if ($importedparts) {
1.1070    www      13330: # We had imported parts and need to rebuild partorder
1.1369    raeburn  13331:                 $metaentry{':partorder'}='';
                   13332:                 $metathesekeys{'partorder'}=1;
                   13333:             }
                   13334:             if ($importedresponses) {
                   13335: # We had imported responses and need to rebuil responseorder
                   13336:                 $metaentry{':responseorder'}='';
                   13337:                 $metathesekeys{'responseorder'}=1;
                   13338:             }
                   13339:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   13340:                 my $origid = $origfiletagids[$index+1];
                   13341:                 if ($origfiletagids[$index] eq 'part') {
                   13342: # Original part, part of the problem
                   13343:                     if ($importedparts) {
                   13344:                         $metaentry{':partorder'}.=','.$origid;
                   13345:                     }
                   13346:                 } elsif ($origfiletagids[$index] eq 'import') {
                   13347:                     if ($importedparts) {
                   13348: # We have imported parts at this position
1.1373    raeburn  13349:                         if ($importedpartids{$origid} ne '') {
                   13350:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   13351:                         }
1.1369    raeburn  13352:                     }
                   13353:                     if ($importedresponses) {
                   13354: # We have imported responses at this position
1.1373    raeburn  13355:                         if ($importedrespids{$origid} ne '') {
                   13356:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  13357:                         }
                   13358:                     }
                   13359:                 } else {
                   13360: # Original response item, part of the problem
                   13361:                     if ($importedresponses) {
                   13362:                         $metaentry{':responseorder'}.=','.$origid;
                   13363:                     }
                   13364:                 }
                   13365:             }
                   13366:             if ($importedparts) {
                   13367:                 $metaentry{':partorder'}=~s/^\,//;
                   13368:             }
                   13369:             if ($importedresponses) {
                   13370:                 $metaentry{':responseorder'}=~s/^\,//;
                   13371:             }
1.1070    www      13372:         }
1.737     albertel 13373: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13374: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  13375: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  13376:         unless ($liburi) {
                   13377: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   13378:         }
1.177     www      13379: # this is the end of "was not already recently cached
1.71      www      13380:     }
1.599     albertel 13381:     return $metaentry{':'.$what};
1.261     albertel 13382: }
                   13383: 
1.488     albertel 13384: sub metadata_create_package_def {
1.483     albertel 13385:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13386:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13387:     if ($subp eq 'default') { next; }
                   13388:     
1.599     albertel 13389:     if (defined($metaentry{':packages'})) {
                   13390: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13391:     } else {
1.599     albertel 13392: 	$metaentry{':packages'}=$package;
1.483     albertel 13393:     }
                   13394:     my $value=$packagetab{$key};
                   13395:     my $unikey;
                   13396:     $unikey='parameter_0_'.$name;
1.599     albertel 13397:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13398:     $$metathesekeys{$unikey}=1;
1.599     albertel 13399:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13400: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13401:     }
1.599     albertel 13402:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13403: 	$metaentry{':'.$unikey}=
                   13404: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13405:     }
                   13406: }
                   13407: 
1.261     albertel 13408: sub metadata_generate_part0 {
                   13409:     my ($metadata,$metacache,$uri) = @_;
                   13410:     my %allnames;
1.737     albertel 13411:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13412: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13413: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13414: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13415: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13416: 	    $allnames{$name}=$part;
                   13417: 	  }
                   13418: 	}
                   13419:     }
                   13420:     foreach my $name (keys(%allnames)) {
                   13421:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13422:       my $key=":parameter_0_$name";
1.261     albertel 13423:       $$metacache{"$key.part"}='0';
                   13424:       $$metacache{"$key.name"}=$name;
1.428     albertel 13425:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13426: 					   $allnames{$name}.'_'.$name.
                   13427: 					   '.type'};
1.428     albertel 13428:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13429: 			     '.display'};
1.644     www      13430:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13431:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13432:       $$metacache{"$key.display"}=$olddis;
                   13433:     }
1.71      www      13434: }
                   13435: 
1.764     albertel 13436: # ------------------------------------------------------ Devalidate title cache
                   13437: 
                   13438: sub devalidate_title_cache {
                   13439:     my ($url)=@_;
                   13440:     if (!$env{'request.course.id'}) { return; }
                   13441:     my $symb=&symbread($url);
                   13442:     if (!$symb) { return; }
                   13443:     my $key=$env{'request.course.id'}."\0".$symb;
                   13444:     &devalidate_cache_new('title',$key);
                   13445: }
                   13446: 
1.1014    droeschl 13447: # ------------------------------------------------- Get the title of a course
                   13448: 
                   13449: sub current_course_title {
                   13450:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13451: }
1.301     www      13452: # ------------------------------------------------- Get the title of a resource
                   13453: 
                   13454: sub gettitle {
                   13455:     my $urlsymb=shift;
                   13456:     my $symb=&symbread($urlsymb);
1.534     albertel 13457:     if ($symb) {
1.620     albertel 13458: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13459: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13460: 	if (defined($cached)) { 
                   13461: 	    return $result;
                   13462: 	}
1.534     albertel 13463: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13464: 	my $title='';
1.907     albertel 13465: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13466: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13467: 	} else {
                   13468: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13469: 		    &GDBM_READER(),0640)) {
                   13470: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13471: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13472: 		untie(%bighash);
                   13473: 	    }
1.534     albertel 13474: 	}
                   13475: 	$title=~s/\&colon\;/\:/gs;
                   13476: 	if ($title) {
1.1159    www      13477: # Remember both $symb and $title for dynamic metadata
                   13478:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13479:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13480: # Cache this title and then return it
1.599     albertel 13481: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13482: 	}
                   13483: 	$urlsymb=$url;
                   13484:     }
                   13485:     my $title=&metadata($urlsymb,'title');
                   13486:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13487:     return $title;
1.301     www      13488: }
1.613     albertel 13489: 
1.614     albertel 13490: sub get_slot {
                   13491:     my ($which,$cnum,$cdom)=@_;
                   13492:     if (!$cnum || !$cdom) {
1.790     albertel 13493: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13494: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13495: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13496:     }
1.703     albertel 13497:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13498:     my %slotinfo;
                   13499:     if (exists($remembered{$key})) {
                   13500: 	$slotinfo{$which} = $remembered{$key};
                   13501:     } else {
                   13502: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13503: 	&Apache::lonhomework::showhash(%slotinfo);
                   13504: 	my ($tmp)=keys(%slotinfo);
                   13505: 	if ($tmp=~/^error:/) { return (); }
                   13506: 	$remembered{$key} = $slotinfo{$which};
                   13507:     }
1.616     albertel 13508:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13509: 	return %{$slotinfo{$which}};
                   13510:     }
                   13511:     return $slotinfo{$which};
1.614     albertel 13512: }
1.1150    raeburn  13513: 
                   13514: sub get_reservable_slots {
                   13515:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13516:     my $now = time;
                   13517:     my $reservable_info;
                   13518:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13519:     if (exists($remembered{$key})) {
                   13520:         $reservable_info = $remembered{$key};
                   13521:     } else {
                   13522:         my %resv;
                   13523:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13524:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13525:         $reservable_info = \%resv;
                   13526:         $remembered{$key} = $reservable_info;
                   13527:     }
                   13528:     return $reservable_info;
                   13529: }
                   13530: 
                   13531: sub get_course_slots {
                   13532:     my ($cnum,$cdom) = @_;
                   13533:     my $hashid=$cnum.':'.$cdom;
                   13534:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13535:     if (defined($cached)) {
                   13536:         if (ref($result) eq 'HASH') {
                   13537:             return %{$result};
                   13538:         }
                   13539:     } else {
                   13540:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13541:         my ($tmp) = keys(%slots);
                   13542:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  13543:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13544:             return %slots;
                   13545:         }
                   13546:     }
                   13547:     return;
                   13548: }
                   13549: 
                   13550: sub devalidate_slots_cache {
                   13551:     my ($cnum,$cdom)=@_;
                   13552:     my $hashid=$cnum.':'.$cdom;
                   13553:     &devalidate_cache_new('allslots',$hashid);
                   13554: }
                   13555: 
1.1181    raeburn  13556: sub get_coursechange {
                   13557:     my ($cdom,$cnum) = @_;
                   13558:     if ($cdom eq '' || $cnum eq '') {
                   13559:         return unless ($env{'request.course.id'});
                   13560:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13561:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13562:     }
                   13563:     my $hashid=$cdom.'_'.$cnum;
                   13564:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13565:     if ((defined($cached)) && ($change ne '')) {
                   13566:         return $change;
                   13567:     } else {
                   13568:         my %crshash;
                   13569:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13570:         if ($crshash{'internal.contentchange'} eq '') {
                   13571:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13572:             if ($change eq '') {
                   13573:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13574:                 $change = $crshash{'internal.created'};
                   13575:             }
                   13576:         } else {
                   13577:             $change = $crshash{'internal.contentchange'};
                   13578:         }
                   13579:         my $cachetime = 600;
                   13580:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13581:     }
                   13582:     return $change;
                   13583: }
                   13584: 
                   13585: sub devalidate_coursechange_cache {
                   13586:     my ($cnum,$cdom)=@_;
                   13587:     my $hashid=$cnum.':'.$cdom;
                   13588:     &devalidate_cache_new('crschange',$hashid);
                   13589: }
                   13590: 
1.31      www      13591: # ------------------------------------------------- Update symbolic store links
                   13592: 
                   13593: sub symblist {
                   13594:     my ($mapname,%newhash)=@_;
1.438     www      13595:     $mapname=&deversion(&declutter($mapname));
1.31      www      13596:     my %hash;
1.620     albertel 13597:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13598:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13599:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13600: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13601: 		next if ($url eq 'last_known'
                   13602: 			 && $env{'form.no_update_last_known'});
                   13603: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13604: 						    $newhash{$url}->[1],
                   13605: 						    $newhash{$url}->[0]);
1.191     harris41 13606:             }
1.31      www      13607:             if (untie(%hash)) {
                   13608: 		return 'ok';
                   13609:             }
                   13610:         }
                   13611:     }
                   13612:     return 'error';
1.212     www      13613: }
                   13614: 
                   13615: # --------------------------------------------------------------- Verify a symb
                   13616: 
                   13617: sub symbverify {
1.1190    raeburn  13618:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13619:     my $thisfn=$thisurl;
1.439     www      13620:     $thisfn=&declutter($thisfn);
1.215     www      13621: # direct jump to resource in page or to a sequence - will construct own symbs
                   13622:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13623: # check URL part
1.409     www      13624:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13625: 
1.431     www      13626:     unless ($url eq $thisfn) { return 0; }
1.213     www      13627: 
1.216     www      13628:     $symb=&symbclean($symb);
1.510     www      13629:     $thisurl=&deversion($thisurl);
1.439     www      13630:     $thisfn=&deversion($thisfn);
1.213     www      13631: 
                   13632:     my %bighash;
                   13633:     my $okay=0;
1.431     www      13634: 
1.620     albertel 13635:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13636:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13637:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13638:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  13639:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13640:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13641:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13642:             }
                   13643:         }
                   13644:         my $ids;
1.1419    raeburn  13645:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13646:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  13647:         } else {
                   13648:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13649:         }
1.1102    raeburn  13650:         unless ($ids) {
                   13651:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   13652:             $ids=$bighash{$idkey};
1.216     www      13653:         }
                   13654:         if ($ids) {
                   13655: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  13656:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  13657:                 $symb =~ s/\?.+$//;
1.1202    raeburn  13658:             }
1.800     albertel 13659: 	    foreach my $id (split(/\,/,$ids)) {
                   13660: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13661:                if (
                   13662:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  13663:    eq $symb) {
                   13664:                    if (ref($encstate)) {
                   13665:                        $$encstate = $bighash{'encrypted_'.$id};
                   13666:                    }
1.620     albertel 13667: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  13668: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   13669:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  13670: 		       $okay=1;
1.1202    raeburn  13671:                        last;
1.582     albertel 13672: 		   }
                   13673: 	       }
1.216     www      13674: 	   }
                   13675:         }
1.213     www      13676: 	untie(%bighash);
                   13677:     }
                   13678:     return $okay;
1.31      www      13679: }
                   13680: 
1.210     www      13681: # --------------------------------------------------------------- Clean-up symb
                   13682: 
                   13683: sub symbclean {
                   13684:     my $symb=shift;
1.568     albertel 13685:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13686: # remove version from map
                   13687:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13688: 
1.210     www      13689: # remove version from URL
                   13690:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13691: 
1.507     www      13692: # remove wrapper
                   13693: 
1.510     www      13694:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13695:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13696:     return $symb;
1.409     www      13697: }
                   13698: 
                   13699: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13700: 
                   13701: sub encode_symb {
                   13702:     my ($map,$resid,$url)=@_;
                   13703:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13704: }
1.409     www      13705: 
                   13706: sub decode_symb {
1.568     albertel 13707:     my $symb=shift;
                   13708:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13709:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13710:     return (&fixversion($map),$resid,&fixversion($url));
                   13711: }
                   13712: 
                   13713: sub fixversion {
                   13714:     my $fn=shift;
1.609     banghart 13715:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13716:     my %bighash;
                   13717:     my $uri=&clutter($fn);
1.620     albertel 13718:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13719: # is this cached?
1.599     albertel 13720:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13721:     if (defined($cached)) { return $result; }
                   13722: # unfortunately not cached, or expired
1.620     albertel 13723:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13724: 	    &GDBM_READER(),0640)) {
                   13725:  	if ($bighash{'version_'.$uri}) {
                   13726:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13727:  	    unless (($version eq 'mostrecent') || 
                   13728: 		    ($version==&getversion($uri))) {
1.440     www      13729:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13730:  	    }
                   13731:  	}
                   13732:  	untie %bighash;
1.413     www      13733:     }
1.599     albertel 13734:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13735: }
                   13736: 
                   13737: sub deversion {
                   13738:     my $url=shift;
                   13739:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13740:     return $url;
1.210     www      13741: }
                   13742: 
1.31      www      13743: # ------------------------------------------------------ Return symb list entry
                   13744: 
                   13745: sub symbread {
1.1424    raeburn  13746:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  13747:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  13748:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  13749:     if (defined($env{$cache_str})) {
1.1424    raeburn  13750:         unless (ref($possibles) eq 'HASH') {
                   13751:             if ($ignorecachednull) {
                   13752:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13753:             } else {
                   13754:                 return $env{$cache_str};
                   13755:             }
1.1282    raeburn  13756:         }
                   13757:     }
1.242     www      13758: # no filename provided? try from environment
1.1265    raeburn  13759:     unless ($thisfn) {
1.620     albertel 13760:         if ($env{'request.symb'}) {
1.1427    raeburn  13761:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13762: 	}
1.620     albertel 13763: 	$thisfn=$env{'request.filename'};
1.44      www      13764:     }
1.569     albertel 13765:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13766: # is that filename actually a symb? Verify, clean, and return
                   13767:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13768: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  13769: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13770: 	}
1.242     www      13771:     }
1.44      www      13772:     $thisfn=declutter($thisfn);
1.31      www      13773:     my %hash;
1.37      www      13774:     my %bighash;
                   13775:     my $syval='';
1.620     albertel 13776:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427    raeburn  13777:         unless ($ignoresymbdb) {
1.1424    raeburn  13778:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13779:                           &GDBM_READER(),0640)) {
1.1487    raeburn  13780: 	        $syval=$hash{$thisfn};
1.1424    raeburn  13781:                 untie(%hash);
                   13782:             }
1.1427    raeburn  13783:             if ($syval && $checkforblock) {
                   13784:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  13785:                 if (@blockers) {
                   13786:                     $syval='';
                   13787:                 }
                   13788:             }
1.37      www      13789:         }
                   13790: # ---------------------------------------------------------- There was an entry
                   13791:         if ($syval) {
1.601     albertel 13792: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13793: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13794: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13795: 		    #return $env{$cache_str}='';
1.601     albertel 13796: 		#}    
                   13797: 		#$syval.=$1;
                   13798: 	    #}
1.37      www      13799:         } else {
                   13800: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13801:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13802:                             &GDBM_READER(),0640)) {
1.37      www      13803: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13804:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13805:               unless ($ids) { 
                   13806:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13807:               }
                   13808:               unless ($ids) {
                   13809: # alias?
                   13810: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13811:               }
1.37      www      13812:               if ($ids) {
                   13813: # ------------------------------------------------------------------- Has ID(s)
                   13814:                  my @possibilities=split(/\,/,$ids);
1.39      www      13815:                  if ($#possibilities==0) {
                   13816: # ----------------------------------------------- There is only one possibility
1.37      www      13817: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13818: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13819: 						    $resid,$thisfn);
1.1282    raeburn  13820:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  13821:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13822:                              $possibles->{$syval} = 1;
                   13823:                          }
1.1282    raeburn  13824:                      }
                   13825:                      if ($checkforblock) {
1.1424    raeburn  13826:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  13827:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  13828:                              if (@blockers) {
                   13829:                                  $syval = '';
1.1425    raeburn  13830:                                  untie(%bighash);
                   13831:                                  return $env{$cache_str}='';
1.1424    raeburn  13832:                              }
1.1282    raeburn  13833:                          }
                   13834:                      }
                   13835:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13836: # ------------------------------------------ There is more than one possibility
                   13837:                      my $realpossible=0;
1.800     albertel 13838:                      foreach my $id (@possibilities) {
                   13839: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13840:                          my $canaccess;
                   13841:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13842:                              $canaccess = 1;
                   13843:                          } else { 
                   13844:                              $canaccess = &allowed('bre',$file);
                   13845:                          }
                   13846:                          if ($canaccess) {
                   13847:          		     my ($mapid,$resid)=split(/\./,$id);
                   13848:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13849:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13850: 						             $resid,$thisfn);
1.1424    raeburn  13851:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  13852:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  13853:                                  if ($checkforblock) {
1.1426    raeburn  13854:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  13855:                                      if (@blockers > 0) {
                   13856:                                          $syval = '';
                   13857:                                      } else {
1.1282    raeburn  13858:                                          $syval = $poss_syval;
                   13859:                                          $realpossible++;
                   13860:                                      }
                   13861:                                  } else {
                   13862:                                      $syval = $poss_syval;
                   13863:                                      $realpossible++;
                   13864:                                  }
1.1424    raeburn  13865:                                  if ($syval) {
                   13866:                                      if (ref($possibles) eq 'HASH') {
                   13867:                                          $possibles->{$syval} = 1;
                   13868:                                      }
                   13869:                                  }
1.1282    raeburn  13870:                              }
1.39      www      13871: 			 }
1.191     harris41 13872:                      }
1.39      www      13873: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13874:                  } else {
                   13875:                      $syval='';
1.37      www      13876:                  }
                   13877: 	      }
1.1282    raeburn  13878:               untie(%bighash);
1.481     raeburn  13879:            }
1.31      www      13880:         }
1.62      www      13881:         if ($syval) {
1.1427    raeburn  13882: 	    return $env{$cache_str}=$syval;
1.62      www      13883:         }
1.31      www      13884:     }
1.949     raeburn  13885:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13886:     return $env{$cache_str}='';
1.31      www      13887: }
                   13888: 
                   13889: # ---------------------------------------------------------- Return random seed
                   13890: 
1.32      www      13891: sub numval {
                   13892:     my $txt=shift;
                   13893:     $txt=~tr/A-J/0-9/;
                   13894:     $txt=~tr/a-j/0-9/;
                   13895:     $txt=~tr/K-T/0-9/;
                   13896:     $txt=~tr/k-t/0-9/;
                   13897:     $txt=~tr/U-Z/0-5/;
                   13898:     $txt=~tr/u-z/0-5/;
                   13899:     $txt=~s/\D//g;
1.564     albertel 13900:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13901:     return int($txt);
1.368     albertel 13902: }
                   13903: 
1.484     albertel 13904: sub numval2 {
                   13905:     my $txt=shift;
                   13906:     $txt=~tr/A-J/0-9/;
                   13907:     $txt=~tr/a-j/0-9/;
                   13908:     $txt=~tr/K-T/0-9/;
                   13909:     $txt=~tr/k-t/0-9/;
                   13910:     $txt=~tr/U-Z/0-5/;
                   13911:     $txt=~tr/u-z/0-5/;
                   13912:     $txt=~s/\D//g;
                   13913:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13914:     my $total;
                   13915:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13916:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13917:     return int($total);
                   13918: }
                   13919: 
1.575     albertel 13920: sub numval3 {
                   13921:     use integer;
                   13922:     my $txt=shift;
                   13923:     $txt=~tr/A-J/0-9/;
                   13924:     $txt=~tr/a-j/0-9/;
                   13925:     $txt=~tr/K-T/0-9/;
                   13926:     $txt=~tr/k-t/0-9/;
                   13927:     $txt=~tr/U-Z/0-5/;
                   13928:     $txt=~tr/u-z/0-5/;
                   13929:     $txt=~s/\D//g;
                   13930:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13931:     my $total;
                   13932:     foreach my $val (@txts) { $total+=$val; }
                   13933:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13934:     return $total;
                   13935: }
                   13936: 
1.675     albertel 13937: sub digest {
                   13938:     my ($data)=@_;
                   13939:     my $digest=&Digest::MD5::md5($data);
                   13940:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13941:     my ($e,$f);
                   13942:     {
                   13943:         use integer;
                   13944:         $e=($a+$b);
                   13945:         $f=($c+$d);
                   13946:         if ($_64bit) {
                   13947:             $e=(($e<<32)>>32);
                   13948:             $f=(($f<<32)>>32);
                   13949:         }
                   13950:     }
                   13951:     if (wantarray) {
                   13952: 	return ($e,$f);
                   13953:     } else {
                   13954: 	my $g;
                   13955: 	{
                   13956: 	    use integer;
                   13957: 	    $g=($e+$f);
                   13958: 	    if ($_64bit) {
                   13959: 		$g=(($g<<32)>>32);
                   13960: 	    }
                   13961: 	}
                   13962: 	return $g;
                   13963:     }
                   13964: }
                   13965: 
1.368     albertel 13966: sub latest_rnd_algorithm_id {
1.675     albertel 13967:     return '64bit5';
1.366     albertel 13968: }
1.32      www      13969: 
1.503     albertel 13970: sub get_rand_alg {
                   13971:     my ($courseid)=@_;
1.790     albertel 13972:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13973:     if ($courseid) {
1.620     albertel 13974: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13975:     }
                   13976:     return &latest_rnd_algorithm_id();
                   13977: }
                   13978: 
1.562     albertel 13979: sub validCODE {
                   13980:     my ($CODE)=@_;
                   13981:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13982:     return 0;
                   13983: }
                   13984: 
1.491     albertel 13985: sub getCODE {
1.620     albertel 13986:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13987:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13988: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13989: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13990: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13991:     }
                   13992:     return undef;
                   13993: }
1.1133    foxr     13994: #
                   13995: #  Determines the random seed for a specific context:
                   13996: #
                   13997: # parameters:
                   13998: #   symb      - in course context the symb for the seed.
                   13999: #   course_id - The course id of the form domain_coursenum.
                   14000: #   domain    - Domain for the user.
                   14001: #   course    - Course for the user.
                   14002: #   cenv      - environment of the course.
                   14003: #
                   14004: # NOTE:
                   14005: #   All parameters are picked out of the environment if missing
                   14006: #   or not defined.
                   14007: #   If a symb cannot be determined the current time is used instead.
                   14008: #
                   14009: #  For a given well defined symb, courside, domain, username,
                   14010: #  and course environment, the seed is reproducible.
                   14011: #
1.31      www      14012: sub rndseed {
1.1133    foxr     14013:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 14014:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 14015:     if (!defined($symb)) {
1.366     albertel 14016: 	unless ($symb=$wsymb) { return time; }
                   14017:     }
1.1146    foxr     14018:     if (!defined $courseid) { 
                   14019: 	$courseid=$wcourseid; 
                   14020:     }
                   14021:     if (!defined $domain) { $domain=$wdomain; }
                   14022:     if (!defined $username) { $username=$wusername }
1.1133    foxr     14023: 
                   14024:     my $which;
                   14025:     if (defined($cenv->{'rndseed'})) {
                   14026: 	$which = $cenv->{'rndseed'};
                   14027:     } else {
                   14028: 	$which =&get_rand_alg($courseid);
                   14029:     }
1.491     albertel 14030:     if (defined(&getCODE())) {
1.1133    foxr     14031: 
1.675     albertel 14032: 	if ($which eq '64bit5') {
                   14033: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   14034: 	} elsif ($which eq '64bit4') {
1.575     albertel 14035: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   14036: 	} else {
                   14037: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   14038: 	}
1.675     albertel 14039:     } elsif ($which eq '64bit5') {
                   14040: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 14041:     } elsif ($which eq '64bit4') {
                   14042: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 14043:     } elsif ($which eq '64bit3') {
                   14044: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 14045:     } elsif ($which eq '64bit2') {
                   14046: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 14047:     } elsif ($which eq '64bit') {
                   14048: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   14049:     }
                   14050:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   14051: }
                   14052: 
                   14053: sub rndseed_32bit {
                   14054:     my ($symb,$courseid,$domain,$username)=@_;
                   14055:     {
                   14056: 	use integer;
                   14057: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   14058: 	my $symbseed=numval($symb) << 22;
                   14059: 	my $namechck=unpack("%32C*",$username) << 17;
                   14060: 	my $nameseed=numval($username) << 12;
                   14061: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   14062: 	my $courseseed=unpack("%32C*",$courseid);
                   14063: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 14064: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14065: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14066: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 14067: 	return $num;
                   14068:     }
                   14069: }
                   14070: 
                   14071: sub rndseed_64bit {
                   14072:     my ($symb,$courseid,$domain,$username)=@_;
                   14073:     {
                   14074: 	use integer;
                   14075: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   14076: 	my $symbseed=numval($symb) << 10;
                   14077: 	my $namechck=unpack("%32S*",$username);
                   14078: 	
                   14079: 	my $nameseed=numval($username) << 21;
                   14080: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   14081: 	my $courseseed=unpack("%32S*",$courseid);
                   14082: 	
                   14083: 	my $num1=$symbchck+$symbseed+$namechck;
                   14084: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14085: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14086: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14087: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 14088: 	return "$num1,$num2";
1.155     albertel 14089:     }
1.366     albertel 14090: }
                   14091: 
1.443     albertel 14092: sub rndseed_64bit2 {
                   14093:     my ($symb,$courseid,$domain,$username)=@_;
                   14094:     {
                   14095: 	use integer;
                   14096: 	# strings need to be an even # of cahracters long, it it is odd the
                   14097:         # last characters gets thrown away
                   14098: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14099: 	my $symbseed=numval($symb) << 10;
                   14100: 	my $namechck=unpack("%32S*",$username.' ');
                   14101: 	
                   14102: 	my $nameseed=numval($username) << 21;
1.501     albertel 14103: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14104: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14105: 	
                   14106: 	my $num1=$symbchck+$symbseed+$namechck;
                   14107: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14108: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14109: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 14110: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 14111: 	return "$num1,$num2";
                   14112:     }
                   14113: }
                   14114: 
                   14115: sub rndseed_64bit3 {
                   14116:     my ($symb,$courseid,$domain,$username)=@_;
                   14117:     {
                   14118: 	use integer;
                   14119: 	# strings need to be an even # of cahracters long, it it is odd the
                   14120:         # last characters gets thrown away
                   14121: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14122: 	my $symbseed=numval2($symb) << 10;
                   14123: 	my $namechck=unpack("%32S*",$username.' ');
                   14124: 	
                   14125: 	my $nameseed=numval2($username) << 21;
1.443     albertel 14126: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14127: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14128: 	
                   14129: 	my $num1=$symbchck+$symbseed+$namechck;
                   14130: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14131: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14132: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 14133: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14134: 	
1.503     albertel 14135: 	return "$num1:$num2";
1.443     albertel 14136:     }
                   14137: }
                   14138: 
1.575     albertel 14139: sub rndseed_64bit4 {
                   14140:     my ($symb,$courseid,$domain,$username)=@_;
                   14141:     {
                   14142: 	use integer;
                   14143: 	# strings need to be an even # of cahracters long, it it is odd the
                   14144:         # last characters gets thrown away
                   14145: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14146: 	my $symbseed=numval3($symb) << 10;
                   14147: 	my $namechck=unpack("%32S*",$username.' ');
                   14148: 	
                   14149: 	my $nameseed=numval3($username) << 21;
                   14150: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14151: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14152: 	
                   14153: 	my $num1=$symbchck+$symbseed+$namechck;
                   14154: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14155: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14156: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 14157: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14158: 	
1.575     albertel 14159: 	return "$num1:$num2";
                   14160:     }
                   14161: }
                   14162: 
1.675     albertel 14163: sub rndseed_64bit5 {
                   14164:     my ($symb,$courseid,$domain,$username)=@_;
                   14165:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   14166:     return "$num1:$num2";
                   14167: }
                   14168: 
1.366     albertel 14169: sub rndseed_CODE_64bit {
                   14170:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 14171:     {
1.366     albertel 14172: 	use integer;
1.443     albertel 14173: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 14174: 	my $symbseed=numval2($symb);
1.491     albertel 14175: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14176: 	my $CODEseed=numval(&getCODE());
1.443     albertel 14177: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 14178: 	my $num1=$symbseed+$CODEchck;
                   14179: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14180: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14181: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 14182: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14183: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 14184: 	return "$num1:$num2";
1.366     albertel 14185:     }
                   14186: }
                   14187: 
1.575     albertel 14188: sub rndseed_CODE_64bit4 {
                   14189:     my ($symb,$courseid,$domain,$username)=@_;
                   14190:     {
                   14191: 	use integer;
                   14192: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   14193: 	my $symbseed=numval3($symb);
                   14194: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14195: 	my $CODEseed=numval3(&getCODE());
                   14196: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14197: 	my $num1=$symbseed+$CODEchck;
                   14198: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14199: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14200: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14201: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14202: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14203: 	return "$num1:$num2";
                   14204:     }
                   14205: }
                   14206: 
1.675     albertel 14207: sub rndseed_CODE_64bit5 {
                   14208:     my ($symb,$courseid,$domain,$username)=@_;
                   14209:     my $code = &getCODE();
                   14210:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14211:     return "$num1:$num2";
                   14212: }
                   14213: 
1.366     albertel 14214: sub setup_random_from_rndseed {
                   14215:     my ($rndseed)=@_;
1.503     albertel 14216:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  14217:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14218:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14219:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14220:         } else {
                   14221:             &Math::Random::random_set_seed($num1,$num2);
                   14222:         }
1.366     albertel 14223:     } else {
                   14224: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14225:     }
1.36      albertel 14226: }
                   14227: 
1.474     albertel 14228: sub latest_receipt_algorithm_id {
1.835     albertel 14229:     return 'receipt3';
1.474     albertel 14230: }
                   14231: 
1.480     www      14232: sub recunique {
                   14233:     my $fucourseid=shift;
                   14234:     my $unique;
1.835     albertel 14235:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14236: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14237: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14238:     } else {
                   14239: 	$unique=$perlvar{'lonReceipt'};
                   14240:     }
                   14241:     return unpack("%32C*",$unique);
                   14242: }
                   14243: 
                   14244: sub recprefix {
                   14245:     my $fucourseid=shift;
                   14246:     my $prefix;
1.835     albertel 14247:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14248: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14249: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14250:     } else {
                   14251: 	$prefix=$perlvar{'lonHostID'};
                   14252:     }
                   14253:     return unpack("%32C*",$prefix);
                   14254: }
                   14255: 
1.76      www      14256: sub ireceipt {
1.474     albertel 14257:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14258: 
                   14259:     my $return =&recprefix($fucourseid).'-';
                   14260: 
                   14261:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14262: 	$env{'request.state'} eq 'construct') {
                   14263: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   14264: 	return $return;
                   14265:     }
                   14266: 
1.76      www      14267:     my $cuname=unpack("%32C*",$funame);
                   14268:     my $cudom=unpack("%32C*",$fudom);
                   14269:     my $cucourseid=unpack("%32C*",$fucourseid);
                   14270:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      14271:     my $cunique=&recunique($fucourseid);
1.474     albertel 14272:     my $cpart=unpack("%32S*",$part);
1.835     albertel 14273:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   14274: 
1.790     albertel 14275: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 14276: 			       
                   14277: 	$return.= ($cunique%$cuname+
                   14278: 		   $cunique%$cudom+
                   14279: 		   $cusymb%$cuname+
                   14280: 		   $cusymb%$cudom+
                   14281: 		   $cucourseid%$cuname+
                   14282: 		   $cucourseid%$cudom+
                   14283: 		   $cpart%$cuname+
                   14284: 		   $cpart%$cudom);
                   14285:     } else {
                   14286: 	$return.= ($cunique%$cuname+
                   14287: 		   $cunique%$cudom+
                   14288: 		   $cusymb%$cuname+
                   14289: 		   $cusymb%$cudom+
                   14290: 		   $cucourseid%$cuname+
                   14291: 		   $cucourseid%$cudom);
                   14292:     }
                   14293:     return $return;
1.76      www      14294: }
                   14295: 
                   14296: sub receipt {
1.474     albertel 14297:     my ($part)=@_;
1.790     albertel 14298:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14299:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14300: }
1.260     ng       14301: 
1.790     albertel 14302: sub whichuser {
                   14303:     my ($passedsymb)=@_;
                   14304:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14305:     if (defined($env{'form.grade_symb'})) {
                   14306: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14307: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14308: 	if (!$allowed &&
                   14309: 	    exists($env{'request.course.sec'}) &&
                   14310: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14311: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14312: 			      '/'.$env{'request.course.sec'});
                   14313: 	}
                   14314: 	if ($allowed) {
                   14315: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14316: 	    $courseid=$tmp_courseid;
                   14317: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14318: 	    ($name)=&get_env_multiple('form.grade_username');
                   14319: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14320: 	}
                   14321:     }
                   14322:     if (!$passedsymb) {
                   14323: 	$symb=&symbread();
                   14324:     } else {
                   14325: 	$symb=$passedsymb;
                   14326:     }
                   14327:     $courseid=$env{'request.course.id'};
                   14328:     $domain=$env{'user.domain'};
                   14329:     $name=$env{'user.name'};
                   14330:     if ($name eq 'public' && $domain eq 'public') {
                   14331: 	if (!defined($env{'form.username'})) {
                   14332: 	    $env{'form.username'}.=time.rand(10000000);
                   14333: 	}
                   14334: 	$name.=$env{'form.username'};
                   14335:     }
                   14336:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14337: 
                   14338: }
                   14339: 
1.36      albertel 14340: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14341: # returns either the contents of the file or 
                   14342: # -1 if the file doesn't exist
1.481     raeburn  14343: #
                   14344: # if the target is a file that was uploaded via DOCS, 
                   14345: # a check will be made to see if a current copy exists on the local server,
                   14346: # if it does this will be served, otherwise a copy will be retrieved from
                   14347: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14348: # the local server.   
1.472     albertel 14349: 
1.36      albertel 14350: sub getfile {
1.538     albertel 14351:     my ($file) = @_;
1.609     banghart 14352:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14353:     &repcopy($file);
                   14354:     return &readfile($file);
                   14355: }
                   14356: 
                   14357: sub repcopy_userfile {
                   14358:     my ($file)=@_;
1.1142    raeburn  14359:     my $londocroot = $perlvar{'lonDocRoot'};
                   14360:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14361:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14362:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14363: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14364:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14365:     if (-e "$file") {
1.828     www      14366: # we already have a local copy, check it out
1.538     albertel 14367: 	my @fileinfo = stat($file);
1.828     www      14368: 	my $rtncode;
                   14369: 	my $info;
1.538     albertel 14370: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14371: 	if ($lwpresp ne 'ok') {
1.828     www      14372: # there is no such file anymore, even though we had a local copy
1.482     albertel 14373: 	    if ($rtncode eq '404') {
1.538     albertel 14374: 		unlink($file);
1.482     albertel 14375: 	    }
                   14376: 	    return -1;
                   14377: 	}
                   14378: 	if ($info < $fileinfo[9]) {
1.828     www      14379: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14380: 	    return 'ok';
1.828     www      14381: 	} else {
                   14382: # the file is outdated, get rid of it
                   14383: 	    unlink($file);
1.482     albertel 14384: 	}
1.828     www      14385:     }
                   14386: # one way or the other, at this point, we don't have the file
                   14387: # construct the correct path for the file
                   14388:     my @parts = ($cdom,$cnum); 
                   14389:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14390: 	push @parts, split(/\//,$1);
                   14391:     }
                   14392:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14393:     foreach my $part (@parts) {
                   14394: 	$path .= '/'.$part;
                   14395: 	if (!-e $path) {
                   14396: 	    mkdir($path,0770);
1.482     albertel 14397: 	}
                   14398:     }
1.828     www      14399: # now the path exists for sure
                   14400: # get a user agent
                   14401:     my $transferfile=$file.'.in.transfer';
                   14402: # FIXME: this should flock
                   14403:     if (-e $transferfile) { return 'ok'; }
                   14404:     my $request;
                   14405:     $uri=~s/^\///;
1.980     raeburn  14406:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  14407:     my $hostname = &hostname($homeserver);
1.980     raeburn  14408:     my $protocol = $protocol{$homeserver};
                   14409:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14410:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  14411:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      14412: # did it work?
                   14413:     if ($response->is_error()) {
                   14414: 	unlink($transferfile);
                   14415: 	&logthis("Userfile repcopy failed for $uri");
                   14416: 	return -1;
                   14417:     }
                   14418: # worked, rename the transfer file
                   14419:     rename($transferfile,$file);
1.607     raeburn  14420:     return 'ok';
1.481     raeburn  14421: }
                   14422: 
1.517     albertel 14423: sub tokenwrapper {
                   14424:     my $uri=shift;
1.980     raeburn  14425:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14426:     $uri=~s|^/||;
1.620     albertel 14427:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14428:     my $token=$1;
1.552     albertel 14429:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14430:     if ($udom && $uname && $file) {
                   14431: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14432:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14433:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  14434:         my $hostname = &hostname($homeserver);
1.980     raeburn  14435:         my $protocol = $protocol{$homeserver};
                   14436:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14437:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14438:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14439:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14440:     } else {
                   14441:         return '/adm/notfound.html';
                   14442:     }
                   14443: }
                   14444: 
1.828     www      14445: # call with reqtype HEAD: get last modification time
                   14446: # call with reqtype GET: get the file contents
                   14447: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14448: #
1.481     raeburn  14449: sub getuploaded {
                   14450:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14451:     $uri=~s/^\///;
1.980     raeburn  14452:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  14453:     my $hostname = &hostname($homeserver);
1.980     raeburn  14454:     my $protocol = $protocol{$homeserver};
                   14455:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14456:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14457:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  14458:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  14459:     $$rtncode = $response->code;
1.482     albertel 14460:     if (! $response->is_success()) {
                   14461: 	return 'failed';
                   14462:     }      
                   14463:     if ($reqtype eq 'HEAD') {
1.486     www      14464: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14465:     } elsif ($reqtype eq 'GET') {
                   14466: 	$$info = $response->content;
1.472     albertel 14467:     }
1.482     albertel 14468:     return 'ok';
1.36      albertel 14469: }
                   14470: 
1.481     raeburn  14471: sub readfile {
                   14472:     my $file = shift;
                   14473:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14474:     my $fh;
1.1359    raeburn  14475:     open($fh,"<",$file);
1.481     raeburn  14476:     my $a='';
1.800     albertel 14477:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14478:     return $a;
                   14479: }
                   14480: 
1.36      albertel 14481: sub filelocation {
1.590     banghart 14482:     my ($dir,$file) = @_;
                   14483:     my $location;
                   14484:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14485: 
                   14486:     if ($file =~ m-^/adm/-) {
                   14487: 	$file=~s-^/adm/wrapper/-/-;
                   14488: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14489:     }
1.882     albertel 14490: 
1.1139    www      14491:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14492:         $location = $file;
1.609     banghart 14493:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14494:         my ($udom,$uname,$filename)=
1.811     albertel 14495:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14496:         my $home=&homeserver($uname,$udom);
                   14497:         my $is_me=0;
                   14498:         my @ids=&current_machine_ids();
                   14499:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14500:         if ($is_me) {
1.1117    foxr     14501:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14502:         } else {
                   14503:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14504:   	      $udom.'/'.$uname.'/'.$filename;
                   14505:         }
1.882     albertel 14506:     } elsif ($file =~ m-^/adm/-) {
                   14507: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14508:     } else {
                   14509:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14510:         $file=~s:^/(res|priv)/:/:;
                   14511:         my $space=$1;
1.590     banghart 14512:         if ( !( $file =~ m:^/:) ) {
                   14513:             $location = $dir. '/'.$file;
                   14514:         } else {
1.1142    raeburn  14515:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14516:         }
1.59      albertel 14517:     }
1.590     banghart 14518:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14519:     while ($location=~m{/\.\./}) {
                   14520: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14521: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14522: 	} else {
                   14523: 	    $location=~ s{/\.\./}{/}g;
                   14524: 	}
                   14525:     } #remove dir/..
1.590     banghart 14526:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14527:     return $location;
1.46      www      14528: }
1.36      albertel 14529: 
1.46      www      14530: sub hreflocation {
                   14531:     my ($dir,$file)=@_;
1.980     raeburn  14532:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14533: 	$file=filelocation($dir,$file);
1.700     albertel 14534:     } elsif ($file=~m-^/adm/-) {
                   14535: 	$file=~s-^/adm/wrapper/-/-;
                   14536: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14537:     }
                   14538:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14539: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14540:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14541: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14542: 	        {/uploaded/$1/$2/}x;
1.46      www      14543:     }
1.913     albertel 14544:     if ($file=~ m{^/userfiles/}) {
                   14545: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14546:     }
1.462     albertel 14547:     return $file;
1.465     albertel 14548: }
                   14549: 
1.1139    www      14550: 
                   14551: 
                   14552: 
                   14553: 
1.465     albertel 14554: sub current_machine_domains {
1.853     albertel 14555:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14556: }
                   14557: 
                   14558: sub machine_domains {
                   14559:     my ($hostname) = @_;
1.465     albertel 14560:     my @domains;
1.838     albertel 14561:     my %hostname = &all_hostnames();
1.465     albertel 14562:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14563: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14564: 	if ($hostname eq $name) {
1.844     albertel 14565: 	    push(@domains,&host_domain($id));
1.465     albertel 14566: 	}
                   14567:     }
                   14568:     return @domains;
                   14569: }
                   14570: 
                   14571: sub current_machine_ids {
1.853     albertel 14572:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14573: }
                   14574: 
                   14575: sub machine_ids {
                   14576:     my ($hostname) = @_;
                   14577:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14578:     my @ids;
1.888     albertel 14579:     my %name_to_host = &all_names();
1.889     albertel 14580:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14581: 	return @{ $name_to_host{$hostname} };
                   14582:     }
                   14583:     return;
1.31      www      14584: }
                   14585: 
1.824     raeburn  14586: sub additional_machine_domains {
                   14587:     my @domains;
1.1466    raeburn  14588:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14589:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14590:             while (my $line = <$fh>) {
                   14591:                 chomp($line);           
                   14592:                 $line =~ s/\s//g;
                   14593:                 push(@domains,$line);
                   14594:             }
                   14595:             close($fh);
                   14596:         }
1.824     raeburn  14597:     }
                   14598:     return @domains;
                   14599: }
                   14600: 
                   14601: sub default_login_domain {
                   14602:     my $domain = $perlvar{'lonDefDomain'};
                   14603:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14604:     foreach my $posdom (&current_machine_domains(),
                   14605:                         &additional_machine_domains()) {
                   14606:         if (lc($posdom) eq lc($testdomain)) {
                   14607:             $domain=$posdom;
                   14608:             last;
                   14609:         }
                   14610:     }
                   14611:     return $domain;
                   14612: }
                   14613: 
1.1414    raeburn  14614: sub shared_institution {
1.1439    raeburn  14615:     my ($dom,$lonhost) = @_;
                   14616:     if ($lonhost eq '') {
                   14617:         $lonhost = $perlvar{'lonHostID'};
                   14618:     }
1.1414    raeburn  14619:     my $same_intdom;
1.1439    raeburn  14620:     my $hostintdom = &internet_dom($lonhost);
1.1414    raeburn  14621:     if ($hostintdom ne '') {
                   14622:         my %iphost = &get_iphost();
                   14623:         my $primary_id = &domain($dom,'primary');
                   14624:         my $primary_ip = &get_host_ip($primary_id);
                   14625:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14626:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14627:                 my $intdom = &internet_dom($id);
                   14628:                 if ($intdom eq $hostintdom) {
                   14629:                     $same_intdom = 1;
                   14630:                     last;
                   14631:                 }
                   14632:             }
                   14633:         }
                   14634:     }
                   14635:     return $same_intdom;
                   14636: }
                   14637: 
1.1398    raeburn  14638: sub uses_sts {
                   14639:     my ($ignore_cache) = @_;
                   14640:     my $lonhost = $perlvar{'lonHostID'};
                   14641:     my $hostname = &hostname($lonhost);
                   14642:     my $sts_on;
                   14643:     if ($protocol{$lonhost} eq 'https') {
                   14644:         my $cachetime = 12*3600;
                   14645:         if (!$ignore_cache) {
                   14646:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14647:             if (defined($cached)) {
                   14648:                 return $sts_on;
                   14649:             }
                   14650:         }
                   14651:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14652:         my $request=new HTTP::Request('HEAD',$url);
                   14653:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   14654:         if ($response->is_success) {
                   14655:             my $has_sts = $response->header('Strict-Transport-Security');
                   14656:             if ($has_sts eq '') {
                   14657:                 $sts_on = 0;
                   14658:             } else {
                   14659:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14660:                     my $maxage = $1;
                   14661:                     if ($maxage) {
                   14662:                         $sts_on = 1;
                   14663:                     } else {
                   14664:                         $sts_on = 0;
                   14665:                     }
                   14666:                 } else {
                   14667:                     $sts_on = 0;
                   14668:                 }
                   14669:             }
                   14670:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14671:         }
                   14672:     }
                   14673:     return;
                   14674: }
                   14675: 
1.1449    raeburn  14676: sub waf_allssl {
                   14677:     my ($host_name) = @_;
                   14678:     my $alias = &get_proxy_alias();
                   14679:     if ($host_name eq '') {
                   14680:         $host_name = $ENV{'SERVER_NAME'};
                   14681:     }
                   14682:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14683:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14684:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14685:         if ($defdomdefaults{'waf_sslopt'}) {
                   14686:             return $defdomdefaults{'waf_sslopt'};
                   14687:         }
                   14688:     }
                   14689:     return;
                   14690: }
                   14691: 
1.1434    raeburn  14692: sub get_requestor_ip {
                   14693:     my ($r,$nolookup,$noproxy) = @_;
                   14694:     my $from_ip;
                   14695:     if (ref($r)) {
1.1447    raeburn  14696:         if ($r->can('useragent_ip')) {
                   14697:             if ($noproxy && $r->can('client_ip')) {
                   14698:                 $from_ip = $r->client_ip();
                   14699:             } else {
                   14700:                 $from_ip = $r->useragent_ip();
                   14701:             }
                   14702:         } elsif ($r->connection->can('remote_ip')) {
                   14703:             $from_ip = $r->connection->remote_ip();
                   14704:         } else {
                   14705:             $from_ip = $r->get_remote_host($nolookup);
                   14706:         }
1.1434    raeburn  14707:     } else {
                   14708:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14709:     }
                   14710:     return $from_ip if ($noproxy); 
                   14711:     # Who controls proxy settings for server
                   14712:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14713:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14714:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437    raeburn  14715:         if ($proxyinfo->{'vpnint'}) {
                   14716:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434    raeburn  14717:                 return $from_ip;
                   14718:             }
                   14719:         }
                   14720:         if ($proxyinfo->{'trusted'}) {
                   14721:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14722:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14723:                 my ($ip,$xfor);
                   14724:                 if (ref($r)) {
                   14725:                     if ($ipheader) {
                   14726:                         $ip = $r->headers_in->{$ipheader};
                   14727:                     }
                   14728:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14729:                 } else {
                   14730:                     if ($ipheader) {
                   14731:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14732:                     }
                   14733:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14734:                 }
                   14735:                 if (($ip eq '') && ($xfor ne '')) {
                   14736:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14737:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14738:                             $ip = $poss_ip;
1.1435    raeburn  14739:                             last;
1.1434    raeburn  14740:                         }
                   14741:                     }
                   14742:                 }
                   14743:                 if ($ip ne '') {
                   14744:                     return $ip;
                   14745:                 }
                   14746:             }
                   14747:         }
                   14748:     }
                   14749:     return $from_ip;
                   14750: }
                   14751: 
                   14752: sub get_proxy_settings {
                   14753:     my ($dom_in_use) = @_;
                   14754:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14755:     my $proxyinfo = {
                   14756:                        ipheader => $domdefaults{'waf_ipheader'},
                   14757:                        trusted  => $domdefaults{'waf_trusted'},
1.1437    raeburn  14758:                        vpnint   => $domdefaults{'waf_vpnint'},
1.1438    raeburn  14759:                        vpnext   => $domdefaults{'waf_vpnext'},
1.1449    raeburn  14760:                        sslopt   => $domdefaults{'waf_sslopt'},
1.1434    raeburn  14761:                     };
                   14762:     return $proxyinfo;
                   14763: }
                   14764: 
                   14765: sub ip_match {
                   14766:     my ($ip,$pattern_str) = @_;
                   14767:     $ip=Net::CIDR::cidrvalidate($ip);
                   14768:     if ($ip) {
                   14769:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14770:     }
                   14771:     return;
                   14772: }
                   14773: 
                   14774: sub get_proxy_alias {
1.1450    raeburn  14775:     my ($lonid) = @_;
                   14776:     if ($lonid eq '') {
                   14777:         $lonid = $perlvar{'lonHostID'};
                   14778:     }
                   14779:     if (!defined(&hostname($lonid))) {
                   14780:         return;
                   14781:     }
                   14782:     if ($lonid ne '') {
                   14783:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434    raeburn  14784:         if ($cached) {
                   14785:             return $alias;
                   14786:         }
1.1450    raeburn  14787:         my $dom = &Apache::lonnet::host_domain($lonid);
1.1434    raeburn  14788:         if ($dom ne '') {
                   14789:             my $cachetime = 60*60*24;
                   14790:             my %domconfig =
1.1437    raeburn  14791:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14792:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14793:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450    raeburn  14794:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14795:                 }
                   14796:             }
                   14797:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14798:         }
                   14799:     }
                   14800:     return;
                   14801: }
                   14802: 
                   14803: sub use_proxy_alias {
                   14804:     my ($r,$lonid) = @_;
                   14805:     my $alias = &get_proxy_alias($lonid);
                   14806:     if ($alias) {
                   14807:         my $dom = &host_domain($lonid);
                   14808:         if ($dom ne '') {
1.1467    raeburn  14809:             my $proxyinfo = &get_proxy_settings($dom);
1.1450    raeburn  14810:             my ($vpnint,$remote_ip);
                   14811:             if (ref($proxyinfo) eq 'HASH') {
                   14812:                 $vpnint = $proxyinfo->{'vpnint'};
                   14813:                 if ($vpnint) {
                   14814:                     $remote_ip = &get_requestor_ip($r,1,1);
1.1434    raeburn  14815:                 }
                   14816:             }
1.1450    raeburn  14817:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14818:                 return $alias;
                   14819:             }
1.1434    raeburn  14820:         }
                   14821:     }
                   14822:     return;
                   14823: }
                   14824: 
1.1474    raeburn  14825: sub alias_sso {
1.1467    raeburn  14826:     my ($lonid) = @_;
                   14827:     if ($lonid eq '') {
                   14828:         $lonid = $perlvar{'lonHostID'};
                   14829:     }
                   14830:     if (!defined(&hostname($lonid))) {
                   14831:         return;
                   14832:     }
                   14833:     if ($lonid ne '') {
                   14834:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14835:         if ($cached) {
                   14836:             return $use_alias;
                   14837:         }
                   14838:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14839:         if ($dom ne '') {
                   14840:             my $cachetime = 60*60*24;
                   14841:             my %domconfig =
                   14842:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14843:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14844:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14845:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14846:                 }
                   14847:             }
                   14848:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14849:         }
                   14850:     }
                   14851:     return;
                   14852: }
                   14853: 
1.1465    raeburn  14854: sub get_saml_landing {
                   14855:     my ($lonid) = @_;
                   14856:     if ($lonid eq '') {
                   14857:         my $defdom = &default_login_domain();
                   14858:         my @hosts = &current_machine_ids();
                   14859:         if (@hosts > 1) {
                   14860:             foreach my $hostid (@hosts) {
                   14861:                 if (&host_domain($hostid) eq $defdom) {
                   14862:                     $lonid = $hostid;
                   14863:                     last;
                   14864:                 }
                   14865:             }
                   14866:         } else {
                   14867:             $lonid = $perlvar{'lonHostID'};
                   14868:         }
                   14869:         if ($lonid) {
                   14870:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14871:                 return;
                   14872:             }
                   14873:         } else {
                   14874:             return;
                   14875:         }
                   14876:     } elsif (!defined(&hostname($lonid))) {
                   14877:         return;
                   14878:     }
                   14879:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14880:     if ($cached) {
                   14881:         return $landing;
                   14882:     }
                   14883:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14884:     if ($dom ne '') {
                   14885:         my $cachetime = 60*60*24;
                   14886:         my %domconfig =
                   14887:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14888:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14889:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14890:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14891:                     $landing = 1;
                   14892:                 }
                   14893:             }
                   14894:         }
                   14895:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14896:     }
                   14897:     return;
                   14898: }
                   14899: 
1.31      www      14900: # ------------------------------------------------------------- Declutters URLs
                   14901: 
                   14902: sub declutter {
                   14903:     my $thisfn=shift;
1.569     albertel 14904:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  14905:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14906:         $thisfn=~s{^/home/httpd/html}{};
                   14907:     }
1.31      www      14908:     $thisfn=~s/^\///;
1.697     albertel 14909:     $thisfn=~s|^adm/wrapper/||;
                   14910:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14911:     $thisfn=~s/^res\///;
1.1172    bisitz   14912:     $thisfn=~s/^priv\///;
1.1032    raeburn  14913:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14914:         $thisfn=~s/\?.+$//;
                   14915:     }
1.268     www      14916:     return $thisfn;
                   14917: }
                   14918: 
                   14919: # ------------------------------------------------------------- Clutter up URLs
                   14920: 
                   14921: sub clutter {
                   14922:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14923:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14924: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14925:        $thisfn='/res'.$thisfn; 
                   14926:     }
1.1031    raeburn  14927:     if ($thisfn !~m|^/adm|) {
                   14928: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14929: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14930: 	} else {
                   14931: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14932: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14933: 	    if ($embstyle eq 'ssi'
                   14934: 		|| ($embstyle eq 'hdn')
                   14935: 		|| ($embstyle eq 'rat')
                   14936: 		|| ($embstyle eq 'prv')
                   14937: 		|| ($embstyle eq 'ign')) {
                   14938: 		#do nothing with these
                   14939: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14940: 		|| ($embstyle eq 'emb')
                   14941: 		|| ($embstyle eq 'wrp')) {
                   14942: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14943: 	    } elsif ($embstyle eq 'unk'
                   14944: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14945: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14946: 	    } else {
1.718     www      14947: #		&logthis("Got a blank emb style");
1.695     albertel 14948: 	    }
1.694     albertel 14949: 	}
1.1343    raeburn  14950:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14951:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14952:     }
1.31      www      14953:     return $thisfn;
1.12      www      14954: }
                   14955: 
1.787     albertel 14956: sub clutter_with_no_wrapper {
                   14957:     my $uri = &clutter(shift);
                   14958:     if ($uri =~ m-^/adm/-) {
                   14959: 	$uri =~ s-^/adm/wrapper/-/-;
                   14960: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14961:     }
                   14962:     return $uri;
                   14963: }
                   14964: 
1.557     albertel 14965: sub freeze_escape {
                   14966:     my ($value)=@_;
                   14967:     if (ref($value)) {
                   14968: 	$value=&nfreeze($value);
                   14969: 	return '__FROZEN__'.&escape($value);
                   14970:     }
                   14971:     return &escape($value);
                   14972: }
                   14973: 
1.11      www      14974: 
1.557     albertel 14975: sub thaw_unescape {
                   14976:     my ($value)=@_;
                   14977:     if ($value =~ /^__FROZEN__/) {
                   14978: 	substr($value,0,10,undef);
                   14979: 	$value=&unescape($value);
                   14980: 	return &thaw($value);
                   14981:     }
                   14982:     return &unescape($value);
                   14983: }
                   14984: 
1.436     albertel 14985: sub correct_line_ends {
                   14986:     my ($result)=@_;
                   14987:     $$result =~s/\r\n/\n/mg;
                   14988:     $$result =~s/\r/\n/mg;
1.415     albertel 14989: }
1.1       albertel 14990: # ================================================================ Main Program
                   14991: 
1.184     www      14992: sub goodbye {
1.204     albertel 14993:    &logthis("Starting Shut down");
1.443     albertel 14994: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14995:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14996: #converted
1.599     albertel 14997: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14998:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14999: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   15000: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 15001: #1.1 only
1.870     albertel 15002: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   15003: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   15004: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   15005: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   15006:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 15007:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   15008:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      15009:    &flushcourselogs();
                   15010:    &logthis("Shutting down");
                   15011: }
                   15012: 
1.852     albertel 15013: sub get_dns {
1.1210    raeburn  15014:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 15015:     if (!$ignore_cache) {
                   15016: 	my ($content,$cached)=
                   15017: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   15018: 	if ($cached) {
1.1210    raeburn  15019: 	    &$func($content,$hashref);
1.869     albertel 15020: 	    return;
                   15021: 	}
                   15022:     }
                   15023: 
                   15024:     my %alldns;
1.1379    raeburn  15025:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   15026:         foreach my $dns (<$config>) {
                   15027: 	    next if ($dns !~ /^\^(\S*)/x);
                   15028:             my $line = $1;
                   15029:             my ($host,$protocol) = split(/:/,$line);
                   15030:             if ($protocol ne 'https') {
                   15031:                 $protocol = 'http';
                   15032:             }
                   15033: 	    $alldns{$host} = $protocol;
1.979     raeburn  15034:         }
1.1379    raeburn  15035:         close($config);
1.869     albertel 15036:     }
                   15037:     while (%alldns) {
1.1263    raeburn  15038: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456    raeburn  15039:         my ($contents,@content);
                   15040:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   15041:             my $command = (split('/',$url))[3];
                   15042:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   15043:             delete($alldns{$dns});
                   15044:             next if (($dir eq '') || ($file eq ''));
                   15045:             if (open(my $config,'<',"$dir/$file")) {
1.1457    raeburn  15046:                 @content = <$config>;
1.1456    raeburn  15047:                 close($config);
                   15048:             }
                   15049:             if ($url eq '/adm/dns/loncapaCRL') {
                   15050:                 $contents = join('',@content);
                   15051:             }
                   15052:         } else {
                   15053: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   15054:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
                   15055:             delete($alldns{$dns});
                   15056: 	    next if ($response->is_error());
                   15057:             if ($url eq '/adm/dns/loncapaCRL') {
                   15058:                 $contents = $response->content;
                   15059:             } else {
                   15060:                 @content = split("\n",$response->content);
                   15061:             }
                   15062:         }
1.1379    raeburn  15063:         if ($url eq '/adm/dns/loncapaCRL') {
1.1456    raeburn  15064:             return &$func($contents);
1.1379    raeburn  15065:         } else {
                   15066: 	    unless ($nocache) {
                   15067: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   15068: 	    }
                   15069: 	    &$func(\@content,$hashref);
                   15070:             return;
                   15071:         }
                   15072:     }
                   15073:     my $which = (split('/',$url,4))[3];
                   15074:     if ($which eq 'loncapaCRL') {
                   15075:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   15076:         if (-e $diskfile) {
                   15077:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   15078:         } else {
                   15079:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   15080:         }
                   15081:     } else {
                   15082:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   15083:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   15084:             my @content = <$config>;
                   15085:             close($config);
                   15086:             &$func(\@content,$hashref);
                   15087:         }
1.852     albertel 15088:     }
1.1210    raeburn  15089:     return;
                   15090: }
                   15091: 
                   15092: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  15093: sub parse_dns_checksums_tab {
1.1210    raeburn  15094:     my ($lines,$hashref) = @_;
1.1264    raeburn  15095:     my $lonhost = $perlvar{'lonHostID'};
                   15096:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  15097:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  15098:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   15099:     my $webconfdir = '/etc/httpd/conf';
                   15100:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   15101:         $webconfdir = '/etc/apache2';
                   15102:     } elsif ($distro =~ /^sles(\d+)$/) {
                   15103:         if ($1 >= 10) {
                   15104:             $webconfdir = '/etc/apache2';
                   15105:         }
                   15106:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   15107:         if ($1 >= 10.0) {
                   15108:             $webconfdir = '/etc/apache2';
                   15109:         }
                   15110:     }
1.1210    raeburn  15111:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15112:     my (%chksum,%revnum);
                   15113:     if (ref($lines) eq 'ARRAY') {
                   15114:         chomp(@{$lines});
1.1238    raeburn  15115:         my $version = shift(@{$lines});
                   15116:         if ($version eq $release) {  
1.1210    raeburn  15117:             foreach my $line (@{$lines}) {
1.1238    raeburn  15118:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  15119:                 if ($file =~ m{^/etc/httpd/conf}) {
                   15120:                     if ($webconfdir eq '/etc/apache2') {
                   15121:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   15122:                     }
                   15123:                 }
1.1238    raeburn  15124:                 $chksum{$file} = $shasum;
                   15125:                 $revnum{$file} = $version;
1.1210    raeburn  15126:             }
                   15127:             if (ref($hashref) eq 'HASH') {
                   15128:                 %{$hashref} = (
                   15129:                                 sums     => \%chksum,
                   15130:                                 versions => \%revnum,
                   15131:                               );
                   15132:             }
                   15133:         }
                   15134:     }
1.869     albertel 15135:     return;
1.852     albertel 15136: }
1.1210    raeburn  15137: 
                   15138: sub fetch_dns_checksums {
1.1238    raeburn  15139:     my %checksums;
                   15140:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  15141:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  15142:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15143:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  15144:              \%checksums);
1.1210    raeburn  15145:     return \%checksums;
                   15146: }
                   15147: 
1.1379    raeburn  15148: sub fetch_crl_pemfile {
                   15149:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   15150: }
                   15151: 
                   15152: sub save_crl_pem {
1.1456    raeburn  15153:     my ($content) = @_;
1.1380    raeburn  15154:     my ($msg,$hadchanges);
1.1456    raeburn  15155:     if ($content ne '') {
1.1379    raeburn  15156:         my $now = time;
                   15157:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   15158:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   15159:         if (open(my $fh,'>',"$tmpcrl")) {
1.1456    raeburn  15160:             print $fh $content;
1.1379    raeburn  15161:             close($fh);
                   15162:             if (-e $lonca) {
                   15163:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   15164:                     my $check = <PIPE>;
                   15165:                     close(PIPE);
                   15166:                     chomp($check);
                   15167:                     if ($check eq 'verify OK') {
                   15168:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  15169:                         my $backup;
1.1379    raeburn  15170:                         if (-e $dest) {
1.1380    raeburn  15171:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   15172:                                 $backup = 'ok';
                   15173:                             }
1.1379    raeburn  15174:                         }
                   15175:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   15176:                             $msg = 'ok';
1.1380    raeburn  15177:                             if ($backup) {
                   15178:                                 my (%oldnums,%newnums);
                   15179:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   15180:                                     while (<PIPE>) {
                   15181:                                         $oldnums{(split(/:/))[1]} = 1;
                   15182:                                     }
                   15183:                                     close(PIPE);
                   15184:                                 }
                   15185:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   15186:                                     while(<PIPE>) {
                   15187:                                         $newnums{(split(/:/))[1]} = 1;
                   15188:                                     }
                   15189:                                     close(PIPE);
                   15190:                                 }
                   15191:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   15192:                                     unless (exists($oldnums{$key})) {
                   15193:                                         $hadchanges = 1;
                   15194:                                         last;
                   15195:                                     }
                   15196:                                 }
                   15197:                                 unless ($hadchanges) {
                   15198:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   15199:                                         unless (exists($newnums{$key})) {
                   15200:                                             $hadchanges = 1;
                   15201:                                             last;
                   15202:                                         }
                   15203:                                     }
                   15204:                                 }
                   15205:                             }
1.1379    raeburn  15206:                         }
                   15207:                     } else {
                   15208:                         unlink($tmpcrl);
                   15209:                     }
                   15210:                 } else {
                   15211:                     unlink($tmpcrl);
                   15212:                 }
                   15213:             } else {
                   15214:                 unlink($tmpcrl);
                   15215:             }
                   15216:         }
                   15217:     }
1.1380    raeburn  15218:     return ($msg,$hadchanges);
1.1379    raeburn  15219: }
                   15220: 
1.1456    raeburn  15221: sub parse_getdns_url {
                   15222:     my ($command,$url) = @_;
                   15223:     my $dir = $perlvar{'lonTabDir'};
                   15224:     my $file;
                   15225:     if ($command eq 'hosts') {
                   15226:         $file = 'dns_hosts.tab';
                   15227:     } elsif ($command eq 'domain') {
                   15228:         $file = 'dns_domain.tab';
                   15229:     } elsif ($command eq 'checksums') {
                   15230:         my $version = (split('/',$url))[4];
                   15231:         $file = "dns_checksums/$version.tab",
                   15232:     } elsif ($command eq 'loncapaCRL') {
                   15233:         $dir = $perlvar{'lonCertificateDirectory'};
                   15234:         $file = $perlvar{'lonnetCertRevocationList'};
                   15235:     }
                   15236:     return ($dir,$file);
                   15237: }
                   15238: 
1.327     albertel 15239: # ------------------------------------------------------------ Read domain file
                   15240: {
1.852     albertel 15241:     my $loaded;
1.846     albertel 15242:     my %domain;
                   15243: 
1.852     albertel 15244:     sub parse_domain_tab {
                   15245: 	my ($lines) = @_;
                   15246: 	foreach my $line (@$lines) {
                   15247: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      15248: 
1.846     albertel 15249: 	    chomp($line);
1.852     albertel 15250: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 15251: 	    my %this_domain;
                   15252: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   15253: 			       'lang_def', 'city', 'longi', 'lati',
                   15254: 			       'primary') {
                   15255: 		$this_domain{$field} = shift(@elements);
                   15256: 	    }
                   15257: 	    $domain{$name} = \%this_domain;
1.852     albertel 15258: 	}
                   15259:     }
1.864     albertel 15260: 
                   15261:     sub reset_domain_info {
                   15262: 	undef($loaded);
                   15263: 	undef(%domain);
                   15264:     }
                   15265: 
1.852     albertel 15266:     sub load_domain_tab {
1.1293    raeburn  15267: 	my ($ignore_cache,$nocache) = @_;
                   15268: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 15269: 	my $fh;
1.1359    raeburn  15270: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 15271: 	    my @lines = <$fh>;
                   15272: 	    &parse_domain_tab(\@lines);
1.448     albertel 15273: 	}
1.852     albertel 15274: 	close($fh);
                   15275: 	$loaded = 1;
1.327     albertel 15276:     }
1.846     albertel 15277: 
                   15278:     sub domain {
1.852     albertel 15279: 	&load_domain_tab() if (!$loaded);
                   15280: 
1.846     albertel 15281: 	my ($name,$what) = @_;
                   15282: 	return if ( !exists($domain{$name}) );
                   15283: 
                   15284: 	if (!$what) {
                   15285: 	    return $domain{$name}{'description'};
                   15286: 	}
                   15287: 	return $domain{$name}{$what};
                   15288:     }
1.974     raeburn  15289: 
                   15290:     sub domain_info {
                   15291:         &load_domain_tab() if (!$loaded);
                   15292:         return %domain;
                   15293:     }
                   15294: 
1.327     albertel 15295: }
                   15296: 
                   15297: 
1.1       albertel 15298: # ------------------------------------------------------------- Read hosts file
                   15299: {
1.838     albertel 15300:     my %hostname;
1.844     albertel 15301:     my %hostdom;
1.845     albertel 15302:     my %libserv;
1.852     albertel 15303:     my $loaded;
1.888     albertel 15304:     my %name_to_host;
1.1074    raeburn  15305:     my %internetdom;
1.1107    raeburn  15306:     my %LC_dns_serv;
1.852     albertel 15307: 
                   15308:     sub parse_hosts_tab {
                   15309: 	my ($file) = @_;
                   15310: 	foreach my $configline (@$file) {
                   15311: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  15312:             chomp($configline);
                   15313: 	    if ($configline =~ /^\^/) {
                   15314:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   15315:                     $LC_dns_serv{$1} = 1;
                   15316:                 }
                   15317:                 next;
                   15318:             }
1.1074    raeburn  15319: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 15320: 	    $name=~s/\s//g;
                   15321: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  15322:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   15323:                     my $curr = $hostname{$id};
                   15324:                     my $skip;
                   15325:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   15326:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   15327:                             $skip = 1;
                   15328:                         } else {
                   15329:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   15330:                         }
                   15331:                     }
                   15332:                     unless ($skip) {
                   15333:                         push(@{$name_to_host{$name}},$id);
                   15334:                     }
                   15335:                 } else {
                   15336:                     push(@{$name_to_host{$name}},$id);
                   15337:                 }
1.852     albertel 15338: 		$hostname{$id}=$name;
                   15339: 		$hostdom{$id}=$domain;
                   15340: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  15341:                 if (defined($protocol)) {
                   15342:                     if ($protocol eq 'https') {
                   15343:                         $protocol{$id} = $protocol;
                   15344:                     } else {
                   15345:                         $protocol{$id} = 'http'; 
                   15346:                     }
1.968     raeburn  15347:                 } else {
1.969     raeburn  15348:                     $protocol{$id} = 'http';
1.968     raeburn  15349:                 }
1.1074    raeburn  15350:                 if (defined($intdom)) {
                   15351:                     $internetdom{$id} = $intdom;
                   15352:                 }
1.852     albertel 15353: 	    }
                   15354: 	}
                   15355:     }
1.864     albertel 15356:     
                   15357:     sub reset_hosts_info {
1.897     albertel 15358: 	&purge_remembered();
1.864     albertel 15359: 	&reset_domain_info();
                   15360: 	&reset_hosts_ip_info();
1.1339    raeburn  15361:         undef(%internetdom);
1.892     albertel 15362: 	undef(%name_to_host);
1.864     albertel 15363: 	undef(%hostname);
                   15364: 	undef(%hostdom);
                   15365: 	undef(%libserv);
                   15366: 	undef($loaded);
                   15367:     }
1.1       albertel 15368: 
1.852     albertel 15369:     sub load_hosts_tab {
1.1293    raeburn  15370: 	my ($ignore_cache,$nocache) = @_;
                   15371: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  15372: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 15373: 	my @config = <$config>;
                   15374: 	&parse_hosts_tab(\@config);
                   15375: 	close($config);
                   15376: 	$loaded=1;
1.1       albertel 15377:     }
1.852     albertel 15378: 
1.838     albertel 15379:     sub hostname {
1.852     albertel 15380: 	&load_hosts_tab() if (!$loaded);
                   15381: 
1.838     albertel 15382: 	my ($lonid) = @_;
                   15383: 	return $hostname{$lonid};
                   15384:     }
1.845     albertel 15385: 
1.838     albertel 15386:     sub all_hostnames {
1.852     albertel 15387: 	&load_hosts_tab() if (!$loaded);
                   15388: 
1.838     albertel 15389: 	return %hostname;
                   15390:     }
1.845     albertel 15391: 
1.888     albertel 15392:     sub all_names {
1.1293    raeburn  15393:         my ($ignore_cache,$nocache) = @_;
                   15394: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15395: 
                   15396: 	return %name_to_host;
                   15397:     }
                   15398: 
1.974     raeburn  15399:     sub all_host_domain {
                   15400:         &load_hosts_tab() if (!$loaded);
                   15401:         return %hostdom;
                   15402:     }
                   15403: 
1.1339    raeburn  15404:     sub all_host_intdom {
                   15405:         &load_hosts_tab() if (!$loaded);
                   15406:         return %internetdom;
                   15407:     }
                   15408: 
1.845     albertel 15409:     sub is_library {
1.852     albertel 15410: 	&load_hosts_tab() if (!$loaded);
                   15411: 
1.845     albertel 15412: 	return exists($libserv{$_[0]});
                   15413:     }
                   15414: 
                   15415:     sub all_library {
1.852     albertel 15416: 	&load_hosts_tab() if (!$loaded);
                   15417: 
1.845     albertel 15418: 	return %libserv;
                   15419:     }
                   15420: 
1.1062    droeschl 15421:     sub unique_library {
                   15422: 	#2x reverse removes all hostnames that appear more than once
                   15423:         my %unique = reverse &all_library();
                   15424:         return reverse %unique;
                   15425:     }
                   15426: 
1.841     albertel 15427:     sub get_servers {
1.852     albertel 15428: 	&load_hosts_tab() if (!$loaded);
                   15429: 
1.841     albertel 15430: 	my ($domain,$type) = @_;
                   15431: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15432: 	                                          : %hostname;
                   15433: 	my %result;
1.842     albertel 15434: 	if (ref($domain) eq 'ARRAY') {
                   15435: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15436: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15437: 		    $result{$host} = $hostname;
                   15438: 		}
                   15439: 	    }
                   15440: 	} else {
                   15441: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15442: 		if ($hostdom{$host} eq $domain) {
                   15443: 		    $result{$host} = $hostname;
                   15444: 		}
1.841     albertel 15445: 	    }
                   15446: 	}
                   15447: 	return %result;
                   15448:     }
1.845     albertel 15449: 
1.1062    droeschl 15450:     sub get_unique_servers {
                   15451:         my %unique = reverse &get_servers(@_);
                   15452: 	return reverse %unique;
                   15453:     }
                   15454: 
1.844     albertel 15455:     sub host_domain {
1.852     albertel 15456: 	&load_hosts_tab() if (!$loaded);
                   15457: 
1.844     albertel 15458: 	my ($lonid) = @_;
                   15459: 	return $hostdom{$lonid};
                   15460:     }
                   15461: 
1.841     albertel 15462:     sub all_domains {
1.852     albertel 15463: 	&load_hosts_tab() if (!$loaded);
                   15464: 
1.841     albertel 15465: 	my %seen;
                   15466: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15467: 	return @uniq;
                   15468:     }
1.1074    raeburn  15469: 
                   15470:     sub internet_dom {
                   15471:         &load_hosts_tab() if (!$loaded);
                   15472: 
                   15473:         my ($lonid) = @_;
                   15474:         return $internetdom{$lonid};
                   15475:     }
1.1107    raeburn  15476: 
                   15477:     sub is_LC_dns {
                   15478:         &load_hosts_tab() if (!$loaded);
                   15479: 
                   15480:         my ($hostname) = @_;
                   15481:         return exists($LC_dns_serv{$hostname});
                   15482:     }
                   15483: 
1.1       albertel 15484: }
                   15485: 
1.847     albertel 15486: { 
                   15487:     my %iphost;
1.856     albertel 15488:     my %name_to_ip;
                   15489:     my %lonid_to_ip;
1.869     albertel 15490: 
1.847     albertel 15491:     sub get_hosts_from_ip {
                   15492: 	my ($ip) = @_;
                   15493: 	my %iphosts = &get_iphost();
                   15494: 	if (ref($iphosts{$ip})) {
                   15495: 	    return @{$iphosts{$ip}};
                   15496: 	}
                   15497: 	return;
1.839     albertel 15498:     }
1.864     albertel 15499:     
                   15500:     sub reset_hosts_ip_info {
                   15501: 	undef(%iphost);
                   15502: 	undef(%name_to_ip);
                   15503: 	undef(%lonid_to_ip);
                   15504:     }
1.856     albertel 15505: 
                   15506:     sub get_host_ip {
                   15507: 	my ($lonid) = @_;
                   15508: 	if (exists($lonid_to_ip{$lonid})) {
                   15509: 	    return $lonid_to_ip{$lonid};
                   15510: 	}
                   15511: 	my $name=&hostname($lonid);
                   15512:    	my $ip = gethostbyname($name);
                   15513: 	return if (!$ip || length($ip) ne 4);
                   15514: 	$ip=inet_ntoa($ip);
                   15515: 	$name_to_ip{$name}   = $ip;
                   15516: 	$lonid_to_ip{$lonid} = $ip;
                   15517: 	return $ip;
                   15518:     }
1.847     albertel 15519:     
                   15520:     sub get_iphost {
1.1293    raeburn  15521: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15522: 
1.869     albertel 15523: 	if (!$ignore_cache) {
                   15524: 	    if (%iphost) {
                   15525: 		return %iphost;
                   15526: 	    }
                   15527: 	    my ($ip_info,$cached)=
                   15528: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15529: 	    if ($cached) {
                   15530: 		%iphost      = %{$ip_info->[0]};
                   15531: 		%name_to_ip  = %{$ip_info->[1]};
                   15532: 		%lonid_to_ip = %{$ip_info->[2]};
                   15533: 		return %iphost;
                   15534: 	    }
                   15535: 	}
1.894     albertel 15536: 
                   15537: 	# get yesterday's info for fallback
                   15538: 	my %old_name_to_ip;
                   15539: 	my ($ip_info,$cached)=
                   15540: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15541: 	if ($cached) {
                   15542: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15543: 	}
                   15544: 
1.1293    raeburn  15545: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15546: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15547: 	    my $ip;
                   15548: 	    if (!exists($name_to_ip{$name})) {
                   15549: 		$ip = gethostbyname($name);
                   15550: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15551: 		    if (defined($old_name_to_ip{$name})) {
                   15552: 			$ip = $old_name_to_ip{$name};
                   15553: 			&logthis("Can't find $name defaulting to old $ip");
                   15554: 		    } else {
                   15555: 			&logthis("Name $name no IP found");
                   15556: 			next;
                   15557: 		    }
                   15558: 		} else {
                   15559: 		    $ip=inet_ntoa($ip);
1.847     albertel 15560: 		}
                   15561: 		$name_to_ip{$name} = $ip;
                   15562: 	    } else {
                   15563: 		$ip = $name_to_ip{$name};
1.653     albertel 15564: 	    }
1.888     albertel 15565: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15566: 		$lonid_to_ip{$id} = $ip;
                   15567: 	    }
                   15568: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15569: 	}
1.1293    raeburn  15570:         unless ($nocache) {
                   15571: 	    &do_cache_new('iphost','iphost',
                   15572: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15573: 		          48*60*60);
                   15574:         }
1.869     albertel 15575: 
1.847     albertel 15576: 	return %iphost;
1.598     albertel 15577:     }
                   15578: 
1.992     raeburn  15579:     #
                   15580:     #  Given a DNS returns the loncapa host name for that DNS 
                   15581:     # 
                   15582:     sub host_from_dns {
                   15583:         my ($dns) = @_;
                   15584:         my @hosts;
                   15585:         my $ip;
                   15586: 
1.993     raeburn  15587:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15588:             $ip = $name_to_ip{$dns};
                   15589:         }
                   15590:         if (!$ip) {
                   15591:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15592:             if (length($ip) == 4) { 
                   15593: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15594:             }
                   15595:         }
                   15596:         if ($ip) {
                   15597: 	    @hosts = get_hosts_from_ip($ip);
                   15598: 	    return $hosts[0];
                   15599:         }
                   15600:         return undef;
1.986     foxr     15601:     }
1.992     raeburn  15602: 
1.1074    raeburn  15603:     sub get_internet_names {
                   15604:         my ($lonid) = @_;
                   15605:         return if ($lonid eq '');
                   15606:         my ($idnref,$cached)=
                   15607:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15608:         if ($cached) {
                   15609:             return $idnref;
                   15610:         }
                   15611:         my $ip = &get_host_ip($lonid);
                   15612:         my @hosts = &get_hosts_from_ip($ip);
                   15613:         my %iphost = &get_iphost();
                   15614:         my (@idns,%seen);
                   15615:         foreach my $id (@hosts) {
                   15616:             my $dom = &host_domain($id);
                   15617:             my $prim_id = &domain($dom,'primary');
                   15618:             my $prim_ip = &get_host_ip($prim_id);
                   15619:             next if ($seen{$prim_ip});
                   15620:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15621:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15622:                     my $intdom = &internet_dom($id);
                   15623:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15624:                         push(@idns,$intdom);
                   15625:                     }
                   15626:                 }
                   15627:             }
                   15628:             $seen{$prim_ip} = 1;
                   15629:         }
1.1219    raeburn  15630:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15631:     }
                   15632: 
1.986     foxr     15633: }
                   15634: 
1.1079    raeburn  15635: sub all_loncaparevs {
1.1249    raeburn  15636:     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  15637: }
                   15638: 
1.1227    raeburn  15639: # ---------------------------------------------------------- Read loncaparev table
                   15640: {
                   15641:     sub load_loncaparevs { 
                   15642:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  15643:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  15644:                 while (my $configline=<$config>) {
                   15645:                     chomp($configline);
                   15646:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15647:                     $loncaparevs{$hostid}=$loncaparev;
                   15648:                 }
                   15649:                 close($config);
                   15650:             }
                   15651:         }
                   15652:     }
                   15653: }
                   15654: 
                   15655: # ---------------------------------------------------------- Read serverhostID table
                   15656: {
                   15657:     sub load_serverhomeIDs {
                   15658:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  15659:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  15660:                 while (my $configline=<$config>) {
                   15661:                     chomp($configline);
                   15662:                     my ($name,$id)=split(/:/,$configline);
                   15663:                     $serverhomeIDs{$name}=$id;
                   15664:                 }
                   15665:                 close($config);
                   15666:             }
                   15667:         }
                   15668:     }
                   15669: }
                   15670: 
                   15671: 
1.862     albertel 15672: BEGIN {
                   15673: 
                   15674: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15675:     unless ($readit) {
                   15676: {
                   15677:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15678:     %perlvar = (%perlvar,%{$configvars});
                   15679: }
                   15680: 
                   15681: 
1.1       albertel 15682: # ------------------------------------------------------ Read spare server file
                   15683: {
1.1359    raeburn  15684:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15685: 
                   15686:     while (my $configline=<$config>) {
                   15687:        chomp($configline);
1.284     matthew  15688:        if ($configline) {
1.784     albertel 15689: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15690: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15691: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15692:        }
                   15693:     }
1.448     albertel 15694:     close($config);
1.1       albertel 15695: }
1.11      www      15696: # ------------------------------------------------------------ Read permissions
                   15697: {
1.1359    raeburn  15698:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15699: 
                   15700:     while (my $configline=<$config>) {
1.448     albertel 15701: 	chomp($configline);
                   15702: 	if ($configline) {
                   15703: 	    my ($role,$perm)=split(/ /,$configline);
                   15704: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15705: 	}
1.11      www      15706:     }
1.448     albertel 15707:     close($config);
1.11      www      15708: }
                   15709: 
                   15710: # -------------------------------------------- Read plain texts for permissions
                   15711: {
1.1359    raeburn  15712:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15713: 
                   15714:     while (my $configline=<$config>) {
1.448     albertel 15715: 	chomp($configline);
                   15716: 	if ($configline) {
1.742     raeburn  15717: 	    my ($short,@plain)=split(/:/,$configline);
                   15718:             %{$prp{$short}} = ();
                   15719: 	    if (@plain > 0) {
                   15720:                 $prp{$short}{'std'} = $plain[0];
                   15721:                 for (my $i=1; $i<@plain; $i++) {
                   15722:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15723:                 }
                   15724:             }
1.448     albertel 15725: 	}
1.135     www      15726:     }
1.448     albertel 15727:     close($config);
1.135     www      15728: }
                   15729: 
                   15730: # ---------------------------------------------------------- Read package table
                   15731: {
1.1359    raeburn  15732:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15733: 
                   15734:     while (my $configline=<$config>) {
1.483     albertel 15735: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15736: 	chomp($configline);
                   15737: 	my ($short,$plain)=split(/:/,$configline);
                   15738: 	my ($pack,$name)=split(/\&/,$short);
                   15739: 	if ($plain ne '') {
                   15740: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15741: 	    $packagetab{$short}=$plain; 
                   15742: 	}
1.11      www      15743:     }
1.448     albertel 15744:     close($config);
1.329     matthew  15745: }
                   15746: 
1.1073    raeburn  15747: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  15748: 
                   15749: &load_loncaparevs();
1.1073    raeburn  15750: 
1.1074    raeburn  15751: # ---------------------------------------------------------- Read serverhostID table
                   15752: 
1.1227    raeburn  15753: &load_serverhomeIDs();
                   15754: 
                   15755: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15756: {
                   15757:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15758:     if (-e $file) {
                   15759:         my $parser = HTML::LCParser->new($file);
                   15760:         while (my $token = $parser->get_token()) {
                   15761:             if ($token->[0] eq 'S') {
                   15762:                 my $item = $token->[1];
                   15763:                 my $name = $token->[2]{'name'};
                   15764:                 my $value = $token->[2]{'value'};
1.1285    raeburn  15765:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  15766:                 my $namematch = $token->[2]{'namematch'};
                   15767:                 if ($item eq 'parameter') {
                   15768:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   15769:                         my $release = $parser->get_text();
                   15770:                         $release =~ s/(^\s*|\s*$ )//gx;
                   15771:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   15772:                     }
                   15773:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  15774:                     my $release = $parser->get_text();
                   15775:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  15776:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  15777:                 }
                   15778:             }
                   15779:         }
                   15780:     }
1.1073    raeburn  15781: }
                   15782: 
1.1138    raeburn  15783: # ---------------------------------------------------------- Read managers table
                   15784: {
                   15785:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  15786:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15787:             while (my $configline=<$config>) {
                   15788:                 chomp($configline);
                   15789:                 next if ($configline =~ /^\#/);
                   15790:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15791:                     $managerstab{$configline} = 1;
                   15792:                 }
                   15793:             }
                   15794:             close($config);
                   15795:         }
                   15796:     }
                   15797: }
                   15798: 
1.329     matthew  15799: # ------------- set up temporary directory
                   15800: {
1.1117    foxr     15801:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15802: 
1.11      www      15803: }
                   15804: 
1.1405    raeburn  15805: # ------------- set default texengine (domain default overrides this)
                   15806: {
                   15807:     $deftex = LONCAPA::texengine();
                   15808: }
                   15809: 
1.1416    raeburn  15810: # ------------- set default minimum length for passwords for internal auth users
                   15811: {
                   15812:     $passwdmin = LONCAPA::passwd_min();
                   15813: }
                   15814: 
1.794     albertel 15815: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15816: 				'compress_threshold'=> 20_000,
                   15817:  			        });
1.185     www      15818: 
1.281     www      15819: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15820: $dumpcount=0;
1.958     www      15821: $locknum=0;
1.22      www      15822: 
1.163     harris41 15823: &logtouch();
1.672     albertel 15824: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15825: $readit=1;
1.564     albertel 15826:     {
                   15827: 	use integer;
                   15828: 	my $test=(2**32)+1;
1.568     albertel 15829: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15830: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15831:     }
1.195     www      15832: }
1.1       albertel 15833: }
1.179     www      15834: 
1.1       albertel 15835: 1;
1.191     harris41 15836: __END__
                   15837: 
1.243     albertel 15838: =pod
                   15839: 
1.191     harris41 15840: =head1 NAME
                   15841: 
1.243     albertel 15842: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15843: 
                   15844: =head1 SYNOPSIS
                   15845: 
1.243     albertel 15846: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15847: 
                   15848:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15849: 
1.243     albertel 15850: Common parameters:
                   15851: 
                   15852: =over 4
                   15853: 
                   15854: =item *
                   15855: 
                   15856: $uname : an internal username (if $cname expecting a course Id specifically)
                   15857: 
                   15858: =item *
                   15859: 
                   15860: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15861: 
                   15862: =item *
                   15863: 
                   15864: $symb : a resource instance identifier
                   15865: 
                   15866: =item *
                   15867: 
                   15868: $namespace : the name of a .db file that contains the data needed or
                   15869: being set.
                   15870: 
                   15871: =back
                   15872: 
1.394     bowersj2 15873: =head1 OVERVIEW
1.191     harris41 15874: 
1.394     bowersj2 15875: lonnet provides subroutines which interact with the
                   15876: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15877: about classes, users, and resources.
1.243     albertel 15878: 
                   15879: For many of these objects you can also use this to store data about
                   15880: them or modify them in various ways.
1.191     harris41 15881: 
1.394     bowersj2 15882: =head2 Symbs
1.191     harris41 15883: 
1.394     bowersj2 15884: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15885: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15886: map, the resource number of the resource in the map, and the URL of
                   15887: the resource itself. The latter is somewhat redundant, but might help
                   15888: if maps change.
                   15889: 
                   15890: An example is
                   15891: 
                   15892:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15893: 
                   15894: The respective map entry is
                   15895: 
                   15896:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15897:   title="Problem 2">
                   15898:  </resource>
                   15899: 
                   15900: Symbs are used by the random number generator, as well as to store and
                   15901: restore data specific to a certain instance of for example a problem.
                   15902: 
                   15903: =head2 Storing And Retrieving Data
                   15904: 
                   15905: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15906: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15907: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15908: is is the non-critical message twin of cstore. These functions are for
                   15909: handlers to store a perl hash to a user's permanent data space in an
                   15910: easy manner, and to retrieve it again on another call. It is expected
                   15911: that a handler would use this once at the beginning to retrieve data,
                   15912: and then again once at the end to send only the new data back.
                   15913: 
                   15914: The data is stored in the user's data directory on the user's
                   15915: homeserver under the ID of the course.
                   15916: 
                   15917: The hash that is returned by restore will have all of the previous
                   15918: value for all of the elements of the hash.
                   15919: 
                   15920: Example:
                   15921: 
                   15922:  #creating a hash
                   15923:  my %hash;
                   15924:  $hash{'foo'}='bar';
                   15925: 
                   15926:  #storing it
                   15927:  &Apache::lonnet::cstore(\%hash);
                   15928: 
                   15929:  #changing a value
                   15930:  $hash{'foo'}='notbar';
                   15931: 
                   15932:  #adding a new value
                   15933:  $hash{'bar'}='foo';
                   15934:  &Apache::lonnet::cstore(\%hash);
                   15935: 
                   15936:  #retrieving the hash
                   15937:  my %history=&Apache::lonnet::restore();
                   15938: 
                   15939:  #print the hash
                   15940:  foreach my $key (sort(keys(%history))) {
                   15941:    print("\%history{$key} = $history{$key}");
                   15942:  }
                   15943: 
                   15944: Will print out:
1.191     harris41 15945: 
1.394     bowersj2 15946:  %history{1:foo} = bar
                   15947:  %history{1:keys} = foo:timestamp
                   15948:  %history{1:timestamp} = 990455579
                   15949:  %history{2:bar} = foo
                   15950:  %history{2:foo} = notbar
                   15951:  %history{2:keys} = foo:bar:timestamp
                   15952:  %history{2:timestamp} = 990455580
                   15953:  %history{bar} = foo
                   15954:  %history{foo} = notbar
                   15955:  %history{timestamp} = 990455580
                   15956:  %history{version} = 2
                   15957: 
                   15958: Note that the special hash entries C<keys>, C<version> and
                   15959: C<timestamp> were added to the hash. C<version> will be equal to the
                   15960: total number of versions of the data that have been stored. The
                   15961: C<timestamp> attribute will be the UNIX time the hash was
                   15962: stored. C<keys> is available in every historical section to list which
                   15963: keys were added or changed at a specific historical revision of a
                   15964: hash.
                   15965: 
                   15966: B<Warning>: do not store the hash that restore returns directly. This
                   15967: will cause a mess since it will restore the historical keys as if the
                   15968: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15969: 
1.394     bowersj2 15970: Calling convention:
1.191     harris41 15971: 
1.1225    raeburn  15972:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  15973:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15974: 
1.394     bowersj2 15975: For more detailed information, see lonnet specific documentation.
1.191     harris41 15976: 
1.394     bowersj2 15977: =head1 RETURN MESSAGES
1.191     harris41 15978: 
1.394     bowersj2 15979: =over 4
1.191     harris41 15980: 
1.394     bowersj2 15981: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15982: 
1.394     bowersj2 15983: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15984: when the connection is brought back up
1.191     harris41 15985: 
1.394     bowersj2 15986: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15987: for later delivery
1.191     harris41 15988: 
1.967     bisitz   15989: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15990: 
1.394     bowersj2 15991: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15992: that was requested
1.191     harris41 15993: 
1.243     albertel 15994: =back
1.191     harris41 15995: 
1.243     albertel 15996: =head1 PUBLIC SUBROUTINES
1.191     harris41 15997: 
1.243     albertel 15998: =head2 Session Environment Functions
1.191     harris41 15999: 
1.243     albertel 16000: =over 4
1.191     harris41 16001: 
1.394     bowersj2 16002: =item * 
                   16003: X<appenv()>
1.949     raeburn  16004: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 16005: the user envirnoment file, and will be restored for each access this
1.620     albertel 16006: user makes during this session, also modifies the %env for the current
1.949     raeburn  16007: process. Optional rolesarrayref - if defined contains a reference to an array
                   16008: of roles which are exempt from the restriction on modifying user.role entries 
                   16009: in the user's environment.db and in %env.    
1.191     harris41 16010: 
                   16011: =item *
1.394     bowersj2 16012: X<delenv()>
1.987     raeburn  16013: B<delenv($delthis,$regexp)>: removes all items from the session
                   16014: environment file that begin with $delthis. If the 
                   16015: optional second arg - $regexp - is true, $delthis is treated as a 
                   16016: regular expression, otherwise \Q$delthis\E is used. 
                   16017: The values are also deleted from the current processes %env.
1.191     harris41 16018: 
1.795     albertel 16019: =item * get_env_multiple($name) 
                   16020: 
                   16021: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   16022: values may be defined and end up as an array ref.
                   16023: 
                   16024: returns an array of values
                   16025: 
1.243     albertel 16026: =back
                   16027: 
                   16028: =head2 User Information
1.191     harris41 16029: 
1.243     albertel 16030: =over 4
1.191     harris41 16031: 
                   16032: =item *
1.394     bowersj2 16033: X<queryauthenticate()>
                   16034: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 16035: authentication scheme
                   16036: 
                   16037: =item *
1.394     bowersj2 16038: X<authenticate()>
1.1073    raeburn  16039: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 16040: authenticate user from domain's lib servers (first use the current
                   16041: one). C<$upass> should be the users password.
1.1073    raeburn  16042: $checkdefauth is optional (value is 1 if a check should be made to
                   16043:    authenticate user using default authentication method, and allow
                   16044:    account creation if username does not have account in the domain).
                   16045: $clientcancheckhost is optional (value is 1 if checking whether the
                   16046:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 16047: 
                   16048: =item *
1.394     bowersj2 16049: X<homeserver()>
                   16050: B<homeserver($uname,$udom)>: find the server which has
                   16051: the user's directory and files (there must be only one), this caches
                   16052: the answer, and also caches if there is a borken connection.
1.191     harris41 16053: 
                   16054: =item *
1.394     bowersj2 16055: X<idget()>
1.1300    raeburn  16056: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   16057: a list of student/employee IDs or clicker IDs
                   16058: (student/employee IDs are a unique resource in a domain, there must be 
                   16059: only 1 ID per username, and only 1 username per ID in a specific domain).
                   16060: clickerIDs are not necessarily unique, as students might share clickers.
                   16061: (returns hash: id=>name,id=>name)
1.191     harris41 16062: 
                   16063: =item *
1.394     bowersj2 16064: X<idrget()>
                   16065: B<idrget($udom,@unames)>: find the IDs behind a list of
                   16066: usernames (returns hash: name=>id,name=>id)
1.191     harris41 16067: 
                   16068: =item *
1.394     bowersj2 16069: X<idput()>
1.1300    raeburn  16070: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   16071: names and associated student/employee IDs or clicker IDs.
                   16072: 
                   16073: =item *
                   16074: X<iddel()>
                   16075: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   16076: student/employee ID or clicker ID username look-ups from domain.
                   16077: The homeserver ($uhome) and namespace ($namespace) are optional.
                   16078: If no $uhome is provided, it will be determined usig &homeserver()
                   16079: for each user.  If no $namespace is provided, the default is ids.
                   16080: 
                   16081: =item *
                   16082: X<updateclickers()>
                   16083: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   16084: clicker ID-to-username look-ups in clickers.db on library server.
                   16085: Permitted actions are add or del (i.e., add or delete). The 
                   16086: clickers.db contains clickerID as keys (escaped), and each corresponding
                   16087: value is an escaped comma-separated list of usernames (for whom the
                   16088: library server is the homeserver), who registered that particular ID.
                   16089: If $critical is true, the update will be sent via &critical, otherwise
                   16090: &reply() will be used.
1.191     harris41 16091: 
                   16092: =item *
1.394     bowersj2 16093: X<rolesinit()>
1.1169    droeschl 16094: B<rolesinit($udom,$username)>: get user privileges.
                   16095: returns user role, first access and timer interval hashes
1.243     albertel 16096: 
                   16097: =item *
1.1171    droeschl 16098: X<privileged()>
                   16099: B<privileged($username,$domain)>: returns a true if user has a
                   16100: privileged and active role (i.e. su or dc), false otherwise.
                   16101: 
                   16102: =item *
1.551     albertel 16103: X<getsection()>
                   16104: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 16105: course $cname, return section name/number or '' for "not in course"
                   16106: and '-1' for "no section"
                   16107: 
                   16108: =item *
1.394     bowersj2 16109: X<userenvironment()>
                   16110: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 16111: passed in @what from the requested user's environment, returns a hash
                   16112: 
1.858     raeburn  16113: =item * 
                   16114: X<userlog_query()>
1.859     albertel 16115: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   16116: activity.log file. %filters defines filters applied when parsing the
                   16117: log file. These can be start or end timestamps, or the type of action
                   16118: - log to look for Login or Logout events, check for Checkin or
                   16119: Checkout, role for role selection. The response is in the form
                   16120: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   16121: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  16122: 
1.243     albertel 16123: =back
                   16124: 
                   16125: =head2 User Roles
                   16126: 
                   16127: =over 4
                   16128: 
                   16129: =item *
                   16130: 
1.1284    raeburn  16131: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   16132: returns codes for allowed actions.
                   16133: 
                   16134: The first argument is required, all others are optional.
                   16135: 
                   16136: $priv is the privilege being checked.
                   16137: $uri contains additional information about what is being checked for access (e.g.,
                   16138: URL, course ID etc.). 
                   16139: $symb is the unique resource instance identifier in a course; if needed,
                   16140: but not provided, it will be retrieved via a call to &symbread(). 
                   16141: $role is the role for which a priv is being checked (only used if priv is evb). 
                   16142: $clientip is the user's IP address (only used when checking for access to portfolio 
                   16143: files).
                   16144: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   16145: prevents recursive calls to &allowed.
                   16146: 
1.243     albertel 16147:  F: full access
                   16148:  U,I,K: authentication modes (cxx only)
                   16149:  '': forbidden
                   16150:  1: user needs to choose course
                   16151:  2: browse allowed
1.766     albertel 16152:  A: passphrase authentication needed
1.1284    raeburn  16153:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  16154:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 16155: 
                   16156: =item *
                   16157: 
1.1192    raeburn  16158: constructaccess($url,$setpriv) : check for access to construction space URL
                   16159: 
                   16160: See if the owner domain and name in the URL match those in the
                   16161: expected environment.  If so, return three element list
                   16162: ($ownername,$ownerdomain,$ownerhome).
                   16163: 
                   16164: Otherwise return the null string.
                   16165: 
                   16166: If second argument 'setpriv' is true, it assigns the privileges,
                   16167: and returns the same three element list, unless the owner has
                   16168: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   16169: in which case the null string is returned.
                   16170: 
                   16171: =item *
                   16172: 
1.1326    raeburn  16173: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   16174: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   16175: for system, domain, and course level. $uname and $udom are optional (current
                   16176: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 16177: 
                   16178: =item *
                   16179: 
1.988     raeburn  16180: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   16181: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  16182: $type is Course (default) or Community.
1.988     raeburn  16183: If $forcedefault evaluates to true, text returned will be default 
                   16184: text for $type. Otherwise, if this is a course, the text returned 
                   16185: will be a custom name for the role (if defined in the course's 
                   16186: environment).  If no custom name is defined the default is returned.
                   16187:    
1.832     raeburn  16188: =item *
                   16189: 
1.1219    raeburn  16190: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  16191: All arguments are optional. Returns a hash of a roles, either for
                   16192: co-author/assistant author roles for a user's Construction Space
1.906     albertel 16193: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  16194: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   16195: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   16196: For each key, value is set to colon-separated start and end times for
                   16197: the role.  If no username and domain are specified, will default to
1.934     raeburn  16198: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  16199: of role statuses (active, future or previous), roles 
                   16200: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   16201: to restrict the list of roles reported. If no array ref is 
                   16202: provided for types, will default to return only active roles.
1.834     albertel 16203: 
1.1195    raeburn  16204: =item *
                   16205: 
                   16206: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  16207: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   16208: 
                   16209: Additional optional arguments are: $type (if role checking is to be restricted 
                   16210: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  16211: available roles) or future (roles available in the future), and
                   16212: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  16213: have active Domain Coordinator role in course's domain or in additional
                   16214: domains (specified in 'Domains to check for privileged users' in course
                   16215: environment -- set via:  Course Settings -> Classlists and staff listing).
                   16216: 
                   16217: =item *
                   16218: 
                   16219: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   16220: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   16221: $possdomains and $possroles are optional array refs -- to domains to check and
                   16222: roles to check.  If $possdomains is not specified, a dump will be done of the
                   16223: users' roles.db to check for a dc or su role in any domain. This can be
                   16224: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   16225: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   16226: this then allows &privileged_by_domain() to be used, which caches the identity
                   16227: of privileged users, eliminating the need for repeated calls to &dump().
                   16228: 
                   16229: =item *
                   16230: 
                   16231: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   16232: where the outer hash keys are domains specified in the $possdomains array ref,
                   16233: next inner hash keys are privileged roles specified in the $roles array ref,
                   16234: and the innermost hash contains key = value pairs for username:domain = end:start
                   16235: for active or future "privileged" users with that role in that domain. To avoid
                   16236: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   16237: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  16238: 
1.243     albertel 16239: =back
                   16240: 
                   16241: =head2 User Modification
                   16242: 
                   16243: =over 4
                   16244: 
                   16245: =item *
                   16246: 
1.957     raeburn  16247: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 16248: user for the level given by URL.  Optional start and end dates (leave empty
                   16249: string or zero for "no date")
1.191     harris41 16250: 
                   16251: =item *
                   16252: 
1.243     albertel 16253: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   16254: change a users, password, possible return values are: ok,
                   16255: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   16256: refused
1.191     harris41 16257: 
                   16258: =item *
                   16259: 
1.243     albertel 16260: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 16261: 
                   16262: =item *
                   16263: 
1.1058    raeburn  16264: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   16265:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   16266: 
                   16267: will update user information (firstname,middlename,lastname,generation,
                   16268: permanentemail), and if forceid is true, student/employee ID also.
                   16269: A user's institutional affiliation(s) can also be updated.
                   16270: User information fields will not be overwritten with empty entries 
                   16271: unless the field is included in the $candelete array reference.
                   16272: This array is included when a single user is modified via "Manage Users",
                   16273: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 16274: 
                   16275: =item *
                   16276: 
1.286     matthew  16277: modifystudent
                   16278: 
1.957     raeburn  16279: modify a student's enrollment and identification information.
1.1235    raeburn  16280: The course id is resolved based on the current user's environment.  
                   16281: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  16282: associated with a course.
                   16283: 
1.297     matthew  16284: This call is essentially a wrapper for lonnet::modifyuser and
                   16285: lonnet::modify_student_enrollment
1.286     matthew  16286: 
                   16287: Inputs: 
                   16288: 
                   16289: =over 4
                   16290: 
1.957     raeburn  16291: =item B<$udom> Student's loncapa domain
1.286     matthew  16292: 
1.957     raeburn  16293: =item B<$uname> Student's loncapa login name
1.286     matthew  16294: 
1.964     bisitz   16295: =item B<$uid> Student/Employee ID
1.286     matthew  16296: 
1.957     raeburn  16297: =item B<$umode> Student's authentication mode
1.286     matthew  16298: 
1.957     raeburn  16299: =item B<$upass> Student's password
1.286     matthew  16300: 
1.957     raeburn  16301: =item B<$first> Student's first name
1.286     matthew  16302: 
1.957     raeburn  16303: =item B<$middle> Student's middle name
1.286     matthew  16304: 
1.957     raeburn  16305: =item B<$last> Student's last name
1.286     matthew  16306: 
1.957     raeburn  16307: =item B<$gene> Student's generation
1.286     matthew  16308: 
1.957     raeburn  16309: =item B<$usec> Student's section in course
1.286     matthew  16310: 
                   16311: =item B<$end> Unix time of the roles expiration
                   16312: 
                   16313: =item B<$start> Unix time of the roles start date
                   16314: 
                   16315: =item B<$forceid> If defined, allow $uid to be changed
                   16316: 
                   16317: =item B<$desiredhome> server to use as home server for student
                   16318: 
1.957     raeburn  16319: =item B<$email> Student's permanent e-mail address
                   16320: 
                   16321: =item B<$type> Type of enrollment (auto or manual)
                   16322: 
1.963     raeburn  16323: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   16324: 
                   16325: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  16326: 
1.963     raeburn  16327: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  16328: 
1.963     raeburn  16329: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  16330: 
1.1216    raeburn  16331: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   16332: 
                   16333: =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  16334: 
1.286     matthew  16335: =back
1.297     matthew  16336: 
                   16337: =item *
                   16338: 
                   16339: modify_student_enrollment
                   16340: 
1.1235    raeburn  16341: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  16342: 'role.request.course' must be defined for this function to proceed.
                   16343: 
                   16344: Inputs:
                   16345: 
                   16346: =over 4
                   16347: 
1.1235    raeburn  16348: =item $udom, student's domain
1.297     matthew  16349: 
1.1235    raeburn  16350: =item $uname, student's name
1.297     matthew  16351: 
1.1235    raeburn  16352: =item $uid, student's user id
1.297     matthew  16353: 
1.1235    raeburn  16354: =item $first, student's first name
1.297     matthew  16355: 
                   16356: =item $middle
                   16357: 
                   16358: =item $last
                   16359: 
                   16360: =item $gene
                   16361: 
                   16362: =item $usec
                   16363: 
                   16364: =item $end
                   16365: 
                   16366: =item $start
                   16367: 
1.957     raeburn  16368: =item $type
                   16369: 
                   16370: =item $locktype
                   16371: 
                   16372: =item $cid
                   16373: 
                   16374: =item $selfenroll
                   16375: 
                   16376: =item $context
                   16377: 
1.1216    raeburn  16378: =item $credits, number of credits student will earn from this class
                   16379: 
1.1314    raeburn  16380: =item $instsec, institutional course section code for student
                   16381: 
1.297     matthew  16382: =back
                   16383: 
1.191     harris41 16384: 
                   16385: =item *
                   16386: 
1.243     albertel 16387: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   16388: custom role; give a custom role to a user for the level given by URL.  Specify
                   16389: name and domain of role author, and role name
1.191     harris41 16390: 
                   16391: =item *
                   16392: 
1.243     albertel 16393: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 16394: 
                   16395: =item *
                   16396: 
1.243     albertel 16397: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   16398: 
                   16399: =back
                   16400: 
                   16401: =head2 Course Infomation
                   16402: 
                   16403: =over 4
1.191     harris41 16404: 
                   16405: =item *
                   16406: 
1.1118    foxr     16407: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 16408: specified course id, including all environment settings for the
                   16409: course, the description of the course will be in the hash under the
                   16410: key 'description'
1.191     harris41 16411: 
1.1118    foxr     16412: $options is an optional parameter that if supplied is a hash reference that controls
                   16413: what how this function works.  It has the following key/values:
                   16414: 
                   16415: =over 4
                   16416: 
                   16417: =item freshen_cache
                   16418: 
                   16419: If defined, and the environment cache for the course is valid, it is 
                   16420: returned in the returned hash.
                   16421: 
                   16422: =item one_time
                   16423: 
                   16424: If defined, the last cache time is set to _now_
                   16425: 
                   16426: =item user
                   16427: 
                   16428: If defined, the supplied username is used instead of the current user.
                   16429: 
                   16430: 
                   16431: =back
                   16432: 
1.191     harris41 16433: =item *
                   16434: 
1.624     albertel 16435: resdata($name,$domain,$type,@which) : request for current parameter
                   16436: setting for a specific $type, where $type is either 'course' or 'user',
                   16437: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  16438: answers for 10 minutes.
1.243     albertel 16439: 
1.877     foxr     16440: =item *
                   16441: 
                   16442: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16443: data base, returning a hash that is keyed by the resource name and has
                   16444: values that are the resource value.  I believe that the timestamps and
                   16445: versions are also returned.
                   16446: 
1.1236    raeburn  16447: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   16448: supplemental content area. This routine caches the number of files for 
                   16449: 10 minutes.
                   16450: 
1.243     albertel 16451: =back
                   16452: 
                   16453: =head2 Course Modification
                   16454: 
                   16455: =over 4
1.191     harris41 16456: 
                   16457: =item *
                   16458: 
1.243     albertel 16459: writecoursepref($courseid,%prefs) : write preferences (environment
                   16460: database) for a course
1.191     harris41 16461: 
                   16462: =item *
                   16463: 
1.1011    raeburn  16464: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16465: 
                   16466: =item *
                   16467: 
1.1038    raeburn  16468: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16469: 
1.1167    droeschl 16470: =item *
                   16471: 
                   16472: is_course($courseid), is_course($cdom, $cnum)
                   16473: 
                   16474: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16475: two component version $cdom, $cnum. It checks if the specified course exists.
                   16476: 
                   16477: Returns:
                   16478:     undef if the course doesn't exist, otherwise
                   16479:     in scalar context the combined courseid.
                   16480:     in list context the two components of the course identifier, domain and 
                   16481:     courseid.    
                   16482: 
1.243     albertel 16483: =back
                   16484: 
1.1401    raeburn  16485: =head2 Bubblesheet Configuration
                   16486: 
                   16487: =over 4
                   16488: 
                   16489: =item *
                   16490: 
                   16491: get_scantron_config($which)
                   16492: 
                   16493: $which - the name of the configuration to parse from the file.
                   16494: 
                   16495: Parses and returns the bubblesheet configuration line selected as a
                   16496: hash of configuration file fields.
                   16497: 
                   16498: 
                   16499: Returns:
                   16500:     If the named configuration is not in the file, an empty
                   16501:     hash is returned.
                   16502: 
                   16503:     a hash with the fields
                   16504:       name         - internal name for the this configuration setup
                   16505:       description  - text to display to operator that describes this config
                   16506:       CODElocation - if 0 or the string 'none'
                   16507:                           - no CODE exists for this config
                   16508:                      if -1 || the string 'letter'
                   16509:                           - a CODE exists for this config and is
                   16510:                             a string of letters
                   16511:                      Unsupported value (but planned for future support)
                   16512:                           if a positive integer
                   16513:                                - The CODE exists as the first n items from
                   16514:                                  the question section of the form
                   16515:                           if the string 'number'
                   16516:                                - The CODE exists for this config and is
                   16517:                                  a string of numbers
                   16518:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16519:                      the CODE starts
                   16520:       CODElength  - length of the CODE
                   16521:       IDstart     - column where the student/employee ID starts
                   16522:       IDlength    - length of the student/employee ID info
                   16523:       Qstart      - column where the information from the bubbled
                   16524:                     'questions' start
                   16525:       Qlength     - number of columns comprising a single bubble line from
                   16526:                     the sheet. (usually either 1 or 10)
                   16527:       Qon         - either a single character representing the character used
                   16528:                     to signal a bubble was chosen in the positional setup, or
                   16529:                     the string 'letter' if the letter of the chosen bubble is
                   16530:                     in the final, or 'number' if a number representing the
                   16531:                     chosen bubble is in the file (1->A 0->J)
                   16532:       Qoff        - the character used to represent that a bubble was
                   16533:                     left blank
                   16534:       PaperID     - if the scanning process generates a unique number for each
                   16535:                     sheet scanned the column that this ID number starts in
                   16536:       PaperIDlength - number of columns that comprise the unique ID number
                   16537:                       for the sheet of paper
                   16538:       FirstName   - column that the first name starts in
                   16539:       FirstNameLength - number of columns that the first name spans
                   16540:       LastName    - column that the last name starts in
                   16541:       LastNameLength - number of columns that the last name spans
                   16542:       BubblesPerRow - number of bubbles available in each row used to
                   16543:                       bubble an answer. (If not specified, 10 assumed).
                   16544: 
                   16545: 
                   16546: =item *
                   16547: 
                   16548: get_scantronformat_file($cdom)
                   16549: 
                   16550: $cdom - the course's domain (optional); if not supplied, uses
                   16551: domain for current $env{'request.course.id'}.
                   16552: 
                   16553: Returns an array containing lines from the scantron format file for
                   16554: the domain of the course.
                   16555: 
                   16556: If a url for a custom.tab file is listed in domain's configuration.db,
                   16557: lines are from this file.
                   16558: 
                   16559: Otherwise, if a default.tab has been published in RES space by the
                   16560: domainconfig user, lines are from this file.
                   16561: 
                   16562: Otherwise, fall back to getting lines from the legacy file on the
                   16563: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16564: 
                   16565: =back
                   16566: 
1.243     albertel 16567: =head2 Resource Subroutines
                   16568: 
                   16569: =over 4
1.191     harris41 16570: 
                   16571: =item *
                   16572: 
1.243     albertel 16573: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16574: 
                   16575: =item *
                   16576: 
1.243     albertel 16577: repcopy($filename) : subscribes to the requested file, and attempts to
                   16578: replicate from the owning library server, Might return
1.607     raeburn  16579: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16580: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16581: resource. Expects the local filesystem pathname
                   16582: (/home/httpd/html/res/....)
                   16583: 
                   16584: =back
                   16585: 
                   16586: =head2 Resource Information
                   16587: 
                   16588: =over 4
1.191     harris41 16589: 
                   16590: =item *
                   16591: 
1.1228    raeburn  16592: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16593: and returns the value of a variety of different possible values,
                   16594: $varname should be a request string, and the other parameters can be
                   16595: used to specify who and what one is asking about. Ordinarily, $cid 
                   16596: does not need to be specified, as it is retrived from 
                   16597: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16598: within lonuserstate::loadmap() when initializing a course, before
                   16599: $env{'request.course.id'} has been set, so it needs to be provided
                   16600: in that one case.
1.243     albertel 16601: 
                   16602: Possible values for $varname are environment.lastname (or other item
                   16603: from the envirnment hash), user.name (or someother aspect about the
                   16604: user), resource.0.maxtries (or some other part and parameter of a
                   16605: resource)
1.204     albertel 16606: 
                   16607: =item *
                   16608: 
1.243     albertel 16609: directcondval($number) : get current value of a condition; reads from a state
                   16610: string
1.204     albertel 16611: 
                   16612: =item *
                   16613: 
1.243     albertel 16614: condval($condidx) : value of condition index based on state
1.204     albertel 16615: 
                   16616: =item *
                   16617: 
1.1362    raeburn  16618: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16619: resource's metadata, $what should be either a specific key, or either
                   16620: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  16621: packages that this resource currently uses, the last 3 arguments are 
                   16622: only used internally for recursive metadata.
                   16623: 
                   16624: the toolsymb is only used where the uri is for an external tool (for which
                   16625: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16626: 
1.1371    raeburn  16627: this function automatically caches all requests except any made recursively
                   16628: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   16629: defined).
1.191     harris41 16630: 
                   16631: =item *
                   16632: 
1.243     albertel 16633: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16634: network of library servers; returns file handle of where SQL and regex results
                   16635: will be stored for query
1.191     harris41 16636: 
                   16637: =item *
                   16638: 
1.1282    raeburn  16639: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   16640: return symbolic list entry (all arguments optional). 
                   16641: 
                   16642: Args: filename is the filename (including path) for the file for which a symb 
                   16643: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   16644: to check access status if more than one resource was found in the bighash 
                   16645: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   16646: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   16647: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16648: cause possible symbs to be checked to determine if they are subject to content
                   16649: blocking, if so they will not be included as possible symbs; possibles is a
                   16650: ref to a hash, which, as a side effect, will be populated with all possible 
                   16651: symbs (content blocking not tested).
                   16652:  
1.243     albertel 16653: returns the data handle
1.191     harris41 16654: 
                   16655: =item *
                   16656: 
1.1190    raeburn  16657: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   16658: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16659: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  16660: on failure, user must be in a course, as it assumes the existence of
                   16661: the course initial hash, and uses $env('request.course.id'}.  The third
                   16662: arg is an optional reference to a scalar.  If this arg is passed in the 
                   16663: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16664: encrypted; otherwise it will be null.  
1.191     harris41 16665: 
                   16666: =item *
                   16667: 
1.243     albertel 16668: symbclean($symb) : removes versions numbers from a symb, returns the
                   16669: cleaned symb
1.191     harris41 16670: 
                   16671: =item *
                   16672: 
1.243     albertel 16673: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16674: course map, user must be in a course for it to work.
1.191     harris41 16675: 
                   16676: =item *
                   16677: 
1.243     albertel 16678: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16679: 
                   16680: =item *
                   16681: 
1.243     albertel 16682: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16683: a random seed, all arguments are optional, if they aren't sent it uses the
                   16684: environment to derive them. Note: if symb isn't sent and it can't get one
                   16685: from &symbread it will use the current time as its return value
1.191     harris41 16686: 
                   16687: =item *
                   16688: 
1.243     albertel 16689: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16690: unfakeable, receipt
1.191     harris41 16691: 
                   16692: =item *
                   16693: 
1.620     albertel 16694: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16695: 
                   16696: =item *
                   16697: 
1.243     albertel 16698: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16699: 
                   16700: =item *
                   16701: 
1.243     albertel 16702: 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 16703: 
                   16704: =item *
                   16705: 
1.243     albertel 16706: 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 16707: 
                   16708: =item *
                   16709: 
1.243     albertel 16710: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16711: 
                   16712: =item *
                   16713: 
1.243     albertel 16714: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16715: forcing spreadsheet to reevaluate the resource scores next time.
                   16716: 
1.1195    raeburn  16717: =item * 
                   16718: 
1.1196    raeburn  16719: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16720: when viewing in course context.
1.1195    raeburn  16721: 
1.1196    raeburn  16722:  input: six args -- filename (decluttered), course number, course domain,
                   16723:                     url, symb (if registered) and group (if this is a 
                   16724:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  16725: 
1.1196    raeburn  16726:  output: array of five scalars --
1.1195    raeburn  16727:          $cfile -- url for file editing if editable on current server
                   16728:          $home -- homeserver of resource (i.e., for author if published,
                   16729:                                           or course if uploaded.).
                   16730:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  16731:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   16732:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  16733: 
                   16734: =item *
                   16735: 
                   16736: is_course_upload($file,$cnum,$cdom)
                   16737: 
                   16738: Used in course context to determine if current file was uploaded to 
                   16739: the course (i.e., would be found in /userfiles/docs on the course's 
                   16740: homeserver.
                   16741: 
                   16742:   input: 3 args -- filename (decluttered), course number and course domain.
                   16743:   output: boolean -- 1 if file was uploaded.
                   16744: 
1.243     albertel 16745: =back
                   16746: 
                   16747: =head2 Storing/Retreiving Data
                   16748: 
                   16749: =over 4
1.191     harris41 16750: 
                   16751: =item *
                   16752: 
1.1269    raeburn  16753: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   16754: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16755: the remaining args aren't required and if they aren't passed or are '' they will
                   16756: be derived from the env (with the exception of $laststore, which is an 
                   16757: optional arg used when a user's submission is stored in grading).
                   16758: $laststore is $version=$timestamp, where $version is the most recent version
                   16759: number retrieved for the corresponding $symb in the $namespace db file, and
                   16760: $timestamp is the timestamp for that transaction (UNIX time).
                   16761: $laststore is currently only passed when cstore() is called by 
                   16762: structuretags::finalize_storage().
1.191     harris41 16763: 
                   16764: =item *
                   16765: 
1.1269    raeburn  16766: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   16767: but uses critical subroutine
1.191     harris41 16768: 
                   16769: =item *
                   16770: 
1.243     albertel 16771: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16772: all args are optional
1.191     harris41 16773: 
                   16774: =item *
                   16775: 
1.717     albertel 16776: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16777: dumps the complete (or key matching regexp) namespace into a hash
                   16778: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16779: normally &store()ed into
                   16780: 
                   16781: $range should be either an integer '100' (give me the first 100
                   16782:                                            matching records)
                   16783:               or be  two integers sperated by a - with no spaces
                   16784:                  '30-50' (give me the 30th through the 50th matching
                   16785:                           records)
                   16786: 
                   16787: 
                   16788: =item *
                   16789: 
1.1269    raeburn  16790: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16791: replaces a &store() version of data with a replacement set of data
                   16792: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  16793: reference. If $tolog is true, the transaction is logged in the courselog
                   16794: with an action=PUTSTORE.
1.717     albertel 16795: 
                   16796: =item *
                   16797: 
1.243     albertel 16798: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16799: works very similar to store/cstore, but all data is stored in a
                   16800: temporary location and can be reset using tmpreset, $storehash should
                   16801: be a hash reference, returns nothing on success
1.191     harris41 16802: 
                   16803: =item *
                   16804: 
1.243     albertel 16805: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16806: similar to restore, but all data is stored in a temporary location and
                   16807: can be reset using tmpreset. Returns a hash of values on success,
                   16808: error string otherwise.
1.191     harris41 16809: 
                   16810: =item *
                   16811: 
1.243     albertel 16812: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16813: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16814: 
                   16815: =item *
                   16816: 
1.243     albertel 16817: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16818: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16819: 
                   16820: =item *
                   16821: 
1.243     albertel 16822: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16823: namesp ($udom and $uname are optional)
1.191     harris41 16824: 
                   16825: =item *
                   16826: 
1.702     albertel 16827: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16828: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16829: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16830: 
1.702     albertel 16831: $range should be either an integer '100' (give me the first 100
                   16832:                                            matching records)
                   16833:               or be  two integers sperated by a - with no spaces
                   16834:                  '30-50' (give me the 30th through the 50th matching
                   16835:                           records)
1.449     matthew  16836: =item *
                   16837: 
                   16838: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16839: $store can be a scalar, an array reference, or if the amount to be 
                   16840: incremented is > 1, a hash reference.
                   16841: 
                   16842: ($udom and $uname are optional)
1.191     harris41 16843: 
                   16844: =item *
                   16845: 
1.243     albertel 16846: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16847: ($udom and $uname are optional)
1.191     harris41 16848: 
                   16849: =item *
                   16850: 
1.243     albertel 16851: cput($namespace,$storehash,$udom,$uname) : critical put
                   16852: ($udom and $uname are optional)
1.191     harris41 16853: 
                   16854: =item *
                   16855: 
1.748     albertel 16856: newput($namespace,$storehash,$udom,$uname) :
                   16857: 
                   16858: Attempts to store the items in the $storehash, but only if they don't
                   16859: currently exist, if this succeeds you can be certain that you have 
                   16860: successfully created a new key value pair in the $namespace db.
                   16861: 
                   16862: 
                   16863: Args:
                   16864:  $namespace: name of database to store values to
                   16865:  $storehash: hashref to store to the db
                   16866:  $udom: (optional) domain of user containing the db
                   16867:  $uname: (optional) name of user caontaining the db
                   16868: 
                   16869: Returns:
                   16870:  'ok' -> succeeded in storing all keys of $storehash
                   16871:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16872:                         least <key> already existed in the db (other
                   16873:                         requested keys may also already exist)
1.967     bisitz   16874:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16875:  'con_lost' -> unable to contact request server
                   16876:  'refused' -> action was not allowed by remote machine
                   16877: 
                   16878: 
                   16879: =item *
                   16880: 
1.243     albertel 16881: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16882: reference filled in from namesp (encrypts the return communication)
                   16883: ($udom and $uname are optional)
1.191     harris41 16884: 
                   16885: =item *
                   16886: 
1.243     albertel 16887: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16888: critical subroutine
                   16889: 
1.806     raeburn  16890: =item *
                   16891: 
1.860     raeburn  16892: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16893: array reference filled in from namespace found in domain level on either
                   16894: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16895: 
                   16896: =item *
                   16897: 
1.860     raeburn  16898: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16899: domain level either on specified domain server ($uhome) or primary domain 
                   16900: server ($udom and $uhome are optional)
1.806     raeburn  16901: 
1.943     raeburn  16902: =item * 
                   16903: 
1.1240    raeburn  16904: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   16905: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16906: the target domain.
                   16907: 
                   16908: May also include additional key => value pairs for the following groups:
                   16909: 
                   16910: =over
                   16911: 
                   16912: =item
                   16913: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16914: 
                   16915: =over
                   16916: 
                   16917: =item defaultquota, authorquota
                   16918: 
                   16919: =back
                   16920: 
                   16921: =item
                   16922: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16923: portfolio for users).
                   16924: 
                   16925: =over
                   16926: 
                   16927: =item
                   16928: aboutme, blog, webdav, portfolio
                   16929: 
                   16930: =back
                   16931: 
                   16932: =item
                   16933: requestcourses: ability to request courses, and how requests are processed.
                   16934: 
                   16935: =over
                   16936: 
                   16937: =item
1.1305    raeburn  16938: official, unofficial, community, textbook, placement
1.1240    raeburn  16939: 
                   16940: =back
                   16941: 
                   16942: =item
                   16943: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16944: 
                   16945: =over
                   16946: 
                   16947: =item
1.1256    raeburn  16948: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  16949: 
                   16950: =back
                   16951: 
                   16952: =item
                   16953: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16954: for course's uploaded content.
                   16955: 
                   16956: =over
                   16957: 
                   16958: =item
1.1246    raeburn  16959: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  16960: communityquota, textbookquota, placementquota
1.1240    raeburn  16961: 
                   16962: =back
                   16963: 
                   16964: =item
                   16965: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16966: on your servers.
                   16967: 
                   16968: =over
                   16969: 
                   16970: =item 
                   16971: remotesessions, hostedsessions
                   16972: 
                   16973: =back
                   16974: 
                   16975: =back
                   16976: 
                   16977: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16978: utility to create a configuration.db file on a domain's primary library server 
                   16979: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16980: -- corresponding values are authentication type (internal, krb4, krb5,
                   16981: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   16982: will be available. Values are retrieved from cache (if current), unless the
                   16983: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16984: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16985: 
                   16986: Typical usage:
1.943     raeburn  16987: 
1.1240    raeburn  16988: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16989: 
1.243     albertel 16990: =back
                   16991: 
                   16992: =head2 Network Status Functions
                   16993: 
                   16994: =over 4
1.191     harris41 16995: 
                   16996: =item *
                   16997: 
1.1137    raeburn  16998: dirlist() : return directory list based on URI (first arg).
                   16999: 
                   17000: Inputs: 1 required, 5 optional.
                   17001: 
                   17002: =over
                   17003: 
                   17004: =item 
                   17005: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   17006: 
                   17007: =item
                   17008: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   17009: 
                   17010: =item
                   17011: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   17012: 
                   17013: =item
                   17014: $getpropath - boolean: 1 if prepend path using &propath(). 
                   17015: 
                   17016: =item
                   17017: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   17018: 
                   17019: =item 
                   17020: $alternateRoot - path to prepend in place of path from $uri.
                   17021: 
                   17022: =back
                   17023: 
                   17024: Returns: Array of up to two items.
                   17025: 
                   17026: =over
                   17027: 
                   17028: a reference to an array of files/subdirectories
                   17029: 
                   17030: =over
                   17031: 
                   17032: Each element in the array of files/subdirectories is a & separated list of
                   17033: item name and the result of running stat on the item.  If dirlist was requested
                   17034: for a file instead of a directory, the item name will be ''. For a directory 
                   17035: listing, if the item is a metadata file, the element will end &N&M 
                   17036: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   17037: default copyright set (1).  
                   17038: 
                   17039: =back
                   17040: 
                   17041: a scalar containing error condition (if encountered).
                   17042: 
                   17043: =over
                   17044: 
                   17045: =item 
                   17046: no_host (no homeserver identified for $username:$domain).
                   17047: 
                   17048: =item 
                   17049: no_such_host (server contacted for listing not identified as valid host).
                   17050: 
                   17051: =item 
                   17052: con_lost (connection to remote server failed).
                   17053: 
                   17054: =item 
                   17055: refused (invalid $username:$domain received on lond side).
                   17056: 
                   17057: =item 
                   17058: no_such_dir (directory at specified path on lond side does not exist). 
                   17059: 
                   17060: =item 
                   17061: empty (directory at specified path on lond side is empty).
                   17062: 
                   17063: =over
                   17064: 
                   17065: This is currently not encountered because the &ls3, &ls2, 
                   17066: &ls (_handler) routines on the lond side do not filter out
                   17067: . and .. from a directory listing. 
                   17068: 
                   17069: =back
                   17070: 
                   17071: =back
                   17072: 
                   17073: =back
1.191     harris41 17074: 
                   17075: =item *
                   17076: 
1.243     albertel 17077: spareserver() : find server with least workload from spare.tab
                   17078: 
1.986     foxr     17079: 
                   17080: =item *
                   17081: 
                   17082: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   17083: if there is no corresponding loncapa host.
                   17084: 
1.243     albertel 17085: =back
                   17086: 
1.986     foxr     17087: 
1.243     albertel 17088: =head2 Apache Request
                   17089: 
                   17090: =over 4
1.191     harris41 17091: 
                   17092: =item *
                   17093: 
1.243     albertel 17094: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   17095: localhost, posts hash
                   17096: 
                   17097: =back
                   17098: 
                   17099: =head2 Data to String to Data
                   17100: 
                   17101: =over 4
1.191     harris41 17102: 
                   17103: =item *
                   17104: 
1.243     albertel 17105: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   17106: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 17107: 
                   17108: =item *
                   17109: 
1.243     albertel 17110: hashref2str($hashref) : convert a hashref into a string complete with
                   17111: escaping and '=' and '&' separators, supports elements that are
                   17112: arrayrefs and hashrefs
1.191     harris41 17113: 
                   17114: =item *
                   17115: 
1.243     albertel 17116: arrayref2str($arrayref) : convert an arrayref into a string complete
                   17117: with escaping and '&' separators, supports elements that are arrayrefs
                   17118: and hashrefs
1.191     harris41 17119: 
                   17120: =item *
                   17121: 
1.243     albertel 17122: str2hash($string) : convert string to hash using unescaping and
                   17123: splitting on '=' and '&', supports elements that are arrayrefs and
                   17124: hashrefs
1.191     harris41 17125: 
                   17126: =item *
                   17127: 
1.243     albertel 17128: str2array($string) : convert string to hash using unescaping and
                   17129: splitting on '&', supports elements that are arrayrefs and hashrefs
                   17130: 
                   17131: =back
                   17132: 
                   17133: =head2 Logging Routines
                   17134: 
                   17135: 
                   17136: These routines allow one to make log messages in the lonnet.log and
                   17137: lonnet.perm logfiles.
1.191     harris41 17138: 
1.1119    foxr     17139: =over 4
                   17140: 
1.191     harris41 17141: =item *
                   17142: 
1.243     albertel 17143: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 17144: 
                   17145: =item *
                   17146: 
1.243     albertel 17147: logthis() : append message to the normal lonnet.log file, it gets
                   17148: preiodically rolled over and deleted.
1.191     harris41 17149: 
                   17150: =item *
                   17151: 
1.243     albertel 17152: logperm() : append a permanent message to lonnet.perm.log, this log
                   17153: file never gets deleted by any automated portion of the system, only
                   17154: messages of critical importance should go in here.
                   17155: 
1.1119    foxr     17156: 
1.243     albertel 17157: =back
                   17158: 
                   17159: =head2 General File Helper Routines
                   17160: 
                   17161: =over 4
1.191     harris41 17162: 
                   17163: =item *
                   17164: 
1.481     raeburn  17165: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   17166: (a) files in /uploaded
                   17167:   (i) If a local copy of the file exists - 
                   17168:       compares modification date of local copy with last-modified date for 
                   17169:       definitive version stored on home server for course. If local copy is 
                   17170:       stale, requests a new version from the home server and stores it. 
                   17171:       If the original has been removed from the home server, then local copy 
                   17172:       is unlinked.
                   17173:   (ii) If local copy does not exist -
                   17174:       requests the file from the home server and stores it. 
                   17175:   
                   17176:   If $caller is 'uploadrep':  
                   17177:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   17178:     for request for files originally uploaded via DOCS. 
                   17179:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   17180:   
                   17181:   Otherwise:
                   17182:      This indicates a call from the content generation phase of the request.
                   17183:      -  returns the entire contents of the file or -1.
                   17184:      
                   17185: (b) files in /res
                   17186:    - returns the entire contents of a file or -1; 
                   17187:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 17188: 
1.712     albertel 17189: 
                   17190: =item *
                   17191: 
                   17192: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   17193:                   reference
                   17194: 
                   17195: returns either a stat() list of data about the file or an empty list
                   17196: if the file doesn't exist or couldn't find out about it (connection
                   17197: problems or user unknown)
                   17198: 
1.191     harris41 17199: =item *
                   17200: 
1.243     albertel 17201: filelocation($dir,$file) : returns file system location of a file
                   17202: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   17203: directory that relative $file lookups are to looked in ($dir of /a/dir
                   17204: and a file of ../bob will become /a/bob)
1.191     harris41 17205: 
                   17206: =item *
                   17207: 
                   17208: hreflocation($dir,$file) : returns file system location or a URL; same as
                   17209: filelocation except for hrefs
                   17210: 
                   17211: =item *
                   17212: 
1.1261    raeburn  17213: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   17214: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 17215: 
1.243     albertel 17216: =back
                   17217: 
1.608     albertel 17218: =head2 Usererfile file routines (/uploaded*)
                   17219: 
                   17220: =over 4
                   17221: 
                   17222: =item *
                   17223: 
                   17224: userfileupload(): main rotine for putting a file in a user or course's
                   17225:                   filespace, arguments are,
                   17226: 
1.620     albertel 17227:  formname - required - this is the name of the element in $env where the
1.608     albertel 17228:            filename, and the contents of the file to create/modifed exist
1.620     albertel 17229:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   17230:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  17231:  context - if coursedoc, store the file in the course of the active role
                   17232:              of the current user; 
                   17233:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   17234:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 17235:  subdir - required - subdirectory to put the file in under ../userfiles/
                   17236:          if undefined, it will be placed in "unknown"
                   17237: 
                   17238:  (This routine calls clean_filename() to remove any dangerous
                   17239:  characters from the filename, and then calls finuserfileupload() to
                   17240:  complete the transaction)
                   17241: 
                   17242:  returns either the url of the uploaded file (/uploaded/....) if successful
                   17243:  and /adm/notfound.html if unsuccessful
                   17244: 
                   17245: =item *
                   17246: 
                   17247: clean_filename(): routine for cleaing a filename up for storage in
                   17248:                  userfile space, argument is:
                   17249: 
                   17250:  filename - proposed filename
                   17251: 
                   17252: returns: the new clean filename
                   17253: 
                   17254: =item *
                   17255: 
1.1090    raeburn  17256: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 17257: userspace, probably shouldn't be called directly
                   17258: 
                   17259:   docuname: username or courseid of destination for the file
                   17260:   docudom: domain of user/course of destination for the file
                   17261:   formname: same as for userfileupload()
1.1090    raeburn  17262:   fname: filename (including subdirectories) for the file
                   17263:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  17264:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  17265:   allfiles: reference to hash used to store objects found by parser
                   17266:   codebase: reference to hash used for codebases of java objects found by parser
                   17267:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   17268:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   17269:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   17270:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   17271:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   17272:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  17273:   mimetype: reference to scalar to accommodate mime type determined
                   17274:             from File::MMagic if $parser = parse.
1.608     albertel 17275: 
                   17276:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  17277:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   17278:  was 'overwrite').
                   17279:  
1.608     albertel 17280: 
                   17281: =item *
                   17282: 
                   17283: renameuserfile(): renames an existing userfile to a new name
                   17284: 
                   17285:   Args:
                   17286:    docuname: username or courseid of destination for the file
                   17287:    docudom: domain of user/course of destination for the file
                   17288:    old: current file name (including any subdirs under userfiles)
                   17289:    new: desired file name (including any subdirs under userfiles)
                   17290: 
                   17291: =item *
                   17292: 
                   17293: mkdiruserfile(): creates a directory is a userfiles dir
                   17294: 
                   17295:   Args:
                   17296:    docuname: username or courseid of destination for the file
                   17297:    docudom: domain of user/course of destination for the file
                   17298:    dir: dir to create (including any subdirs under userfiles)
                   17299: 
                   17300: =item *
                   17301: 
                   17302: removeuserfile(): removes a file that exists in userfiles
                   17303: 
                   17304:   Args:
                   17305:    docuname: username or courseid of destination for the file
                   17306:    docudom: domain of user/course of destination for the file
                   17307:    fname: filname to delete (including any subdirs under userfiles)
                   17308: 
                   17309: =item *
                   17310: 
                   17311: removeuploadedurl(): convience function for removeuserfile()
                   17312: 
                   17313:   Args:
                   17314:    url:  a full /uploaded/... url to delete
                   17315: 
1.747     albertel 17316: =item * 
                   17317: 
                   17318: get_portfile_permissions():
                   17319:   Args:
                   17320:     domain: domain of user or course contain the portfolio files
                   17321:     user: name of user or num of course contain the portfolio files
                   17322:   Returns:
                   17323:     hashref of a dump of the proper file_permissions.db
                   17324:    
                   17325: 
                   17326: =item * 
                   17327: 
                   17328: get_access_controls():
                   17329: 
                   17330: Args:
                   17331:   current_permissions: the hash ref returned from get_portfile_permissions()
                   17332:   group: (optional) the group you want the files associated with
                   17333:   file: (optional) the file you want access info on
                   17334: 
                   17335: Returns:
1.749     raeburn  17336:     a hash (keys are file names) of hashes containing
                   17337:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   17338:         values are XML containing access control settings (see below) 
1.747     albertel 17339: 
                   17340: Internal notes:
                   17341: 
1.749     raeburn  17342:  access controls are stored in file_permissions.db as key=value pairs.
                   17343:     key -> path to file/file_name\0uniqueID:scope_end_start
                   17344:         where scope -> public,guest,course,group,domains or users.
                   17345:               end -> UNIX time for end of access (0 -> no end date)
                   17346:               start -> UNIX time for start of access
                   17347: 
                   17348:     value -> XML description of access control
                   17349:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   17350:             <start></start>
                   17351:             <end></end>
                   17352: 
                   17353:             <password></password>  for scope type = guest
                   17354: 
                   17355:             <domain></domain>     for scope type = course or group
                   17356:             <number></number>
                   17357:             <roles id="">
                   17358:              <role></role>
                   17359:              <access></access>
                   17360:              <section></section>
                   17361:              <group></group>
                   17362:             </roles>
                   17363: 
                   17364:             <dom></dom>         for scope type = domains
                   17365: 
                   17366:             <users>             for scope type = users
                   17367:              <user>
                   17368:               <uname></uname>
                   17369:               <udom></udom>
                   17370:              </user>
                   17371:             </users>
                   17372:            </scope> 
                   17373:               
                   17374:  Access data is also aggregated for each file in an additional key=value pair:
                   17375:  key -> path to file/file_name\0accesscontrol 
                   17376:  value -> reference to hash
                   17377:           hash contains key = value pairs
                   17378:           where key = uniqueID:scope_end_start
                   17379:                 value = UNIX time record was last updated
                   17380: 
                   17381:           Used to improve speed of look-ups of access controls for each file.  
                   17382:  
                   17383:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   17384: 
1.1198    raeburn  17385: =item *
                   17386: 
1.749     raeburn  17387: modify_access_controls():
                   17388: 
                   17389: Modifies access controls for a portfolio file
                   17390: Args
                   17391: 1. file name
                   17392: 2. reference to hash of required changes,
                   17393: 3. domain
                   17394: 4. username
                   17395:   where domain,username are the domain of the portfolio owner 
                   17396:   (either a user or a course) 
                   17397: 
                   17398: Returns:
                   17399: 1. result of additions or updates ('ok' or 'error', with error message). 
                   17400: 2. result of deletions ('ok' or 'error', with error message).
                   17401: 3. reference to hash of any new or updated access controls.
                   17402: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   17403:    key = integer (inbound ID)
1.1198    raeburn  17404:    value = uniqueID
                   17405: 
                   17406: =item *
                   17407: 
                   17408: get_timebased_id():
                   17409: 
                   17410: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   17411: course via the Course Editor (e.g., folders, composite pages, 
                   17412: group bulletin boards).
                   17413: 
                   17414: Args: (first three required; six others optional)
                   17415: 
                   17416: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   17417:    docssequence, or name of group
                   17418: 
                   17419: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   17420:    e.g., num, boardids
                   17421: 
                   17422: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   17423:    file will be named nohist_namespace.db
                   17424: 
                   17425: 4. cdom: domain of course; default is current course domain from %env
                   17426: 
                   17427: 5. cnum: course number; default is current course number from %env
                   17428: 
                   17429: 6. idtype: set to concat if an additional digit is to be appended to the 
                   17430:    unix timestamp to form the suffix, if the plain timestamp is already
                   17431:    in use.  Default is to not do this, but simply increment the unix 
                   17432:    timestamp by 1 until a unique key is obtained.
                   17433: 
                   17434: 7. who: holder of locking key; defaults to user:domain for user.
                   17435: 
                   17436: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   17437:    retrying); default is 3.
                   17438: 
                   17439: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   17440: 
                   17441: Returns:
                   17442: 
                   17443: 1. suffix obtained (numeric)
                   17444: 
                   17445: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17446: 
                   17447: 3. error: contains (localized) error message if an error occurred.
                   17448: 
1.747     albertel 17449: 
1.608     albertel 17450: =back
                   17451: 
1.243     albertel 17452: =head2 HTTP Helper Routines
                   17453: 
                   17454: =over 4
                   17455: 
1.191     harris41 17456: =item *
                   17457: 
                   17458: escape() : unpack non-word characters into CGI-compatible hex codes
                   17459: 
                   17460: =item *
                   17461: 
                   17462: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17463: 
1.243     albertel 17464: =back
                   17465: 
                   17466: =head1 PRIVATE SUBROUTINES
                   17467: 
                   17468: =head2 Underlying communication routines (Shouldn't call)
                   17469: 
                   17470: =over 4
                   17471: 
                   17472: =item *
                   17473: 
                   17474: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17475: 
                   17476: =item *
                   17477: 
                   17478: reply() : uses subreply to send a message to remote machine, logs all failures
                   17479: 
                   17480: =item *
                   17481: 
                   17482: critical() : passes a critical message to another server; if cannot
                   17483: get through then place message in connection buffer directory and
                   17484: returns con_delayed, if incapable of saving message, returns
                   17485: con_failed
                   17486: 
                   17487: =item *
                   17488: 
                   17489: reconlonc() : tries to reconnect lonc client processes.
                   17490: 
                   17491: =back
                   17492: 
                   17493: =head2 Resource Access Logging
                   17494: 
                   17495: =over 4
                   17496: 
                   17497: =item *
                   17498: 
                   17499: flushcourselogs() : flush (save) buffer logs and access logs
                   17500: 
                   17501: =item *
                   17502: 
                   17503: courselog($what) : save message for course in hash
                   17504: 
                   17505: =item *
                   17506: 
                   17507: courseacclog($what) : save message for course using &courselog().  Perform
                   17508: special processing for specific resource types (problems, exams, quizzes, etc).
                   17509: 
1.191     harris41 17510: =item *
                   17511: 
                   17512: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17513: as a PerlChildExitHandler
1.243     albertel 17514: 
                   17515: =back
                   17516: 
                   17517: =head2 Other
                   17518: 
                   17519: =over 4
                   17520: 
                   17521: =item *
                   17522: 
                   17523: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17524: 
                   17525: =back
                   17526: 
                   17527: =cut
1.877     foxr     17528: 

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